fe-deploy-kit 0.0.0-stage → 1.0.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/src/build.js ADDED
@@ -0,0 +1,241 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawn } from 'node:child_process';
4
+ import { DeployError } from './core/flow.js';
5
+
6
+ const LOCKFILES = [
7
+ ['pnpm-lock.yaml', 'pnpm'],
8
+ ['yarn.lock', 'yarn'],
9
+ ['bun.lockb', 'bun'],
10
+ ['bun.lock', 'bun'],
11
+ ['package-lock.json', 'npm'],
12
+ ['npm-shrinkwrap.json', 'npm']
13
+ ];
14
+
15
+ /** 按 lockfile 猜包管理器。 */
16
+ export function detectPackageManager(projectRoot) {
17
+ for (const [lockfile, manager] of LOCKFILES) {
18
+ if (fs.existsSync(path.join(projectRoot, lockfile))) return manager;
19
+ }
20
+ return 'npm';
21
+ }
22
+
23
+ function readPackageJson(dir) {
24
+ const file = path.join(dir, 'package.json');
25
+ if (!fs.existsSync(file)) return null;
26
+ try {
27
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * 把配置里的 build 解析成一条可执行命令。
35
+ * 支持:显式命令字符串 / [cmd, ...args] / { command, args } / vite 模式 / 自动读取 package.json 的 build 脚本。
36
+ * @returns {null | {command: string, args: string[], shell: boolean, cwd: string, env: Record<string,string>, label: string, timeoutMs: number}}
37
+ */
38
+ export function resolveBuildCommand(config) {
39
+ const build = config.build;
40
+ if (!build || build.skip) return null;
41
+
42
+ const cwd = build.cwd ?? config.projectRoot;
43
+ const env = { ...process.env, ...build.env };
44
+ const base = { shell: false, args: [], cwd, env, timeoutMs: build.timeoutMs };
45
+
46
+ if (typeof build.command === 'function') {
47
+ const resolved = build.command({ projectRoot: config.projectRoot, cwd, env });
48
+ if (!resolved) return null;
49
+ if (typeof resolved === 'string') return { ...base, shell: true, command: resolved, label: resolved };
50
+ if (typeof resolved.command === 'string') {
51
+ return { ...base, shell: Boolean(resolved.shell), command: resolved.command, args: resolved.args ?? [], label: resolved.label ?? resolved.command };
52
+ }
53
+ throw new DeployError('build.command 函数必须返回字符串或 { command, args }');
54
+ }
55
+
56
+ // 兼容老配置的 buildMode:vite build --mode <mode>
57
+ if (!build.command && build.mode) {
58
+ const viteBin = path.join(cwd, 'node_modules', 'vite', 'bin', 'vite.js');
59
+ if (!fs.existsSync(viteBin)) {
60
+ throw new DeployError(
61
+ `找不到本地 vite:${viteBin}\n` +
62
+ `buildMode 需要项目内安装 vite。请先在 ${cwd} 安装依赖,或改用 build.command 指定构建命令。`
63
+ );
64
+ }
65
+ return {
66
+ ...base,
67
+ command: process.execPath,
68
+ args: [viteBin, 'build', '--mode', build.mode],
69
+ label: `vite build --mode ${build.mode}`
70
+ };
71
+ }
72
+
73
+ if (Array.isArray(build.command)) {
74
+ const [command, ...args] = build.command;
75
+ return { ...base, command, args: [...args, ...(build.args ?? [])], label: build.command.join(' ') };
76
+ }
77
+
78
+ if (typeof build.command === 'string') {
79
+ return { ...base, shell: true, command: build.command, label: build.command };
80
+ }
81
+
82
+ // 自动模式:package.json 的 build 脚本
83
+ const pkg = readPackageJson(cwd);
84
+ if (!pkg?.scripts?.build) {
85
+ throw new DeployError(
86
+ `没有找到构建命令:${path.join(cwd, 'package.json')} 里没有 scripts.build。\n` +
87
+ '请在配置里显式写 build.command,或把 build 设为 false 跳过构建。'
88
+ );
89
+ }
90
+ const manager = build.packageManager ?? detectPackageManager(cwd);
91
+ const label = `${manager} run build`;
92
+ return { ...base, shell: true, command: label, label };
93
+ }
94
+
95
+ /** 执行构建命令(继承 stdio,输出直接给用户看)。 */
96
+ export async function runBuild(plan, { log } = {}) {
97
+ const { command, args, shell, cwd, env, label, timeoutMs } = plan;
98
+ log?.step(`构建:${label}`);
99
+ await new Promise((resolve, reject) => {
100
+ const child = spawn(command, args, { cwd, env, shell, stdio: 'inherit' });
101
+ let settled = false;
102
+ const timer =
103
+ timeoutMs > 0
104
+ ? setTimeout(() => {
105
+ if (settled) return;
106
+ settled = true;
107
+ child.kill('SIGTERM');
108
+ reject(new DeployError(`构建超时(${Math.round(timeoutMs / 1000)}s):${label}`));
109
+ }, timeoutMs)
110
+ : null;
111
+
112
+ child.on('error', err => {
113
+ if (settled) return;
114
+ settled = true;
115
+ if (timer) clearTimeout(timer);
116
+ reject(new DeployError(`启动构建失败:${err.message}`));
117
+ });
118
+ child.on('exit', code => {
119
+ if (settled) return;
120
+ settled = true;
121
+ if (timer) clearTimeout(timer);
122
+ if (code === 0) resolve();
123
+ else reject(new DeployError(`构建失败,退出码 ${code}(${label})`));
124
+ });
125
+ });
126
+ }
127
+
128
+ /** 递归收集产物目录里的文件与子目录(相对路径 + 绝对路径 + 大小)。 */
129
+ export function buildLocalTree(distDir) {
130
+ if (!fs.existsSync(distDir)) throw new DeployError(`还没有构建产物:${distDir}`);
131
+ const files = [];
132
+ const dirs = [];
133
+ const walk = (abs, rel) => {
134
+ const entries = fs.readdirSync(abs, { withFileTypes: true });
135
+ for (const entry of entries) {
136
+ const childAbs = path.join(abs, entry.name);
137
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
138
+ if (entry.isDirectory()) {
139
+ dirs.push({ rel: childRel, abs: childAbs });
140
+ walk(childAbs, childRel);
141
+ } else if (entry.isFile()) {
142
+ files.push({ rel: childRel, abs: childAbs, size: fs.statSync(childAbs).size });
143
+ } else {
144
+ throw new DeployError(`产物里有不支持的文件类型(符号链接?):${childRel}`);
145
+ }
146
+ }
147
+ };
148
+ walk(distDir, '');
149
+ return {
150
+ root: distDir,
151
+ files: files.toSorted((a, b) => a.rel.localeCompare(b.rel)),
152
+ dirs: dirs.toSorted((a, b) => a.rel.localeCompare(b.rel))
153
+ };
154
+ }
155
+
156
+ function globToRegExp(pattern) {
157
+ let out = '';
158
+ for (let index = 0; index < pattern.length; index += 1) {
159
+ const char = pattern[index];
160
+ if (char === '*') {
161
+ if (pattern[index + 1] === '*') {
162
+ out += '.*';
163
+ index += 1;
164
+ } else {
165
+ out += '[^/]*';
166
+ }
167
+ } else if (char === '?') {
168
+ out += '[^/]';
169
+ } else {
170
+ out += char.replace(/[.+^${}()|[\]\\]/g, '\\$&');
171
+ }
172
+ }
173
+ return new RegExp(`^${out}$`);
174
+ }
175
+
176
+ /** 简单的 glob 匹配:`dir/**` 匹配整棵子树,`.env.*` 匹配同名文件,`**\/*.map` 匹配任意层级。 */
177
+ export function matchForbidden(rel, pattern) {
178
+ if (pattern.endsWith('/**')) {
179
+ const prefix = pattern.slice(0, -3);
180
+ return rel === prefix || rel.startsWith(`${prefix}/`);
181
+ }
182
+ if (pattern.startsWith('**/')) {
183
+ const tail = pattern.slice(3);
184
+ const regex = globToRegExp(tail);
185
+ return rel.split('/').some(segment => regex.test(segment)) || regex.test(rel);
186
+ }
187
+ const regex = globToRegExp(pattern);
188
+ if (!pattern.includes('/')) return rel.split('/').some(segment => regex.test(segment));
189
+ return regex.test(rel);
190
+ }
191
+
192
+ /**
193
+ * 校验产物目录:存在、非空、index.html 有效、包含预期资源前缀、没有禁止上传的文件。
194
+ * @returns {{files: any[], dirs: any[], bytes: number, mapFiles: string[], distDir: string}}
195
+ */
196
+ export function validateDist(config, { log } = {}) {
197
+ const distDir = config.distDir;
198
+ const rules = config.validate;
199
+ if (!fs.existsSync(distDir)) throw new DeployError(`还没有构建产物:${distDir}(先构建,或用 --skip-build 前确认 dist 存在)`);
200
+
201
+ const indexPath = path.join(distDir, 'index.html');
202
+ if (rules.requireIndexHtml) {
203
+ if (!fs.existsSync(indexPath)) throw new DeployError(`构建产物里没有 index.html:${indexPath}`);
204
+ const html = fs.readFileSync(indexPath, 'utf8');
205
+ if (!html.trim()) throw new DeployError('index.html 是空的,构建可能失败了');
206
+ if (rules.assetPrefix && !html.includes(rules.assetPrefix)) {
207
+ throw new DeployError(
208
+ `index.html 里找不到资源前缀 ${rules.assetPrefix},产物可能不是生产构建,或者部署路径(base)配置不一致。`
209
+ );
210
+ }
211
+ }
212
+
213
+ const localTree = buildLocalTree(distDir);
214
+ if (localTree.files.length === 0) throw new DeployError(`${distDir} 是空目录`);
215
+
216
+ const forbidden = [];
217
+ const mapFiles = [];
218
+ for (const file of localTree.files) {
219
+ if (file.rel.endsWith('.map')) mapFiles.push(file.rel);
220
+ for (const pattern of rules.forbidPatterns) {
221
+ if (matchForbidden(file.rel, pattern)) forbidden.push(`${file.rel}(命中 ${pattern})`);
222
+ }
223
+ }
224
+ if (forbidden.length > 0) {
225
+ throw new DeployError(
226
+ `产物里出现了不该上传的文件,已停止:\n - ${forbidden.slice(0, 10).join('\n - ')}\n` +
227
+ '如果确实需要上传,请调整配置里的 validate.forbidPatterns。'
228
+ );
229
+ }
230
+ if (rules.warnOnSourcemaps && mapFiles.length > 0) {
231
+ log?.warn(`注意:产物里有 ${mapFiles.length} 个 sourcemap,会把源码结构暴露给浏览器,建议关掉 sourcemap 再发布。`);
232
+ }
233
+
234
+ return {
235
+ distDir,
236
+ files: localTree.files,
237
+ dirs: localTree.dirs,
238
+ bytes: localTree.files.reduce((sum, file) => sum + file.size, 0),
239
+ mapFiles
240
+ };
241
+ }
package/src/cli.js ADDED
@@ -0,0 +1,171 @@
1
+ #!/usr/bin/env node
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { loadConfig } from './config.js';
6
+ import { DeployError } from './core/flow.js';
7
+ import { GuardError } from './core/guard.js';
8
+ import { runCheck, runInit, runListBackups, runRollback } from './commands.js';
9
+ import { runDeploy } from './deploy.js';
10
+ import { releaseActiveLock } from './state.js';
11
+
12
+ const require = createRequire(import.meta.url);
13
+ const pkg = require('../package.json');
14
+
15
+ const COMMANDS = new Set(['deploy', 'check', 'rollback', 'list-backups', 'init']);
16
+ const VALUE_FLAGS = new Set(['--config', '--cwd', '--backup', '--keep']);
17
+
18
+ const HELP = `
19
+ fe-deploy — 前端项目一键部署(构建 → 校验 → SFTP 上传 → 备份 → 原子切换 → 回滚)
20
+
21
+ 用法:
22
+ npx fe-deploy 构建并部署(默认命令)
23
+ npx fe-deploy check 只检查配置/连接/远程目录,不做任何修改
24
+ npx fe-deploy rollback 回滚到最近一次备份
25
+ npx fe-deploy rollback --backup 20261126-180000 回滚到指定备份
26
+ npx fe-deploy list-backups 列出服务器上的备份
27
+ npx fe-deploy init 交互式生成 deploy.config.json
28
+
29
+ 选项:
30
+ --config <文件> 配置文件路径(默认自动查找 deploy.config.json / .mjs / deploy/deploy.config.json)
31
+ --cwd <目录> 在指定目录下查找配置、执行构建(默认当前目录)
32
+ --skip-build 跳过构建,直接使用现有产物
33
+ --dry-run 只检查并打印计划,不上传、不修改服务器
34
+ -y, --yes 跳过确认(首次信任服务器指纹仍需交互确认)
35
+ --force 允许非空但不是站点目录的目标,或接管过期的部署锁
36
+ --trust-fingerprint 首次连接(或指纹变化)时信任并记录服务器指纹
37
+ --create-remote-path 首次部署时允许在 remoteRoot 下创建 remotePath
38
+ --backup <时间戳> 回滚时指定备份(默认 latest)
39
+ --keep <数量> 覆盖配置里的 keepBackups(保留几份备份)
40
+ --json 以 JSON 输出结果(适合 CI)
41
+ -v, --verbose 输出更多调试信息
42
+ -V, --version 显示版本
43
+ -h, --help 显示本帮助
44
+
45
+ 凭据来源(不会写进任何文件):
46
+ 私钥:配置 keyFile;口令用环境变量 DEPLOY_KEY_PASSPHRASE
47
+ 密码:环境变量 DEPLOY_PASSWORD,或部署时交互输入(不回显)
48
+ `;
49
+
50
+ export function parseArgs(argv) {
51
+ const options = {
52
+ command: 'deploy',
53
+ config: null,
54
+ cwd: process.cwd(),
55
+ skipBuild: false,
56
+ dryRun: false,
57
+ yes: false,
58
+ force: false,
59
+ verbose: false,
60
+ json: false,
61
+ trustFingerprint: false,
62
+ createRemotePath: false,
63
+ keep: null,
64
+ backup: null,
65
+ help: false,
66
+ version: false
67
+ };
68
+ let positionalSeen = false;
69
+
70
+ for (let index = 0; index < argv.length; index += 1) {
71
+ const arg = argv[index];
72
+ const [flag, inlineValue] = arg.includes('=') ? [arg.slice(0, arg.indexOf('=')), arg.slice(arg.indexOf('=') + 1)] : [arg, null];
73
+
74
+ if (VALUE_FLAGS.has(flag)) {
75
+ const value = inlineValue ?? argv[(index += 1)];
76
+ if (value === undefined || value.startsWith('--')) throw new GuardError(`参数 ${flag} 需要一个值`);
77
+ if (flag === '--config') options.config = value;
78
+ else if (flag === '--cwd') options.cwd = path.resolve(value);
79
+ else if (flag === '--backup') options.backup = value;
80
+ else {
81
+ const keep = Number(value);
82
+ if (!Number.isInteger(keep) || keep < 0 || keep > 50) throw new GuardError('--keep 需要 0-50 的整数');
83
+ options.keep = keep;
84
+ }
85
+ continue;
86
+ }
87
+
88
+ if (arg === '--skip-build' || arg === '--no-build') options.skipBuild = true;
89
+ else if (arg === '--dry-run') options.dryRun = true;
90
+ else if (arg === '-y' || arg === '--yes') options.yes = true;
91
+ else if (arg === '--force') options.force = true;
92
+ else if (arg === '-v' || arg === '--verbose') options.verbose = true;
93
+ else if (arg === '--json') options.json = true;
94
+ else if (arg === '--trust-fingerprint') options.trustFingerprint = true;
95
+ else if (arg === '--create-remote-path') options.createRemotePath = true;
96
+ else if (arg === '-h' || arg === '--help') options.help = true;
97
+ else if (arg === '-V' || arg === '--version') options.version = true;
98
+ else if (arg.startsWith('-')) throw new GuardError(`不认识的参数:${arg}(--help 查看用法)`);
99
+ else {
100
+ if (positionalSeen) throw new GuardError(`多余的参数:${arg}`);
101
+ if (!COMMANDS.has(arg)) throw new GuardError(`不认识的命令:${arg}(可用:${[...COMMANDS].join(' / ')})`);
102
+ options.command = arg;
103
+ positionalSeen = true;
104
+ }
105
+ }
106
+ return options;
107
+ }
108
+
109
+ export async function main(argv = process.argv.slice(2)) {
110
+ const options = parseArgs(argv);
111
+ if (options.help) {
112
+ console.log(HELP.trim());
113
+ return 0;
114
+ }
115
+ if (options.version) {
116
+ console.log(pkg.version);
117
+ return 0;
118
+ }
119
+
120
+ if (options.command === 'init') {
121
+ const result = await runInit({ cwd: options.cwd, configPath: options.config, options });
122
+ if (options.json) console.log(JSON.stringify(result, null, 2));
123
+ return 0;
124
+ }
125
+
126
+ let config = await loadConfig(options.config ?? undefined, { cwd: options.cwd });
127
+ if (options.keep !== null) config = { ...config, keepBackups: options.keep };
128
+
129
+ const runners = {
130
+ deploy: runDeploy,
131
+ check: runCheck,
132
+ rollback: runRollback,
133
+ 'list-backups': runListBackups
134
+ };
135
+ const runner = runners[options.command];
136
+ if (!runner) throw new GuardError(`不认识的命令:${options.command}`);
137
+
138
+ const result = await runner(config, options);
139
+ if (options.json) {
140
+ console.log(JSON.stringify(result, null, 2));
141
+ } else if (result?.cancelled) {
142
+ console.log('没有做任何修改');
143
+ }
144
+ return 0;
145
+ }
146
+
147
+ const isMain = process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href;
148
+
149
+ if (isMain) {
150
+ const onInterrupt = signal => {
151
+ console.error(`\n已中断(${signal})`);
152
+ releaseActiveLock();
153
+ process.exit(130);
154
+ };
155
+ process.on('SIGINT', () => onInterrupt('SIGINT'));
156
+ process.on('SIGTERM', () => onInterrupt('SIGTERM'));
157
+
158
+ main()
159
+ .then(code => {
160
+ process.exitCode = code;
161
+ })
162
+ .catch(err => {
163
+ const known = err instanceof GuardError || err instanceof DeployError;
164
+ console.error(`\n${known ? '失败' : '意外错误'}:${err.message}`);
165
+ if (!known && err.stack) console.error(err.stack);
166
+ if (err.cause?.message) console.error(`原因:${err.cause.message}`);
167
+ process.exitCode = 1;
168
+ });
169
+ }
170
+
171
+ export { DeployError, GuardError };
@@ -0,0 +1,174 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import readline from 'node:readline/promises';
4
+ import { formatBytes } from './core/fs-ops.js';
5
+ import { DeployError, inspectBackups, metaPaths, planDeploy, rollbackRelease, verifyRemoteLayout } from './core/flow.js';
6
+ import { validateConfig } from './core/guard.js';
7
+ import { createActionLogger } from './logger.js';
8
+ import { saveConfigFile } from './config.js';
9
+ import { acquireLock } from './state.js';
10
+ import { requireConfirmation } from './prompts.js';
11
+ import { withRemote } from './ssh.js';
12
+ import { printRemotePlan, printTarget } from './deploy.js';
13
+
14
+ /** 只读检查:配置、连接、指纹、远程目录、备份列表。不做任何修改。 */
15
+ export async function runCheck(config, options = {}) {
16
+ const logger = options.logger ?? createActionLogger({ config, action: 'check', options });
17
+ logger.step('检查配置与服务器目录(只读,不做任何修改)');
18
+ printTarget(logger, config);
19
+ logger.info(`登录方式:${config.keyFile ? `私钥 ${config.keyFile}` : '密码(环境变量或交互输入)'}`);
20
+ logger.info(`构建命令:${config.build.skip ? '(跳过构建)' : config.build.command ? String(config.build.command) : '自动(package.json scripts.build)'}`);
21
+ logger.info(`产物目录:${config.distDir}`);
22
+
23
+ const summary = await withRemote({
24
+ config,
25
+ logger,
26
+ options,
27
+ fingerprintStore: options.fingerprintStore,
28
+ action: async remote => {
29
+ const layout = await verifyRemoteLayout({ remote, config, createRemotePath: options.createRemotePath });
30
+ logger.info(`remoteRoot 实际路径:${layout.rootReal}`);
31
+ if (layout.targetReal) logger.info(`remotePath 实际路径:${layout.targetReal}`);
32
+
33
+ const plan = await planDeploy({ remote, config, localTree: { files: [], dirs: [] }, force: true });
34
+ printRemotePlan({ log: logger, plan, config });
35
+ if (plan.targetExists && plan.targetEntryCount > 0 && !plan.looksLikeSite) {
36
+ logger.warn('目标目录里没有 index.html,部署时会被拦住,确认目录没填错。');
37
+ }
38
+
39
+ const backups = await inspectBackups({ remote, config });
40
+ if (backups.length === 0) {
41
+ logger.info('服务器上还没有备份(首次部署)');
42
+ } else {
43
+ logger.info(`可用备份 ${backups.length} 份:`);
44
+ for (const backup of backups.slice(0, 5)) {
45
+ logger.info(` ${backup.stamp} ${backup.files} 个文件 ${formatBytes(backup.bytes)}`);
46
+ }
47
+ }
48
+ logger.ok('检查通过,可以执行部署');
49
+ return {
50
+ rootReal: layout.rootReal,
51
+ targetReal: layout.targetReal,
52
+ targetExists: plan.targetExists,
53
+ looksLikeSite: plan.looksLikeSite,
54
+ backups: backups.map(item => item.stamp)
55
+ };
56
+ }
57
+ });
58
+
59
+ return { ok: true, action: 'check', ...summary };
60
+ }
61
+
62
+ /** 回滚到指定备份(默认最近一份)。 */
63
+ export async function runRollback(config, options = {}) {
64
+ const logger = options.logger ?? createActionLogger({ config, action: 'rollback', options });
65
+ const releaseLock = acquireLock({ stateDir: config.stateDir, logger, force: options.force });
66
+ try {
67
+ const summary = await withRemote({
68
+ config,
69
+ logger,
70
+ options,
71
+ fingerprintStore: options.fingerprintStore,
72
+ action: async remote => {
73
+ await verifyRemoteLayout({ remote, config });
74
+ const backups = await inspectBackups({ remote, config });
75
+ if (backups.length === 0) throw new DeployError('服务器上没有可用的备份,无法回滚');
76
+
77
+ const target = options.backup ?? 'latest';
78
+ logger.info(`可用备份:${backups.map(backup => backup.stamp).join('、')}`);
79
+ logger.info(`准备回滚到:${target === 'latest' ? `最新备份(${backups[0].stamp})` : target}`);
80
+
81
+ const confirmed = await requireConfirmation('回滚会把当前版本替换掉,确认继续?输入 yes 继续:', options);
82
+ if (!confirmed) {
83
+ logger.warn('已取消,没有做任何修改');
84
+ return { cancelled: true };
85
+ }
86
+
87
+ const result = await rollbackRelease({ remote, config, log: logger.info, targetStamp: target });
88
+ logger.ok(`回滚完成:已恢复备份 ${result.stamp} 的 ${result.restoredFiles} 个条目`);
89
+ return { cancelled: false, ...result };
90
+ }
91
+ });
92
+ return { ok: true, action: 'rollback', ...summary };
93
+ } finally {
94
+ releaseLock?.();
95
+ }
96
+ }
97
+
98
+ /** 列出服务器上的备份(只读)。 */
99
+ export async function runListBackups(config, options = {}) {
100
+ const logger = options.logger ?? createActionLogger({ config, action: 'list-backups', options });
101
+ const backups = await withRemote({
102
+ config,
103
+ logger,
104
+ options,
105
+ fingerprintStore: options.fingerprintStore,
106
+ action: async remote => {
107
+ const list = await inspectBackups({ remote, config });
108
+ if (list.length === 0) {
109
+ logger.info('服务器上还没有备份');
110
+ return [];
111
+ }
112
+ logger.info(`备份目录:${metaPaths(config).backupsDir}`);
113
+ for (const backup of list) {
114
+ logger.info(` ${backup.stamp} ${String(backup.files).padStart(4)} 个文件 ${formatBytes(backup.bytes)}`);
115
+ }
116
+ return list;
117
+ }
118
+ });
119
+ return { ok: true, action: 'list-backups', backups };
120
+ }
121
+
122
+ /** 交互式生成配置文件。 */
123
+ export async function runInit({ cwd = process.cwd(), configPath = null, options = {} } = {}) {
124
+ const logger = options.logger ?? createActionLogger({ config: { logDir: path.join(cwd, '.deploy', 'logs') }, action: 'init', options });
125
+ const file = configPath ? path.resolve(cwd, configPath) : path.join(cwd, 'deploy.config.json');
126
+
127
+ if (!process.stdin.isTTY) {
128
+ throw new DeployError(
129
+ 'init 需要交互式终端。请手动创建 deploy.config.json(可复制 examples/deploy.config.example.json),或用 JS 配置。'
130
+ );
131
+ }
132
+ if (fs.existsSync(file)) {
133
+ const overwrite = await new Promise(resolve => {
134
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
135
+ rl.question(`配置文件已存在(${file}),要覆盖吗?(yes/no) `)
136
+ .then(answer => resolve(/^(y|yes|是)$/i.test(answer.trim())))
137
+ .finally(() => rl.close());
138
+ });
139
+ if (!overwrite) {
140
+ logger.warn('已取消');
141
+ return { ok: true, action: 'init', cancelled: true, configPath: file };
142
+ }
143
+ }
144
+
145
+ const ask = async (question, fallback) => {
146
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
147
+ try {
148
+ const answer = (await rl.question(question)).trim();
149
+ return answer === '' ? fallback : answer;
150
+ } finally {
151
+ rl.close();
152
+ }
153
+ };
154
+
155
+ const host = await ask('服务器地址(IP 或域名):', '');
156
+ const port = Number(await ask('SSH 端口 [22]:', '22'));
157
+ const username = await ask('登录账号:', '');
158
+ const remoteRoot = await ask('项目在服务器上的父目录(只允许在该目录内操作),例如 /www/wwwroot/example.com:', '');
159
+ const remotePath = await ask('前端产物目录(必须在上一目录内),例如 /www/wwwroot/example.com/console:', '');
160
+ const keep = Number(await ask('保留几份备份 [5]:', '5'));
161
+
162
+ const config = validateConfig({
163
+ host,
164
+ port: Number.isInteger(port) ? port : 22,
165
+ username,
166
+ remoteRoot,
167
+ remotePath,
168
+ keepBackups: Number.isInteger(keep) ? keep : 5
169
+ });
170
+ saveConfigFile(file, config);
171
+ logger.ok(`已写入配置文件:${file}`);
172
+ logger.info('下一步:运行 npx fe-deploy check 检查连接与目录(会显示服务器指纹让你确认)');
173
+ return { ok: true, action: 'init', cancelled: false, configPath: file };
174
+ }