refactor(tools): 发布工具统一到 tools(前后端同时发布 + git 约束 + 共享配置)

- 新增 tools TypeScript 发布 CLI:deploy / deploy:backend / deploy:frontend / rollback / init
- 删除 backend/script 与 frontend/scripts 旧发布脚本,前后端 npm scripts 转发到 tools
- 发布配置独立为 tools/config/deploy.config.local.cjs(模板入库,真实配置与生产 env 不入库)
- 发布受限于 git:工作区有未提交改动默认中止(--allow-dirty 放行),版本记录含 commit/branch
- 后端配置集中到 <deployRoot>/shared-config,本地 env 发布时覆盖共享配置;端口由 EGG_PORT 注入
- 前端服务器端脚本迁至 tools/remote,失败时清理未上线版本目录
- .gitignore 改为忽略 tools 本地配置与临时发布包

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-10-30 23:04:54 +08:00
parent 5908cacdf5
commit 406e5f3b58
37 changed files with 2519 additions and 1290 deletions

11
.gitignore vendored
View File

@ -11,10 +11,13 @@ coverage/
.nyc_output/
# 上传的文件资源(本地磁盘,不入库)
uploads/
# 后端真实部署配置(含服务器地址与 SSH 私钥路径,不入库;
# 模板见 backend/config/deploy.config.example.cjs)
backend/config/deploy.config.local.cjs
# 后端发布脚本的本地临时工作目录(发布包/文件清单)
# 真实部署配置(含服务器地址与 SSH 私钥路径,不入库;模板见 tools/config/*.example.*)
tools/config/deploy.config.local.cjs
# 生产环境变量本机权威副本(发布时覆盖服务端 shared-config,不入库)
tools/config/env.production.local
# 发布工具的本地临时工作目录(发布包/文件清单)
tools/temp/
# 早期发布脚本留在 backend 下的临时工作目录(历史遗留,不入库)
backend/temp/
# 导出任务生成的运行期文件(backend/upload/exports/…,不入库)
backend/upload/

View File

@ -1,94 +0,0 @@
'use strict';
/**
* 后端部署配置模板(此文件提交 git,供复制使用)
*
* 真实配置请复制为同目录下的 config/deploy.config.local.cjs 并填写实际值;
* 该文件已被 .gitignore 排除,**不要提交**(内含服务器地址与 SSH 私钥路径)。
*
* 发布模型(双实例蓝绿,与 WMS 后端一致):
* <deployRoot>/v1、<deployRoot>/v2 两套代码目录,每次发布交替部署另一套
* <deployRoot>/current.md 当前活跃版本(内容为 v1 或 v2)
* <deployRoot>/nginx-upstream.conf Nginx 反代目标:proxy_pass http://127.0.0.1:<端口>;
* 需要站点配置里 include 它(见下方「Nginx 前置」)
* <deployRoot>/.env 服务器端真实环境变量(密钥/数据库等),不入库、
* 发布时按需复制到各版本目录
* <deployRoot>/.deploy/ 发布工作目录(incoming 上传包、state 状态文件)
*
* Nginx 前置(仅首次,站点 api.oms.gztbyc.com):
* 把反向代理 `location /` 里的 `proxy_pass http://127.0.0.1:6090;` 换成
* `include /www/wwwroot/api.oms.gztbyc.com/nginx-upstream.conf;`
* 之后每次发布只需改写该文件并 reload,即可实现零中断切换。
* (若不改,发布脚本会在切换 upstream 时告警:新版实例已起在另一个端口,
* 但站点仍指向旧端口,需要人工处理。)
*
* 服务器端环境变量(仅首次,需手工创建一次):
* /www/wwwroot/api.oms.gztbyc.com/.env —— 真实配置,不入库
* 可从本地 backend/.env 复制,并注意:
* - MYSQL_HOST / MYSQL_PORT / MYSQL_USER / MYSQL_PASSWORD / MYSQL_DATABASE:生产数据库
* - REDIS_HOST / REDIS_PORT / REDIS_PASSWORD
* - JWT_SECRET:生产必须单独设置
* - UPLOAD_DIR=/www/wwwroot/api.oms.gztbyc.com/uploads
* (上传文件必须放在 deployRoot 下、版本目录之外,v1/v2 才能共用同一份文件)
* - OMS_CALLBACK_BASE_URL=http://api.oms.gztbyc.com (可选,用于对外展示回调地址)
* 发布时若目标版本目录没有 .env,会自动从该文件复制一份(各版本目录各自保留副本,
* 已存在则不覆盖)。
*/
module.exports = {
production: {
// —— SSH 连接 ——
host: '112.124.21.102',
port: 22,
username: 'root',
// SSH 私钥:可用绝对路径,或相对 backend 根目录的路径
privateKeyPath: 'C:/Users/lfmingren/.ssh/112.124.21.102_id_ed25519',
sshOptions: [ 'StrictHostKeyChecking=accept-new' ],
// —— 发布目录 ——
deployRoot: '/www/wwwroot/api.oms.gztbyc.com',
// —— 双实例端口(v1 / v2);nginx-upstream.conf 指向当前活跃版本的端口 ——
ports: { v1: 6090, v2: 6091 },
// —— 版本目录内需要跨发布保留的目录/文件(清理旧代码时不会删除)——
// node_modules 保留可让 npm install 增量安装;如需每次全新安装,去掉它即可
// .env 必须保留:每个版本目录的 .env 里写着本实例的 EGG_PORT(v1=6090 / v2=6091),
// 被清理掉后会从 deployRoot/.env 复制一份(那份是 v1 的端口),导致 v2 起在 6090 上
sharedDirs: [ 'logs', 'run', 'node_modules', '.env' ],
// —— 发布包内容(相对 backend 根目录,`**` 表示该目录下全部内容)——
// 说明:.env / uploads / logs / run 等已被 .gitignore 忽略,git ls-files 不会列出,
// 这里再写进 deployExcludePaths 作为兜底。
deployIncludePaths: [
'.sequelizerc',
'app.js',
'app/**',
'config/**',
'database/**',
'package.json',
'package-lock.json',
],
deployExcludePaths: [
'config/deploy.config.local.cjs',
'config/deploy.config.example.cjs',
'.env',
'.env.*',
'uploads/**',
'logs/**',
'run/**',
'temp/**',
'test/**',
'swagger.json',
],
// —— 启动 / 安装命令 ——
// 若需要在服务器上跑迁移(npm run migration:up)、或希望 npx sequelize-cli 可用,
// 把 installCommand 改成 'npm install'(会一并装 devDependencies)
installCommand: 'npm install --production',
// 实例端口由 config/config.local.js 的 EGG_PORT 决定(默认 6090),
// 双实例发布时请在各版本目录的 .env 里分别写 EGG_PORT(v1=6090、v2=6091)
startCommand: 'npm start',
// 健康检查:实例启动后轮询 http://127.0.0.1:<端口><healthCheckPath>
healthCheckPath: '/',
},
};

View File

@ -18,10 +18,12 @@
"migration:create": "sequelize-cli migration:generate --name",
"swagger:export": "node scripts/export-swagger.js",
"deploy": "npm run deploy:prod",
"deploy:prod": "node ./script/deploy-remote.cjs production",
"deploy:init": "node ./script/init-deploy-config.cjs",
"deploy:prod": "npm --prefix ../tools run deploy --",
"deploy:backend": "npm --prefix ../tools run deploy:backend --",
"deploy:init": "npm --prefix ../tools run init",
"rollback": "npm run rollback:prod",
"rollback:prod": "node ./script/rollback-remote.cjs production"
"rollback:prod": "npm --prefix ../tools run rollback --",
"rollback:backend": "npm --prefix ../tools run rollback:backend --"
},
"dependencies": {
"dotenv": "^17.4.2",

View File

@ -1,498 +0,0 @@
'use strict';
/**
* 后端发布公共库(配置加载/校验、SSH/SCP 封装、发布包构建、远端脚本片段)
*
* 发布模型:双实例蓝绿(参考 WMS 后端)
* <deployRoot>/{v1,v2} 两套代码目录,发布时交替部署
* <deployRoot>/current.md 当前活跃版本(v1 / v2)
* <deployRoot>/nginx-upstream.conf Nginx 反代目标(proxy_pass http://127.0.0.1:<端口>;)
* <deployRoot>/.deploy/incoming 上传的发布包
* <deployRoot>/.deploy/state 状态文件(当前发布版本号)
*/
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
/** backend 根目录(本文件在 backend/script 下) */
const ROOT = path.resolve(__dirname, '..');
const LOCAL_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.local.cjs');
const EXAMPLE_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.example.cjs');
const DEFAULT_ENV = 'production';
const VERSIONS = [ 'v1', 'v2' ];
/** 发布包默认包含的文件(相对 backend 根目录) */
const DEFAULT_INCLUDE_PATHS = [
'app.js',
'app/**',
'config/**',
'database/**',
'package.json',
'package-lock.json',
];
/** 发布包默认排除(叠加在 include 之上) */
const DEFAULT_EXCLUDE_PATHS = [
'config/deploy.config.local.cjs',
'config/deploy.config.example.cjs',
'.env',
'.env.*',
'uploads/**',
'logs/**',
'run/**',
'temp/**',
'test/**',
'swagger.json',
];
/**
* bash 单引号字符串里的单引号转义(' → '\'')
* @param {String} value 原始值
* @return {String} 可安全放进单引号中的字符串
*/
function quoteForBash(value) {
return `'${String(value).replace(/'/g, "'\\''")}'`;
}
/**
* 执行本地命令
* @param {String} command 命令
* @param {String[]} args 参数
* @param {Object} [options] 选项(cwd / stdio)
* @return {String} stdout(trim 后)
*/
function runCommand(command, args, options = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd || ROOT,
encoding: 'utf8',
stdio: options.stdio || 'pipe',
shell: false,
});
if (result.error) throw result.error;
if (result.status !== 0) {
const stderr = (result.stderr || '').trim();
const stdout = (result.stdout || '').trim();
throw new Error(stderr || stdout || `${command} 退出码 ${result.status}`);
}
return (result.stdout || '').trim();
}
/**
* 检查本地命令是否存在(不存在时给出安装提示)
* @param {String} command 命令名
* @param {String} installHint 安装提示
* @return {void}
*/
function ensureCommandAvailable(command, installHint) {
const result = spawnSync(command, [], { cwd: ROOT, encoding: 'utf8', stdio: 'pipe', shell: false });
if (result.error && result.error.code === 'ENOENT') {
throw new Error(`${command} 不可用。${installHint}`);
}
}
/** @return {String} yyyyMMddHHmmss 时间戳 */
function getNowStamp() {
const now = new Date();
const pad = value => String(value).padStart(2, '0');
return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
}
/** @return {String} 本地临时工作目录 backend/temp/deploy(自动创建) */
function ensureTempDeployDir() {
const tempDir = path.join(ROOT, 'temp', 'deploy');
fs.mkdirSync(tempDir, { recursive: true });
return tempDir;
}
/**
* 是否为未填写的占位值
* @param {String} value 值
* @return {Boolean} 是占位值返回 true
*/
function isPlaceholder(value) {
if (!value) return true;
return String(value).includes('__FILL_');
}
/**
* 校验并补齐配置默认值
* @param {Object} config 原始配置
* @param {String} envName 环境名
* @return {Object} 规范化后的配置
*/
function normalizeDeployConfig(config, envName) {
const sshOptions = Array.isArray(config.sshOptions) ? [ ...config.sshOptions ] : [];
const guardedOptions = [
'IdentitiesOnly=yes',
'PreferredAuthentications=publickey',
'PubkeyAuthentication=yes',
'PasswordAuthentication=no',
'KbdInteractiveAuthentication=no',
'BatchMode=yes',
'ConnectTimeout=10',
];
for (const option of guardedOptions) {
const key = option.split('=')[0];
if (!sshOptions.some(item => new RegExp(`^${key}=`, 'i').test(item))) sshOptions.push(option);
}
const deployRoot = String(config.deployRoot || '/www/wwwroot/api.oms.gztbyc.com').replace(/\/+$/, '');
const ports = config.ports || {};
return {
envName,
host: config.host,
port: Number(config.port || 22),
username: config.username,
// 支持绝对路径(Windows 下如 C:/Users/x/.ssh/id_ed25519)与相对 backend 根目录的路径
privateKeyPath: config.privateKeyPath ? path.resolve(ROOT, config.privateKeyPath) : '',
deployRoot,
ports: { v1: Number(ports.v1 || 6090), v2: Number(ports.v2 || 6091) },
incomingDir: `${deployRoot}/.deploy/incoming`,
stateDir: `${deployRoot}/.deploy/state`,
sharedDirs: Array.isArray(config.sharedDirs) ? config.sharedDirs : [ 'logs', 'run', 'node_modules' ],
deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length
? config.deployIncludePaths
: DEFAULT_INCLUDE_PATHS,
deployExcludePaths: Array.isArray(config.deployExcludePaths) && config.deployExcludePaths.length
? config.deployExcludePaths
: DEFAULT_EXCLUDE_PATHS,
installCommand: config.installCommand || 'npm install --production',
startCommand: config.startCommand || 'npm start',
healthCheckPath: config.healthCheckPath || '/',
sshOptions,
};
}
/**
* 校验配置必填项
* @param {Object} config 原始配置
* @param {String} configPath 配置文件路径
* @param {String} envName 环境名
* @return {void}
*/
function validateDeployConfig(config, configPath, envName) {
if (!config) throw new Error(`${configPath} 中未找到 ${envName} 配置。`);
const missing = [];
if (isPlaceholder(config.host)) missing.push('host');
if (isPlaceholder(config.username)) missing.push('username');
if (isPlaceholder(config.privateKeyPath)) missing.push('privateKeyPath');
if (missing.length) {
throw new Error(`请先完善配置字段: ${missing.join(', ')}。配置文件: ${configPath}`);
}
const resolvedPrivateKeyPath = path.resolve(ROOT, config.privateKeyPath);
if (!fs.existsSync(resolvedPrivateKeyPath)) {
throw new Error(`SSH 私钥不存在: ${resolvedPrivateKeyPath}。请修正 ${configPath} 中的 privateKeyPath。`);
}
}
/**
* 加载本地部署配置
* @param {String} [envName] 环境名,默认 production
* @return {Object} 规范化后的配置
*/
function loadDeployConfig(envName = DEFAULT_ENV) {
if (!fs.existsSync(LOCAL_CONFIG_PATH)) {
throw new Error(`缺少本地部署配置 ${LOCAL_CONFIG_PATH}。请复制 ${EXAMPLE_CONFIG_PATH} 为 deploy.config.local.cjs 并填写 SSH 信息。`);
}
delete require.cache[require.resolve(LOCAL_CONFIG_PATH)];
const loaded = require(LOCAL_CONFIG_PATH);
const config = loaded[envName];
validateDeployConfig(config, LOCAL_CONFIG_PATH, envName);
return normalizeDeployConfig(config, envName);
}
/**
* 构造 ssh/scp 公共参数
* @param {Object} config 部署配置
* @return {String[]} 参数数组
*/
function buildSshBaseArgs(config) {
const args = [ '-p', String(config.port), '-i', config.privateKeyPath ];
for (const option of config.sshOptions) args.push('-o', option);
return args;
}
/**
* 在服务器上执行 bash 脚本(通过 bash -lc,保证加载登录环境里的 node/npm)
* @param {Object} config 部署配置
* @param {String} remoteScript 脚本内容
* @param {Object} [options] 选项(stdio)
* @return {String} 输出
*/
function runSsh(config, remoteScript, options = {}) {
const args = [
...buildSshBaseArgs(config),
`${config.username}@${config.host}`,
`bash -lc ${quoteForBash(remoteScript)}`,
];
return runCommand('ssh', args, { stdio: options.stdio || 'inherit' });
}
/**
* 上传文件到服务器
* @param {Object} config 部署配置
* @param {String} localPath 本地路径
* @param {String} remotePath 远端路径
* @return {String} 输出
*/
function runScp(config, localPath, remotePath) {
const args = [ '-P', String(config.port), '-i', config.privateKeyPath ];
for (const option of config.sshOptions) args.push('-o', option);
args.push(localPath, `${config.username}@${config.host}:${remotePath}`);
return runCommand('scp', args, { stdio: 'inherit' });
}
/**
* 判断路径是否命中规则(`a/**` 匹配 a 及其全部子项,其余为精确匹配)
* @param {String} filePath 相对路径
* @param {String} rule 规则
* @return {Boolean} 命中返回 true
*/
function pathMatchesRule(filePath, rule) {
const normalizedPath = String(filePath || '').replace(/\\/g, '/');
const normalizedRule = String(rule || '').replace(/\\/g, '/').trim();
if (!normalizedRule) return false;
if (normalizedRule.endsWith('/**')) {
const prefix = normalizedRule.slice(0, -3);
return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`);
}
return normalizedPath === normalizedRule;
}
/**
* 列出可发布文件:以 git 的视角取文件(天然排除 .gitignore 里的 .env / uploads 等),
* 再按 include / exclude 规则过滤
* @param {Object} config 部署配置
* @return {String[]} 相对 backend 根目录的文件列表
*/
function listDeployableFiles(config) {
const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ], { cwd: ROOT });
return Array.from(new Set(
output
.split(/\r?\n/)
.map(item => item.trim())
.filter(Boolean)
.filter(item => !item.startsWith('.git/'))
.filter(item => fs.existsSync(path.join(ROOT, item)))
.filter(item => config.deployIncludePaths.some(rule => pathMatchesRule(item, rule)))
.filter(item => !config.deployExcludePaths.some(rule => pathMatchesRule(item, rule)))
));
}
/**
* 构建本地发布包(tar.gz)
* @param {String} stamp 时间戳
* @param {Object} config 部署配置
* @return {{ archivePath: String, fileCount: Number }} 发布包路径与文件数
*/
function buildArchive(stamp, config) {
const tempDir = ensureTempDeployDir();
const listPath = path.join(tempDir, `deploy-files-${stamp}.txt`);
const archivePath = path.join(tempDir, `release-${stamp}.tar.gz`);
const files = listDeployableFiles(config);
if (!files.length) throw new Error('未找到可发布文件(请检查 deployIncludePaths 配置)。');
fs.writeFileSync(listPath, `${files.join('\n')}\n`, 'utf8');
runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit', cwd: ROOT });
return { archivePath, fileCount: files.length };
}
/**
* 生成远端清理守卫:`find . -mindepth 1 -maxdepth 1 <守卫> -exec rm -rf {} +`
* 保留 .deploy 与 sharedDirs(logs / run / node_modules 等)
* @param {String[]} sharedDirs 需保留的目录名
* @return {String} find 命令的守卫参数
*/
function buildRemoteCleanupGuard(sharedDirs) {
const preserved = [ '.deploy', ...sharedDirs ];
return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' ');
}
/**
* 生成「按目录停止 egg 进程」的远端脚本行:
* 通过 ps 匹配命令行里的版本目录 + node,先 kill 再 kill -9 兜底。
* 不用 `npm run stop`(egg-scripts 按 title 停止,v1/v2 同 title 会互相误杀)。
* @param {String} dirPath 目标目录绝对路径
* @param {String} label 日志前缀
* @return {String[]} 脚本行
*/
function buildScopedEggStopLines(dirPath, label) {
const matchNode = '$2 == "node" || $2 ~ /\\/node$/';
const awkProgram = `index($0, root) && (${matchNode}) { print $1 }`;
return [
`TARGET_DIR=${quoteForBash(dirPath)}`,
`TARGET_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" ${quoteForBash(awkProgram)})`,
'if [ -z "$TARGET_PIDS" ]; then',
` echo "${label}_NONE"`,
'else',
` echo "${label} $TARGET_PIDS"`,
' kill $TARGET_PIDS || true',
' sleep 5',
` REMAIN_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" ${quoteForBash(awkProgram)})`,
' if [ -n "$REMAIN_PIDS" ]; then',
` echo "${label}_FORCE $REMAIN_PIDS"`,
' kill -9 $REMAIN_PIDS || true',
' fi',
'fi',
];
}
/**
* 读取远端当前活跃版本
* @param {Object} config 部署配置
* @return {String} 'v1' / 'v2';尚未初始化(无 current.md)时返回空字符串
*/
function readRemoteCurrentVersion(config) {
const currentMdPath = `${config.deployRoot}/current.md`;
const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`;
const output = String(runSsh(config, script, { stdio: 'pipe' }) || '').replace(/\r/g, '').trim();
if (!output) return '';
if (!VERSIONS.includes(output)) {
throw new Error(`远端 ${currentMdPath} 内容无效: "${output}",期望 v1 或 v2。`);
}
return output;
}
/**
* 取另一个版本标识(v1 ↔ v2)
* @param {String} version 当前版本,为空时返回首次部署使用的 v1
* @return {String} 目标版本
*/
function otherVersion(version) {
if (!version) return 'v1';
if (!VERSIONS.includes(version)) throw new Error(`版本标识无效: ${version}`);
return version === 'v1' ? 'v2' : 'v1';
}
/**
* 取版本对应端口
* @param {Object} config 部署配置
* @param {String} version 版本标识
* @return {Number} 端口
*/
function portOf(config, version) {
if (!VERSIONS.includes(version)) throw new Error(`版本标识无效: ${version}`);
return config.ports[version];
}
/**
* 生成「释放指定端口」的远端脚本行(结束占用该端口的残留进程)
* @param {Number} port 端口
* @return {String[]} 脚本行
*/
function buildFreePortLines(port) {
return [
`TARGET_PORT=${port}`,
'PORT_PID=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)',
'if [ -n "$PORT_PID" ]; then',
' echo "端口 $TARGET_PORT 被进程 $PORT_PID 占用,先停止..."',
' kill "$PORT_PID" 2>/dev/null || true',
' sleep 5',
' PORT_PID_CHECK=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)',
' if [ -n "$PORT_PID_CHECK" ]; then',
' echo "端口 $TARGET_PORT 仍有残留进程 $PORT_PID_CHECK,强制停止"',
' kill -9 "$PORT_PID_CHECK" 2>/dev/null || true',
' fuser -k "$TARGET_PORT/tcp" 2>/dev/null || true',
' fi',
'else',
' echo "端口 $TARGET_PORT 空闲"',
'fi',
];
}
/**
* 生成「启动实例」的远端脚本行(后台运行,输出重定向到启动日志)
* @param {String} dirPath 版本目录
* @param {String} startCommand 启动命令(如 npm start)
* @param {String} logPath 启动日志路径
* @return {String[]} 脚本行
*/
function buildStartInstanceLines(dirPath, startCommand, logPath) {
return [
`cd ${quoteForBash(dirPath)}`,
`nohup bash -lc ${quoteForBash(startCommand)} > ${quoteForBash(logPath)} 2>&1 < /dev/null &`,
`echo "已启动实例: ${dirPath},启动日志: ${logPath}"`,
];
}
/**
* 生成「健康检查」的远端脚本行(轮询 http://127.0.0.1:<端口><路径>)
* @param {Number} port 端口
* @param {String} healthPath 检查路径
* @param {String} label 日志标签
* @param {Number} [attempts] 重试次数
* @param {Number} [interval] 重试间隔秒数
* @return {String[]} 脚本行
*/
function buildHealthCheckLines(port, healthPath, label, attempts = 10, interval = 2) {
return [
`TARGET_PORT=${port}`,
`HEALTH_PATH=${quoteForBash(healthPath)}`,
`for attempt in $(seq 1 ${attempts}); do`,
' if curl -fsS --connect-timeout 2 --max-time 3 "http://127.0.0.1:$TARGET_PORT$HEALTH_PATH" >/dev/null 2>&1; then',
` echo "健康检查通过: ${label} 已就绪(端口 $TARGET_PORT)"`,
' break',
' fi',
` if [ "$attempt" -eq ${attempts} ]; then`,
` echo "健康检查超时: ${label}(端口 $TARGET_PORT)未就绪" >&2`,
' exit 1',
' fi',
` sleep ${interval}`,
'done',
];
}
/**
* 生成「切换 Nginx upstream 并 reload」的远端脚本行
* @param {String} upstreamPath upstream 文件路径
* @param {Number} port 目标端口
* @return {String[]} 脚本行
*/
function buildNginxSwitchLines(upstreamPath, port) {
return [
`printf 'proxy_pass http://127.0.0.1:%s;\\n' ${port} > ${quoteForBash(upstreamPath)}`,
'nginx -t && nginx -s reload',
`echo "Nginx upstream 已切换至 127.0.0.1:${port}"`,
];
}
module.exports = {
ROOT,
VERSIONS,
DEFAULT_ENV,
LOCAL_CONFIG_PATH,
EXAMPLE_CONFIG_PATH,
buildArchive,
buildFreePortLines,
buildHealthCheckLines,
buildNginxSwitchLines,
buildRemoteCleanupGuard,
buildScopedEggStopLines,
buildSshBaseArgs,
buildStartInstanceLines,
ensureCommandAvailable,
ensureTempDeployDir,
getNowStamp,
listDeployableFiles,
loadDeployConfig,
otherVersion,
pathMatchesRule,
portOf,
quoteForBash,
readRemoteCurrentVersion,
runCommand,
runScp,
runSsh,
};

View File

@ -1,202 +0,0 @@
'use strict';
/**
* 后端发布脚本(双实例蓝绿)
*
* npm run deploy # 等价 npm run deploy:prod
* npm run deploy:prod
*
* 流程:
* 1. 本地按 git 文件清单打发布包(不含 .env / uploads / logs 等)
* 2. 读取远端 current.md,确定目标版本(v1 ↔ v2 交替;首次发布用 v1)
* 3. 上传到 <deployRoot>/.deploy/incoming,清理目标版本目录(保留 logs/run/node_modules)后解压
* 4. 补齐 .env、安装生产依赖、释放目标端口、启动新实例
* 5. 健康检查通过后切换 Nginx upstream(nginx -t && nginx -s reload)
* 6. 停止旧实例、记录当前发布版本号
* 健康检查失败:回滚 current.md、杀掉新实例,旧实例不受影响(线上不中断)
*/
const fs = require('node:fs');
const path = require('node:path');
const {
ROOT,
buildArchive,
buildFreePortLines,
buildHealthCheckLines,
buildNginxSwitchLines,
buildRemoteCleanupGuard,
buildScopedEggStopLines,
buildStartInstanceLines,
ensureCommandAvailable,
getNowStamp,
loadDeployConfig,
otherVersion,
portOf,
quoteForBash,
readRemoteCurrentVersion,
runCommand,
runScp,
runSsh,
} = require('./deploy-lib.cjs');
function main() {
const envName = process.argv[2] || 'production';
const config = loadDeployConfig(envName);
ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。');
ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。');
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
// 1. 远端当前活跃版本 → 本次目标版本
const currentVersion = readRemoteCurrentVersion(config);
const targetVersion = otherVersion(currentVersion);
const targetPort = portOf(config, targetVersion);
const targetDir = `${config.deployRoot}/${targetVersion}`;
const oldDir = currentVersion ? `${config.deployRoot}/${currentVersion}` : '';
if (currentVersion) {
console.log(`远端当前活跃版本: ${currentVersion}(端口 ${portOf(config, currentVersion)})`);
} else {
console.log('远端尚未初始化(无 current.md),本次作为首次发布,落到 v1');
}
console.log(`本次发布目标: ${targetVersion} → ${targetDir}(端口 ${targetPort})`);
// 2. 本地打包
const stamp = getNowStamp();
const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]);
const releaseVersion = `v${packageJson.version || '0.0.0'}-${stamp}-${gitCommitShort}`;
const { archivePath, fileCount } = buildArchive(stamp, config);
const remoteArchive = `${config.incomingDir}/${path.basename(archivePath)}`;
console.log(`发布包已生成: ${archivePath}(${fileCount} 个文件,版本号 ${releaseVersion})`);
// 3. 远端准备目录并上传发布包
runSsh(config, [
'set -euo pipefail',
`mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.stateDir)}`,
`echo "远端目录已就绪: ${targetDir}"`,
].join('\n'));
runScp(config, archivePath, remoteArchive);
console.log(`发布包已上传: ${remoteArchive}`);
// 4. 清理目标目录 → 解压 → 补齐 .env → 安装生产依赖
const envFile = `${config.deployRoot}/.env`;
const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs);
const installScript = [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
`REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`,
`ENV_FILE=${quoteForBash(envFile)}`,
'cd "$TARGET_DIR"',
// 清理上一次遗留的代码(保留 .deploy 与 sharedDirs:logs / run / node_modules)
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"',
'rm -f "$REMOTE_ARCHIVE"',
// 服务器端真实环境变量只维护一份(<deployRoot>/.env),首次落到某版本目录时复制过去;
// 已存在则不覆盖,便于个别版本目录单独调整
'if [ ! -f "$TARGET_DIR/.env" ]; then',
' if [ -f "$ENV_FILE" ]; then',
' cp -a "$ENV_FILE" "$TARGET_DIR/.env"',
' echo "ENV_COPIED $ENV_FILE -> $TARGET_DIR/.env"',
' else',
' echo "WARN_ENV_MISSING 未找到 $ENV_FILE,请先在该文件写入生产环境变量(数据库、JWT_SECRET 等)" >&2',
' fi',
'else',
' echo "ENV_KEPT $TARGET_DIR/.env(已存在,未覆盖)"',
'fi',
config.installCommand,
].join('\n');
runSsh(config, installScript);
console.log(`远端代码已更新并安装依赖: ${targetDir}`);
// 5. 释放目标端口(防止残留进程占用导致新实例起不来)
runSsh(config, [ 'set -euo pipefail', ...buildFreePortLines(targetPort) ].join('\n'));
const startLogPath = `/tmp/oms-${targetVersion}-start.log`;
// 6. 记录 current.md 并启动新实例
runSsh(config, [
'set -euo pipefail',
`printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`,
...buildStartInstanceLines(targetDir, config.startCommand, startLogPath),
].join('\n'));
// 7. 健康检查(20 秒内轮询;失败则回滚记录并清理新实例,旧实例继续服务)
const healthCheckScript = [
'set -euo pipefail',
...buildHealthCheckLines(targetPort, config.healthCheckPath, targetVersion),
].join('\n');
try {
runSsh(config, healthCheckScript);
} catch (err) {
console.error(`[ERROR] 新实例健康检查失败: ${err.message}`);
console.error(`[ERROR] 发布中止(未切换 Nginx),请查看启动日志 ${startLogPath}`);
if (currentVersion) {
try {
runSsh(config, [
'set -euo pipefail',
`printf '%s\\n' ${quoteForBash(currentVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`,
`echo "current.md 已回滚为 ${currentVersion}"`,
].join('\n'));
} catch (revertErr) {
console.error(`[ERROR] current.md 回滚失败: ${revertErr.message}`);
}
}
try {
runSsh(config, [
'set -euo pipefail',
...buildScopedEggStopLines(targetDir, 'STOP_FAILED_NEW'),
].join('\n'));
} catch (killErr) {
console.error(`[ERROR] 清理失败的新实例出错: ${killErr.message}`);
}
console.error(`[ERROR] 发布失败: ${envName} -> ${config.username}@${config.host}:${targetDir}`);
if (currentVersion) console.error(`[ERROR] 旧实例(${currentVersion})仍在服务,线上不受影响`);
process.exit(1);
}
// 8. 切换 Nginx upstream(仅健康检查通过后执行)
const upstreamPath = `${config.deployRoot}/nginx-upstream.conf`;
try {
runSsh(config, [ 'set -euo pipefail', ...buildNginxSwitchLines(upstreamPath, targetPort) ].join('\n'));
} catch (err) {
console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`);
console.warn(`[WARN] 请人工确认 ${upstreamPath} 内容并执行 nginx -t && nginx -s reload`);
console.warn('[WARN] 若站点配置尚未 include 该文件,请先按 config/deploy.config.example.cjs 顶部说明改一次站点配置');
}
// 9. 停止旧实例
if (currentVersion) {
try {
runSsh(config, [
'set -euo pipefail',
...buildScopedEggStopLines(oldDir, 'STOP_OLD'),
`echo "旧实例 ${currentVersion} 已停止"`,
].join('\n'));
} catch (err) {
console.warn(`[WARN] 停止旧实例失败: ${err.message},请人工确认并停止 ${oldDir} 下的进程`);
}
}
// 10. 记录当前发布版本号
try {
runSsh(config, [
'set -euo pipefail',
`printf '%s\\n' ${quoteForBash(releaseVersion)} > ${quoteForBash(`${config.stateDir}/current-release.txt`)}`,
`echo "当前发布版本: ${releaseVersion}"`,
].join('\n'));
} catch (err) {
console.warn(`[WARN] 记录发布版本号失败: ${err.message}`);
}
console.log(`发布完成: ${config.username}@${config.host}:${targetDir}`);
console.log(`活跃版本: ${targetVersion}(端口 ${targetPort})`);
console.log(`发布版本号: ${releaseVersion}`);
}
main();

View File

@ -1,21 +0,0 @@
'use strict';
/**
* 初始化后端部署配置:把 config/deploy.config.example.cjs 复制为 config/deploy.config.local.cjs。
* deploy.config.local.cjs 含服务器地址与 SSH 私钥路径,已被 .gitignore 排除,不要提交。
*
* 用法:npm run deploy:init
*/
const fs = require('node:fs');
const { EXAMPLE_CONFIG_PATH, LOCAL_CONFIG_PATH } = require('./deploy-lib.cjs');
if (fs.existsSync(LOCAL_CONFIG_PATH)) {
console.log('ℹ️ config/deploy.config.local.cjs 已存在,未覆盖。');
console.log(` 如需重新生成,请先删除该文件:${LOCAL_CONFIG_PATH}`);
process.exit(0);
}
fs.copyFileSync(EXAMPLE_CONFIG_PATH, LOCAL_CONFIG_PATH);
console.log('✅ 已生成 config/deploy.config.local.cjs');
console.log(' 请按实际服务器信息确认 host / username / privateKeyPath / deployRoot / ports,然后执行 npm run deploy。');

View File

@ -1,131 +0,0 @@
'use strict';
/**
* 后端回滚脚本(双实例蓝绿:切回另一套版本目录,无需重新构建/上传)
*
* npm run rollback # 回滚到上一个版本(v1 ↔ v2)
* npm run rollback -- --to=v1 # 指定切回某个版本
*
* 流程:启动目标版本实例 → 健康检查通过 → 切换 Nginx upstream → 记录 current.md → 停止当前实例
* 目标版本目录不可用(未发布过)时会直接报错,当前实例不受影响。
*/
const {
VERSIONS,
buildFreePortLines,
buildHealthCheckLines,
buildNginxSwitchLines,
buildScopedEggStopLines,
buildStartInstanceLines,
ensureCommandAvailable,
loadDeployConfig,
otherVersion,
portOf,
quoteForBash,
readRemoteCurrentVersion,
runSsh,
} = require('./deploy-lib.cjs');
/**
* 解析 --to=v1|v2 参数
* @param {String[]} argv 参数数组
* @return {String} 目标版本(未指定时返回空字符串)
*/
function parseTargetArg(argv) {
const arg = argv.find(item => item.startsWith('--to='));
if (!arg) return '';
const value = arg.slice('--to='.length).trim();
if (!VERSIONS.includes(value)) {
throw new Error(`--to 取值无效: ${value}(支持 v1 / v2)`);
}
return value;
}
function main() {
const envName = process.argv[2] || 'production';
const config = loadDeployConfig(envName);
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
const currentVersion = readRemoteCurrentVersion(config);
if (!currentVersion) {
throw new Error(`远端 ${config.deployRoot}/current.md 不存在或为空,没有可回滚的版本(请先执行 npm run deploy)。`);
}
const targetVersion = parseTargetArg(process.argv.slice(3)) || otherVersion(currentVersion);
if (targetVersion === currentVersion) {
throw new Error(`目标版本与当前活跃版本相同(${targetVersion}),无需回滚。`);
}
const currentPort = portOf(config, currentVersion);
const targetPort = portOf(config, targetVersion);
const currentDir = `${config.deployRoot}/${currentVersion}`;
const targetDir = `${config.deployRoot}/${targetVersion}`;
const startLogPath = `/tmp/oms-${targetVersion}-start.log`;
console.log(`当前活跃版本: ${currentVersion}(端口 ${currentPort})`);
console.log(`回滚目标: ${targetVersion} → ${targetDir}(端口 ${targetPort})`);
// 1. 校验目标版本可用;缺依赖时补装
runSsh(config, [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
'if [ ! -f "$TARGET_DIR/package.json" ]; then',
' echo "目标版本目录不可用:$TARGET_DIR/package.json 不存在(该版本可能尚未发布过)" >&2',
' exit 1',
'fi',
'if [ ! -d "$TARGET_DIR/node_modules" ]; then',
' echo "目标版本缺少 node_modules,先安装依赖..."',
` ( cd "$TARGET_DIR" && ${config.installCommand} )`,
'fi',
].join('\n'));
// 2. 释放目标端口并启动目标实例
runSsh(config, [ 'set -euo pipefail', ...buildFreePortLines(targetPort) ].join('\n'));
runSsh(config, [
'set -euo pipefail',
...buildStartInstanceLines(targetDir, config.startCommand, startLogPath),
].join('\n'));
// 3. 健康检查(失败则清理刚启动的实例,当前实例继续服务)
try {
runSsh(config, [
'set -euo pipefail',
...buildHealthCheckLines(targetPort, config.healthCheckPath, targetVersion),
].join('\n'));
} catch (err) {
console.error(`[ERROR] 回滚目标健康检查失败: ${err.message}`);
console.error(`[ERROR] 回滚中止(未切换 Nginx),请查看启动日志 ${startLogPath}`);
try {
runSsh(config, [
'set -euo pipefail',
...buildScopedEggStopLines(targetDir, 'STOP_ROLLBACK_TARGET'),
].join('\n'));
} catch (killErr) {
console.error(`[ERROR] 清理回滚目标实例出错: ${killErr.message}`);
}
console.error(`[ERROR] 当前实例(${currentVersion})仍在服务,线上不受影响`);
process.exit(1);
}
// 4. 切换 Nginx upstream
const upstreamPath = `${config.deployRoot}/nginx-upstream.conf`;
try {
runSsh(config, [ 'set -euo pipefail', ...buildNginxSwitchLines(upstreamPath, targetPort) ].join('\n'));
} catch (err) {
console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`);
console.warn(`[WARN] 请人工确认 ${upstreamPath} 内容并执行 nginx -t && nginx -s reload`);
}
// 5. 记录 current.md 并停止原实例
runSsh(config, [
'set -euo pipefail',
`printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`,
...buildScopedEggStopLines(currentDir, 'STOP_ROLLED_BACK'),
`echo "current.md 已更新为 ${targetVersion}"`,
].join('\n'));
console.log(`回滚完成: 线上已切回 ${targetVersion}(端口 ${targetPort})`);
console.log(`如需再次前进,执行 npm run rollback -- --to=${currentVersion}`);
}
main();

View File

@ -7,13 +7,16 @@
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview",
"deploy": "node ./scripts/deploy.mjs",
"rollback": "node ./scripts/rollback.mjs",
"deploy:init": "node ./scripts/init-config.mjs"
"deploy": "npm --prefix ../tools run deploy --",
"deploy:frontend": "npm --prefix ../tools run deploy:frontend --",
"rollback": "npm --prefix ../tools run rollback --",
"rollback:frontend": "npm --prefix ../tools run rollback:frontend",
"deploy:init": "npm --prefix ../tools run init"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.1",
"axios": "^1.20.0",
"element-china-area-data": "^6.1.0",
"element-plus": "^2.9.1",
"pinia": "^2.3.1",
"vue": "^3.5.13",

View File

@ -1,100 +0,0 @@
# OMS 前端蓝绿发布
发布方式与 WMS 前端一致:服务器上按版本目录存放,`current` 软链接指向当前线上版本,切换是原子的,因此**发布/回滚都不中断服务**。
## 目录结构
```
frontend/
├─ scripts/
│ ├─ deploy.mjs # 本地:构建 → 打包 → 上传 → 触发远程切换
│ ├─ rollback.mjs # 本地:把 current 切回上一个版本
│ ├─ init-config.mjs # 生成本地部署配置
│ ├─ deploy.config.example.json # 配置模板(提交 git)
│ ├─ deploy.config.json # 真实配置(.gitignore 排除,禁止提交)
│ └─ remote/
│ ├─ deploy.sh # 服务器端执行:解压 → 校验 → 原子切换 → 清理
│ └─ rollback.sh # 服务器端执行:原子回滚
```
服务器上的布局(`basePath` = `/www/wwwroot/oms.gztbyc.com`):
```
/www/wwwroot/oms.gztbyc.com/
├─ releases/
│ ├─ v20260914_153000_12345/ # 各版本静态文件(index.html + assets/…)
│ └─ ...
└─ current -> releases/v2026... # 软链接,Nginx 站点根目录指向它
```
## 服务器前置条件(仅首次)
```bash
mkdir -p /www/wwwroot/oms.gztbyc.com/releases
```
宝塔面板:站点 `oms.gztbyc.com` 的**网站目录**要设为 `/www/wwwroot/oms.gztbyc.com/current`
(而不是 `.../oms.gztbyc.com`),其余 `index.html`、`/api` 反向代理到后端等配置保持不变。
不需要 `chown` 到 www 用户,但站点目录需对 ssh 用户可写(示例用 `root`)。
## 使用
```bash
cd frontend
# 首次:生成本地部署配置,然后按实际服务器信息修改
npm run deploy:init
# 发布(内部执行 npm run build → 打包 → 上传 → 原子切换)
npm run deploy
# 跳过构建,直接发布现有 dist(调试用)
npm run deploy -- --skip-build
# 回滚到上一个版本(不构建、不上传,秒级)
npm run rollback
```
## 配置项(`scripts/deploy.config.json`)
| 字段 | 说明 |
| --- | --- |
| `user` | ssh 登录用户 |
| `ip` | 服务器 IP |
| `basePath` | 站点根目录,`releases/` 与 `current` 都在其下 |
| `keepReleases` | 服务器保留的最近版本数(默认 5,超出的自动清理,不会删除 current 指向的版本) |
| `siteHost` | 发版后健康检查用的域名(本机 curl 带 Host 头访问 `https://127.0.0.1/`,仅打印状态码,不阻断发布) |
| `sshKey` | 私钥:绝对路径或 `~/.ssh` 下的文件名;留空则用 ssh 默认密钥/agent |
## 发布流程细节(`remote/deploy.sh`)
1. 解压到独立的新版本目录,**全程不触碰线上目录**
2. 校验 `index.html` 非空,且 `index.html` 中引用的 `/assets/*.js|css` 都存在,否则中止(线上版本不受影响)
3. 把最近若干个历史版本中、本版本缺失的文件并入新版本 —— 保证切换后仍停留在旧版页面的用户动态加载旧 chunk 不 404(无感切换的关键)
4. `ln -sfn` 建临时软链 + `mv -Tf` 改名,原子切换
5. 健康检查(仅提示)
6. 清理超出 `keepReleases` 的旧版本
## 注意
- `scripts/deploy.config.json` **不要提交 git**(已在 `frontend/.gitignore` 中排除),只提交 `deploy.config.example.json` 模板。
- 需要本机具备 `ssh`、`scp`、`tar`(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。
- 后端 `oms` 服务不在本脚本范围内,本脚本只发布前端静态文件。
## 前后端域名与跨域(CORS)
| 站点 | 说明 |
| --- | --- |
| `oms.gztbyc.com` | 前端静态站点,由本脚本发布(Nginx 根目录指向 `current`) |
| `api.oms.gztbyc.com` | 后端 API 站点,Nginx 反代到 egg 后端(端口 6090),接口路由前缀 `/api` |
- 前端 API 地址由构建期环境变量 `VITE_API_BASE_URL` 决定:
- 生产 `${VITE_API_BASE_URL}=http://api.oms.gztbyc.com/api`(`frontend/.env.production`)
- 开发 `VITE_API_BASE_URL=/api`(`frontend/.env.development`,由 vite dev server 代理到 `http://localhost:6090`)
- 两个域名**不同源**,跨域请求由后端 `backend/app/middleware/cors.js` 按白名单放行
(默认已含 http/https 的 `oms.gztbyc.com`,可用后端环境变量 `CORS_ORIGINS` 覆盖)。
- 后端返回的图片/头像地址是相对路径(`/api/files/raw/...`),前端渲染时由
`frontend/src/utils/media.ts` 的 `mediaUrl()` 补全为 API 站点绝对地址。
- ⚠️ 若前端站点改用 HTTPS 访问,`VITE_API_BASE_URL` 必须同步改为 `https://api.oms.gztbyc.com/api`,
否则浏览器会按「混合内容(Mixed Content)」拦截请求。

View File

@ -1,8 +0,0 @@
{
"user": "root",
"ip": "112.124.21.102",
"basePath": "/www/wwwroot/oms.gztbyc.com",
"keepReleases": 5,
"siteHost": "oms.gztbyc.com",
"sshKey": "C:\\Users\\lfmingren\\.ssh\\112.124.21.102_id_ed25519"
}

View File

@ -1,136 +0,0 @@
#!/usr/bin/env node
/**
* OMS 前端蓝绿发布脚本(Windows / macOS / Linux 通用)
*
* 发布原理:
* 1. 本地构建 dist,压缩后上传到服务器 `${basePath}/releases/<版本号>/`(全新目录,不触碰线上目录)
* 2. 服务器上解压并做完整性校验,再把历史版本的静态资源补齐(旧 chunk 不 404)
* 3. 通过 `current` 软链接「先建临时链接再 mv 改名」原子切换,切换瞬间服务不中断
* 4. 健康检查(仅提示)并清理超出保留数量的旧版本
*
* 依赖本机已安装:ssh、scp、tar(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。
*
* 用法:
* npm run deploy 构建 + 发布
* npm run deploy -- --skip-build 跳过本地构建,直接发布现有 dist(调试用)
*/
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PROJECT_ROOT = path.resolve(__dirname, '..');
// --- 配置(读取独立配置文件,该文件不纳入版本控制) ---
const CONFIG_PATH = path.join(__dirname, 'deploy.config.json');
const EXAMPLE_PATH = path.join(__dirname, 'deploy.config.example.json');
if (!existsSync(CONFIG_PATH)) {
console.error('❌ 缺少配置文件 scripts/deploy.config.json');
console.error(` 请复制 scripts/deploy.config.example.json 为 scripts/deploy.config.json 并修改其中参数。`);
console.error(` 模板路径:${EXAMPLE_PATH}`);
process.exit(1);
}
const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
// --- 配置校验 ---
const REQUIRED_KEYS = ['user', 'ip', 'basePath', 'siteHost'];
const missingKeys = REQUIRED_KEYS.filter((k) => !config[k]);
if (missingKeys.length) {
console.error(`❌ scripts/deploy.config.json 缺少必填项:${missingKeys.join(', ')}`);
console.error(' 参考 scripts/deploy.config.example.json 补齐。');
process.exit(1);
}
const SKIP_BUILD = process.argv.includes('--skip-build');
const USER = config.user;
const IP = config.ip; // 服务器 IP
const BASE_PATH = config.basePath; // 站点在服务器上的存放路径(releases/current 都在其下)
const KEEP_RELEASES = Number(config.keepReleases) > 0 ? Number(config.keepReleases) : 5; // 服务器保留的最近版本数
const SITE_HOST = config.siteHost; // 发版后健康检查域名
const LOCAL_DIST = path.join(PROJECT_ROOT, 'dist');
const SSH_KEY = resolveSshKey(config.sshKey);
const SSH_OPTS = ['-o', 'StrictHostKeyChecking=no', ...(SSH_KEY ? ['-i', SSH_KEY] : [])];
const HOST = `${USER}@${IP}`;
const TARBALL = 'dist.tar.gz';
const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const RELEASE_NAME = `v${timestamp()}_${process.pid}`; // 版本号(带 PID,避免并发/重复发布冲突)
const REMOTE_RELEASE = `${BASE_PATH}/releases/${RELEASE_NAME}`;
function timestamp() {
const d = new Date();
const p = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}_${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
}
/** sshKey 支持「绝对路径」与「~/.ssh 下的文件名」;留空则用 ssh 默认密钥/agent */
function resolveSshKey(value) {
if (!value) return '';
if (value.startsWith('~')) return path.join(os.homedir(), value.slice(1));
return path.isAbsolute(value) ? value : path.join(os.homedir(), '.ssh', value);
}
function run(cmd, args, opts = {}) {
// Windows 下 .cmd/.bat(如 npm.cmd)不能直接用 spawnSync 执行(报 EINVAL):
// 优先用 node 直接运行 npm-cli.js(无 shell、无 DEP0190 警告),否则回退到 shell: true
const isWinCmd = process.platform === 'win32' && /\.(cmd|bat)$/i.test(cmd);
let res;
if (isWinCmd) {
const npmCli = process.env.npm_execpath;
if (npmCli && /npm-cli\.js$/i.test(npmCli)) {
res = spawnSync(process.execPath, [npmCli, ...args], { stdio: 'inherit', ...opts });
} else {
res = spawnSync(cmd, args, { stdio: 'inherit', shell: true, ...opts });
}
} else {
res = spawnSync(cmd, args, { stdio: 'inherit', ...opts });
}
if (res.error) {
console.error(`❌ 无法执行命令 ${cmd}: ${res.error.message}`);
if (res.error.code === 'ENOENT') {
console.error(' 请确认本机已安装对应命令(ssh/scp/tar)。Windows 10 1803+ 自带 OpenSSH 客户端与 tar。');
}
process.exit(1);
}
if (res.status !== 0) process.exit(res.status ?? 1);
}
console.log(`🚀 开始发布 OMS 前端,版本: ${RELEASE_NAME}`);
console.log(` 目标:${HOST}:${REMOTE_RELEASE}`);
try {
// 1. 本地打包(失败立即中止,防止把坏产物发到线上)
if (SKIP_BUILD) {
console.log('⏭️ 已跳过本地构建(--skip-build)');
} else {
run(NPM, ['run', 'build'], { cwd: PROJECT_ROOT });
}
// 2. 校验本地产物完整性
if (!existsSync(path.join(LOCAL_DIST, 'index.html')) || !existsSync(path.join(LOCAL_DIST, 'assets'))) {
console.error('❌ 本地构建产物不完整(缺少 index.html 或 assets),中止发布');
process.exit(1);
}
// 3. 压缩并上传到服务器上的新版本目录(全程不触碰 current 指向的线上目录)
run('tar', ['-czf', TARBALL, '-C', LOCAL_DIST, '.'], { cwd: PROJECT_ROOT });
run('ssh', [...SSH_OPTS, HOST, `mkdir -p '${REMOTE_RELEASE}'`]);
run('scp', [...SSH_OPTS, path.join(PROJECT_ROOT, TARBALL), `${HOST}:${REMOTE_RELEASE}/${TARBALL}`]);
// 4. 远程:解压 → 校验 → 补齐旧资源 → 原子切换 → 健康检查 → 清理
const remoteScript = readFileSync(path.join(__dirname, 'remote', 'deploy.sh'), 'utf8');
run(
'ssh',
[...SSH_OPTS, HOST, `RELEASE='${REMOTE_RELEASE}' BASE='${BASE_PATH}' KEEP=${KEEP_RELEASES} HOST='${SITE_HOST}' bash -s`],
{ input: remoteScript, stdio: ['pipe', 'inherit', 'inherit'] }
);
console.log(`✨ 发布成功!当前版本: ${RELEASE_NAME}`);
} finally {
// 无论成功失败都清理本地临时压缩包
rmSync(path.join(PROJECT_ROOT, TARBALL), { force: true });
}

View File

@ -1,24 +0,0 @@
#!/usr/bin/env node
/**
* 初始化部署配置:把 scripts/deploy.config.example.json 复制为 scripts/deploy.config.json。
* deploy.config.json 含服务器/密钥信息,已被 .gitignore 排除,不要提交。
*
* 用法:npm run deploy:init
*/
import { copyFileSync, existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const EXAMPLE_PATH = path.join(__dirname, 'deploy.config.example.json');
const CONFIG_PATH = path.join(__dirname, 'deploy.config.json');
if (existsSync(CONFIG_PATH)) {
console.log('ℹ️ scripts/deploy.config.json 已存在,未覆盖。');
console.log(` 如需重新生成,请先删除该文件:${CONFIG_PATH}`);
process.exit(0);
}
copyFileSync(EXAMPLE_PATH, CONFIG_PATH);
console.log('✅ 已生成 scripts/deploy.config.json');
console.log(' 请按实际服务器信息修改其中的 user / ip / basePath / siteHost / sshKey,然后再执行 npm run deploy。');

View File

@ -1,66 +0,0 @@
#!/usr/bin/env node
/**
* OMS 前端蓝绿回滚脚本(Windows / macOS / Linux 通用)
*
* 回滚原理:把服务器上的 `current` 软链接原子切回 releases 里按时间排序的上一个版本。
* 不做构建、不重新上传,秒级完成。
*
* 依赖本机已安装:ssh(Windows 10 1803+ 自带 OpenSSH 客户端)。
*
* 用法:
* npm run rollback
*/
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// --- 配置(读取独立配置文件,该文件不纳入版本控制) ---
const CONFIG_PATH = path.join(__dirname, 'deploy.config.json');
if (!existsSync(CONFIG_PATH)) {
console.error('❌ 缺少配置文件 scripts/deploy.config.json');
console.error(' 请复制 scripts/deploy.config.example.json 为 scripts/deploy.config.json 并修改其中参数。');
process.exit(1);
}
const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
const REQUIRED_KEYS = ['user', 'ip', 'basePath'];
const missingKeys = REQUIRED_KEYS.filter((k) => !config[k]);
if (missingKeys.length) {
console.error(`❌ scripts/deploy.config.json 缺少必填项:${missingKeys.join(', ')}`);
process.exit(1);
}
const USER = config.user;
const IP = config.ip; // 服务器 IP
const BASE_PATH = config.basePath; // 站点在服务器上的存放路径
const SSH_KEY = resolveSshKey(config.sshKey);
const SSH_OPTS = ['-o', 'StrictHostKeyChecking=no', ...(SSH_KEY ? ['-i', SSH_KEY] : [])];
const HOST = `${USER}@${IP}`;
/** sshKey 支持「绝对路径」与「~/.ssh 下的文件名」;留空则用 ssh 默认密钥/agent */
function resolveSshKey(value) {
if (!value) return '';
if (value.startsWith('~')) return path.join(os.homedir(), value.slice(1));
return path.isAbsolute(value) ? value : path.join(os.homedir(), '.ssh', value);
}
console.log('⏪ 正在回滚 OMS 前端到上一个版本...');
const remoteScript = readFileSync(path.join(__dirname, 'remote', 'rollback.sh'), 'utf8');
const res = spawnSync('ssh', [...SSH_OPTS, HOST, `BASE='${BASE_PATH}' bash -s`], {
input: remoteScript,
stdio: ['pipe', 'inherit', 'inherit'],
});
if (res.error) {
console.error(`❌ 无法执行 ssh: ${res.error.message}`);
if (res.error.code === 'ENOENT') {
console.error(' 请确认本机已安装 OpenSSH 客户端(Windows 10 1803+ 自带)。');
}
process.exit(1);
}
process.exit(res.status ?? 1);

3
tools/.env.example Normal file
View File

@ -0,0 +1,3 @@
# 可选:CLI 启动时会自动加载 tools/.env;当前发布脚本不依赖环境变量,
# 需要时可复制本文件为 .env 并按需填写
# EXAMPLE_KEY=value

189
tools/DEPLOY.md Normal file
View File

@ -0,0 +1,189 @@
# OMS 发布工具(tools)
`tools/` 是前后端**统一的发布入口**:一次 `npm run deploy` 同时更新后端(Egg 双实例蓝绿)与前端
(releases 目录 + `current` 软链接),两条链路都是原子切换,线上不中断。
```
tools/
├─ src/
│ ├─ cli.ts # 命令入口(tsx 直跑,或 tsc 后 node dist/cli.js)
│ ├─ commands/ # deploy(发布)/ rollback(回滚)
│ └─ lib/ # 配置、git 约束、打包、ssh/scp、远端脚本生成
├─ config/
│ ├─ deploy.config.example.cjs # 发布配置模板(提交 git)
│ ├─ deploy.config.local.cjs # 发布配置本地真实值(.gitignore 排除)
│ ├─ env.production.example # 生产环境变量模板(本机权威副本)
│ └─ env.production.local # 生产环境变量本地真实值(.gitignore 排除)
├─ remote/ # 前端服务器端 bash 脚本(deploy.sh / rollback.sh)
├─ temp/ # 本地发布包(.gitignore 排除)
└─ DEPLOY.md
```
## 一次性准备
```bash
cd tools
npm install # tsx / typescript(发布脚本本身零运行时依赖)
npm run init # 生成 config/deploy.config.local.cjs,然后填写 SSH 等信息
```
需要本机具备 `git`、`tar`、`ssh`、`scp`(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。
## 命令
| 命令 | 说明 |
| --- | --- |
| `npm run deploy` | **前后端同时发布**:构建前端 → 打包前后端 → 上传 → 一次 SSH 完成切换 |
| `npm run deploy -- --skip-build` | 复用已有 `frontend/dist`,不重新构建 |
| `npm run deploy -- --dry-run` | 只做本地构建与打包,打印远端脚本,不连服务器(同样受 git 约束,可加 `--allow-dirty`) |
| `npm run deploy -- --allow-dirty` | 允许工作区有未提交改动时发布 |
| `npm run deploy:backend` | 只发布后端 |
| `npm run deploy:frontend` | 只发布前端 |
| `npm run rollback` | 前后端一起回滚 |
| `npm run rollback -- --to=v1` | 指定后端回滚到 v1(前端仍回上一个 releases 版本) |
| `npm run rollback -- --dry-run` | 只打印回滚脚本 |
| `npm run cli -- help` | 查看用法 |
在项目目录里也能触发(内部转发到 tools):
```bash
cd backend && npm run deploy # 前后端一起发布
cd backend && npm run deploy:backend # 只发后端
cd frontend && npm run deploy # 前后端一起发布
cd frontend && npm run deploy:frontend # 只发前端
cd frontend && npm run deploy -- --skip-build
```
> 首次在 `backend/` 或 `frontend/` 里调用前,请先在 `tools/` 执行过 `npm install`。
## 发布受限于 git
- 工作区有未提交改动时**默认中止**,并列出改动文件;确认要带改动发布可加 `--allow-dirty`
(或在配置里设 `allowDirtyGit: true`),此时版本记录会标记 `dirty: true`。
- 后端发布包严格按 `git ls-files --cached --others --exclude-standard` 生成,再按
`deployIncludePaths` / `deployExcludePaths` 过滤,天然排除 `.env`、`uploads/`、`logs/` 等未入库内容。
- 远端 `.deploy/state/versions.jsonl` 记录每次发布的 `version / commit / branch / env / dirty /
targets / frontendRelease / operator / time / files / size`,保留最近 `keepVersions` 条。
## 发布配置(独立文件)
发布配置只放在 `tools/config/deploy.config.local.cjs`,不散落在前后端项目里:
```js
module.exports = {
production: {
host, port, username, privateKeyPath, sshOptions, // SSH
allowDirtyGit: false, keepVersions: 30, keepBackups: 5,
backend: {
deployRoot, ports: { v1: 6090, v2: 6091 },
healthCheckPath, healthCheckAttempts, healthCheckInterval,
sharedDirs, deployIncludePaths, deployExcludePaths,
installCommand, startCommand, runMigrations, startTitlePrefix,
sharedConfigDir, envFile, envFileLocalPath, uploadEnvFile, // 服务端共享配置
nginxUpstreamFile, nginxReloadCommand, // Nginx
},
frontend: {
enabled, basePath, distDir, buildCommand, keepReleases, siteHost,
},
},
};
```
`backend` / `frontend` 任一段设为 `false` 即可停用对应的发布目标。
## 后端共享配置(服务的配置只有一份,本地覆盖它)
服务器上后端的运行配置集中放在 `<deployRoot>/shared-config/`:
```
<deployRoot>/shared-config/
├─ .env # 生产环境变量(数据库 / Redis / JWT_SECRET / UPLOAD_DIR …)
└─ config.*.js # 可选:不入库的服务端 Egg 配置
```
发布流程里:
1. **本地覆盖**:若本机 `tools/config/env.production.local` 存在(`envFileLocalPath` 可改),发布前先
`scp` 到 `<deployRoot>/shared-config/.env`,即本地权威副本覆盖服务端共享配置;
本机没有该文件时跳过上传,沿用服务器上现有配置。
2. **下发到实例**:发布时把 `shared-config/.env` 复制为版本目录的 `.env`,
`shared-config/config.*.js` 复制到版本目录的 `config/`,**覆盖**包内同名文件。
3. **首次迁移**:若 `shared-config/.env` 还不存在,而老部署的 `<deployRoot>/.env` 存在,会自动搬过去。
> 实例端口不再写进 `.env`:发布脚本以 `EGG_PORT=<槽位端口>` 启动实例(`dotenv` 不覆盖已存在的环境变量),
> v1/v2 共用同一份 `.env` 也不会串端口。
本地生产环境变量用 `config/env.production.example` 作为模板复制为 `config/env.production.local`,该文件已被 gitignore。
## 后端发布(双实例蓝绿)
```
<deployRoot>/
├─ v1/ v2/ # 两套代码目录,每次发布交替部署另一套
├─ current.md # 当前活跃版本(v1 / v2)
├─ nginx-upstream.conf # proxy_pass http://127.0.0.1:<端口>;
├─ shared-config/ # 共享配置(见上)
└─ .deploy/ # incoming 上传包、backups 备份、state 版本记录、logs 启动日志
```
单次远程序列:确定空闲槽位 → 释放端口 → 备份旧槽位 → 清理代码(保留 `sharedDirs`)→ 解压
→ 应用共享配置 → 安装依赖(可选迁移)→ 启动新实例 → 健康检查 → 切 Nginx upstream → 写 `current.md`
→ 停旧实例 → 清理旧备份。
健康检查失败时脚本自己停掉新实例并退出,旧实例继续服务(`current.md` / upstream 都未改动)。
### Nginx 前置(仅首次,站点 api.oms.gztbyc.com)
把反向代理 `location /` 里的 `proxy_pass http://127.0.0.1:6090;` 换成
`include /www/wwwroot/api.oms.gztbyc.com/nginx-upstream.conf;`。
### 服务器端 `.env`(仅首次,之后由 shared-config 管理)
需要包含:`MYSQL_*`、`REDIS_*`、`JWT_SECRET`、`UPLOAD_DIR=<deployRoot>/uploads`(版本目录之外,
v1/v2 共用)、可选 `OMS_CALLBACK_BASE_URL`。
## 前端发布(releases + current 软链)
```
<basePath>/
├─ releases/
│ ├─ v20261030_190028_2220/ # 各版本静态文件(index.html + assets/…)
│ └─ ...
└─ current -> releases/v2026... # 软链接,Nginx 站点根目录指向它
```
服务器前置(仅首次):`mkdir -p <basePath>/releases`,并把宝塔站点**网站目录**设为 `<basePath>/current`。
`remote/deploy.sh` 流程:解压到新版本目录(不触碰线上目录)→ 校验 `index.html` 与引用的
`/assets/*.js|css` → 合并历史版本中缺失的文件(旧 chunk 不 404)→ `ln -sfn` + `mv -Tf` 原子切换
→ 健康检查(仅提示)→ 按 `keepReleases` 清理旧版本。失败时脚本会删除未上线的版本目录。
## 前后端同时发布时的顺序
后端先完成(健康检查通过、Nginx 已切到新实例、`current.md` 已更新),再切前端 `current` 软链:
- 后端失败 → 前端完全不执行,线上保持原样;
- 后端成功、前端失败 → 后端已上线(新 API 可用),前端仍是上一版,脚本会清理失败的前端目录。
## 注意
- `tools/config/deploy.config.local.cjs`、`tools/config/env.production.local` **不要提交 git**
(根 `.gitignore` 已排除),只提交 `*.example.*` 模板。
- `tools/temp/` 是本地发布包临时目录,已被忽略(保留最近 3 个包)。
## 前后端域名与跨域(CORS)
| 站点 | 说明 |
| --- | --- |
| `oms.gztbyc.com` | 前端静态站点,由前端发布流程更新(Nginx 根目录指向 `current`) |
| `api.oms.gztbyc.com` | 后端 API 站点,Nginx 反代到 egg 后端(端口由 `nginx-upstream.conf` 决定),路由前缀 `/api` |
- 前端 API 地址由构建期环境变量 `VITE_API_BASE_URL` 决定:
- 生产 `${VITE_API_BASE_URL}=http://api.oms.gztbyc.com/api`(`frontend/.env.production`)
- 开发 `VITE_API_BASE_URL=/api`(`frontend/.env.development`,由 vite dev server 代理到 `http://localhost:6090`)
- 两个域名**不同源**,跨域请求由后端 `backend/app/middleware/cors.js` 按白名单放行
(默认已含 http/https 的 `oms.gztbyc.com`,可用后端环境变量 `CORS_ORIGINS` 覆盖)。
- 后端返回的图片/头像地址是相对路径(`/api/files/raw/...`),前端渲染时由
`frontend/src/utils/media.ts` 的 `mediaUrl()` 补全为 API 站点绝对地址。
- ⚠️ 若前端站点改用 HTTPS 访问,`VITE_API_BASE_URL` 必须同步改为 `https://api.oms.gztbyc.com/api`,
否则浏览器会按「混合内容(Mixed Content)」拦截请求。

View File

@ -0,0 +1,114 @@
'use strict';
/**
* OMS 发布配置模板(此文件提交 git,供复制使用)
*
* 使用方式:
* cd tools && npm run init # 生成 deploy.config.local.cjs
* 然后填写 SSH / 目录等真实信息
* deploy.config.local.cjs 已被 .gitignore 排除,**不要提交**(内含服务器地址与私钥路径)。
*
* 发布模型(一次发布同时更新前后端):
* 后端:<deployRoot>/{v1,v2} 双实例蓝绿 + current.md + nginx-upstream.conf
* 前端:<basePath>/releases/<版本>/ 目录 + current 软链接原子切换
*
* <deployRoot>/shared-config/ 服务端共享配置(不入库):可放 config.*.js 与 .env;
* 每次发布复制到版本目录,覆盖包内同名文件
* <deployRoot>/.deploy/ 发布工作目录:incoming 上传包、backups 备份、state 版本记录
*
* Nginx 前置(仅首次,站点 api.oms.gztbyc.com):
* 把反向代理 `location /` 里的 `proxy_pass http://127.0.0.1:6090;` 换成
* `include /www/wwwroot/api.oms.gztbyc.com/nginx-upstream.conf;`
*/
module.exports = {
production: {
// ==================== SSH ====================
host: '__FILL_SSH_HOST__',
port: 22,
username: '__FILL_SSH_USERNAME__',
// 私钥:绝对路径、~/ 开头,或相对仓库根目录的路径
privateKeyPath: '__FILL_PRIVATE_KEY_PATH__',
sshOptions: [ 'StrictHostKeyChecking=accept-new' ],
// ==================== 发布约束(受限于 git)====================
// 工作区有未提交改动时禁止发布(可用 npm run deploy -- --allow-dirty 临时放行)
allowDirtyGit: false,
// 远端保留的版本记录条数 / 备份包个数
keepVersions: 30,
keepBackups: 5,
// ==================== 后端(Egg 双实例蓝绿)====================
backend: {
deployRoot: '/www/wwwroot/api.oms.gztbyc.com',
// 双实例端口;nginx-upstream.conf 指向当前活跃版本的端口
ports: { v1: 6090, v2: 6091 },
// 新实例启动后轮询 http://127.0.0.1:<端口><healthCheckPath>
healthCheckPath: '/',
healthCheckAttempts: 10,
healthCheckInterval: 2,
// 清理旧代码时保留的目录(位于版本目录内)
// 注意:.env 不保留,每次发布都从 shared-config 重新覆盖
sharedDirs: [ 'logs', 'run', 'node_modules' ],
// 发布包内容(相对 backend 根目录,`**` 表示该目录下全部内容)
deployIncludePaths: [
'.sequelizerc',
'app.js',
'app/**',
'config/**',
'database/**',
'package.json',
'package-lock.json',
],
deployExcludePaths: [
'.env',
'.env.*',
'uploads/**',
'logs/**',
'run/**',
'temp/**',
'test/**',
'swagger.json',
],
// 远端安装 / 启动命令;实例端口由发布脚本强制注入 EGG_PORT,无需写进 .env
installCommand: 'npm install --production',
startCommand: 'npm start',
// 启动前是否执行数据库迁移(npm run migration:up,需要 installCommand 安装 devDependencies)
runMigrations: false,
startTitlePrefix: 'oms',
// ===== 服务端共享配置(后端的配置共享出来)=====
// 不写该字段则默认 <deployRoot>/shared-config;设为 '' 表示不启用共享配置
// 共享目录内可放 config.*.js 与 envFile,发布时复制到版本目录并覆盖包内同名文件
envFile: '.env',
// 本机权威副本(相对仓库根目录,已 gitignore);存在时发布前上传,覆盖服务端共享 env
envFileLocalPath: 'tools/config/env.production.local',
uploadEnvFile: true,
// ===== Nginx =====
// 不写 nginxUpstreamFile 则默认 <deployRoot>/nginx-upstream.conf;设为 '' 表示不管理 upstream
// 切换 upstream 后执行的重载命令;设为 '' 则只写文件不重载
nginxReloadCommand: 'nginx -t && nginx -s reload',
},
// ==================== 前端(releases + current 软链)====================
frontend: {
// false 表示本次发布不动前端
enabled: true,
// 站点根目录,releases/ 与 current 都在其下
basePath: '/www/wwwroot/oms.gztbyc.com',
// 本机构建产物的目录(相对仓库根目录)
distDir: 'frontend/dist',
// 发布前本地构建命令(在 frontend/ 下执行)
buildCommand: 'npm run build',
// 服务器保留的最近版本数
keepReleases: 5,
// 发版后健康检查用的域名(本机 curl 带 Host 头访问 https://127.0.0.1/,仅提示)
siteHost: 'oms.gztbyc.com',
},
},
};

View File

@ -0,0 +1,37 @@
# 生产环境变量模板(本机权威副本)
#
# 用法:复制为 tools/config/env.production.local(已 gitignore),填好后执行
# cd tools && npm run deploy
# 发布时会先上传到服务器 <deployRoot>/shared-config/.env,再覆盖到各版本目录的 .env。
# 文件不存在时跳过上传,沿用服务器上已有的 shared-config/.env。
#
# 注意:服务器上 shared-config/.env 首次会从老位置的 <deployRoot>/.env 自动初始化。
# ---- Egg 实例(端口由发布脚本注入 EGG_PORT,此处无需配置)----
# UPLOAD_DIR=/www/wwwroot/api.oms.gztbyc.com/uploads
# ---- MySQL ----
MYSQL_HOST=
MYSQL_PORT=3306
MYSQL_USER=
MYSQL_PASSWORD=
MYSQL_DATABASE=
# ---- Redis ----
REDIS_HOST=
REDIS_PORT=6379
REDIS_PASSWORD=
# ---- 鉴权 ----
JWT_SECRET=
# ---- 邮件(可选)----
SMTP_HOST=
SMTP_PORT=
SMTP_SECURE=
SMTP_USER=
SMTP_PASS=
SMTP_FROM=
# ---- 对外回调地址(可选)----
OMS_CALLBACK_BASE_URL=http://api.oms.gztbyc.com

584
tools/package-lock.json generated Normal file
View File

@ -0,0 +1,584 @@
{
"name": "oms-tools",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "oms-tools",
"version": "1.0.0",
"dependencies": {
"dotenv": "^17.4.2"
},
"devDependencies": {
"@types/node": "^22.10.2",
"tsx": "^4.19.2",
"typescript": "~5.7.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
"integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
"integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
"integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
"integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
"integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
"integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
"integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
"integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
"integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
"integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
"integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
"integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
"integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
"integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
"integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
"integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
"integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
"integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
"integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
"integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
"integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
"integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
"integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
"integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
"integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
"integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/dotenv": {
"version": "17.4.2",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
"integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/esbuild": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
"integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.2",
"@esbuild/android-arm": "0.28.2",
"@esbuild/android-arm64": "0.28.2",
"@esbuild/android-x64": "0.28.2",
"@esbuild/darwin-arm64": "0.28.2",
"@esbuild/darwin-x64": "0.28.2",
"@esbuild/freebsd-arm64": "0.28.2",
"@esbuild/freebsd-x64": "0.28.2",
"@esbuild/linux-arm": "0.28.2",
"@esbuild/linux-arm64": "0.28.2",
"@esbuild/linux-ia32": "0.28.2",
"@esbuild/linux-loong64": "0.28.2",
"@esbuild/linux-mips64el": "0.28.2",
"@esbuild/linux-ppc64": "0.28.2",
"@esbuild/linux-riscv64": "0.28.2",
"@esbuild/linux-s390x": "0.28.2",
"@esbuild/linux-x64": "0.28.2",
"@esbuild/netbsd-arm64": "0.28.2",
"@esbuild/netbsd-x64": "0.28.2",
"@esbuild/openbsd-arm64": "0.28.2",
"@esbuild/openbsd-x64": "0.28.2",
"@esbuild/openharmony-arm64": "0.28.2",
"@esbuild/sunos-x64": "0.28.2",
"@esbuild/win32-arm64": "0.28.2",
"@esbuild/win32-ia32": "0.28.2",
"@esbuild/win32-x64": "0.28.2"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/tsx": {
"version": "4.23.15",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz",
"integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.28.0"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/typescript": {
"version": "5.7.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz",
"integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
}
}
}

34
tools/package.json Normal file
View File

@ -0,0 +1,34 @@
{
"name": "oms-tools",
"version": "1.0.0",
"description": "OMS 发布与运维工具集",
"private": true,
"main": "dist/cli.js",
"bin": {
"oms-tools": "dist/cli.js"
},
"scripts": {
"cli": "tsx src/cli.ts",
"init": "tsx src/cli.ts init",
"deploy": "tsx src/cli.ts deploy",
"deploy:backend": "tsx src/cli.ts deploy:backend",
"deploy:frontend": "tsx src/cli.ts deploy:frontend",
"rollback": "tsx src/cli.ts rollback",
"rollback:backend": "tsx src/cli.ts rollback:backend",
"rollback:frontend": "tsx src/cli.ts rollback:frontend",
"build": "tsc -p tsconfig.json",
"start": "node dist/cli.js",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"dotenv": "^17.4.2"
},
"devDependencies": {
"@types/node": "^22.10.2",
"tsx": "^4.19.2",
"typescript": "~5.7.2"
}
}

77
tools/src/cli.ts Normal file
View File

@ -0,0 +1,77 @@
#!/usr/bin/env node
import 'dotenv/config';
import { runDeploy } from './commands/deploy';
import { runRollback } from './commands/rollback';
import { initDeployConfig } from './lib/config';
interface Command {
summary: string;
run: (args: string[]) => void;
}
const COMMANDS: Record<string, Command> = {
deploy: {
summary: '前后端同时发布 npm run deploy [-- --skip-build|--dry-run|--allow-dirty]',
run: args => runDeploy(args, { backend: true, frontend: true }),
},
'deploy:backend': {
summary: '仅发布后端 npm run deploy:backend [-- 参数同上]',
run: args => runDeploy(args, { backend: true, frontend: false }),
},
'deploy:frontend': {
summary: '仅发布前端 npm run deploy:frontend [-- 参数同上]',
run: args => runDeploy(args, { backend: false, frontend: true }),
},
rollback: {
summary: '前后端一起回滚 npm run rollback [-- --to=v1|v2] [--dry-run]',
run: args => runRollback(args, { backend: true, frontend: true }),
},
'rollback:backend': {
summary: '仅回滚后端 npm run rollback:backend [-- --to=v1|v2]',
run: args => runRollback(args, { backend: true, frontend: false }),
},
'rollback:frontend': {
summary: '仅回滚前端 npm run rollback:frontend',
run: args => runRollback(args, { backend: false, frontend: true }),
},
init: {
summary: '生成发布配置(deploy.config.local.cjs)',
run: () => initDeployConfig(),
},
};
function printUsage(): void {
console.log('OMS 发布工具');
console.log('');
console.log('用法: npm run <script> [-- <参数>] 或 tsx src/cli.ts <命令> [参数]');
console.log('');
console.log('命令:');
for (const [ name, command ] of Object.entries(COMMANDS)) {
console.log(` ${name.padEnd(18)} ${command.summary}`);
}
console.log('');
console.log('发布受限于 git:工作区有未提交改动时默认中止,可用 --allow-dirty 强制发布。');
}
function main(argv: string[]): void {
const [ command, ...rest ] = argv;
if (!command || command === 'help' || command === '--help' || command === '-h') {
printUsage();
return;
}
const entry = COMMANDS[command];
if (!entry) {
throw new Error(`未知命令: ${command}(执行 npm run cli -- help 查看可用命令)`);
}
entry.run(rest);
}
try {
main(process.argv.slice(2));
} catch (err) {
console.error(`❌ ${(err as Error).message}`);
process.exitCode = 1;
}

View File

@ -0,0 +1,178 @@
import fs from 'node:fs';
import path from 'node:path';
import { parseArgs } from '../lib/args';
import { buildBackendArchive, buildFrontendArchive, formatBytes } from '../lib/archive';
import { buildBackendDeployScript } from '../lib/backend-remote';
import { loadDeployConfig } from '../lib/config';
import { buildFrontendDeployScript, frontendArchiveRemotePath } from '../lib/frontend-remote';
import { assertCleanWorktree, getGitInfo } from '../lib/git';
import { BACKEND_ROOT, FRONTEND_ROOT } from '../lib/paths';
import { ensureCommandAvailable, quoteForBash, runForeground, runNpm } from '../lib/shell';
import { runScp, runSsh } from '../lib/ssh';
import { getIsoTime, getNowStamp, getReleaseName } from '../lib/time';
import { recordVersion } from '../lib/version-record';
export interface DeployTargets {
backend: boolean;
frontend: boolean;
}
function runBuildCommand(command: string, cwd: string): void {
const [ bin, ...rest ] = command.trim().split(/\s+/);
if (bin === 'npm' || bin === 'npm.cmd') {
runNpm(rest, cwd);
return;
}
runForeground(bin, rest, cwd);
}
/** 上传前检查生产环境变量文件的关键项,避免误用开发环境文件覆盖线上配置 */
function warnMissingEnvKeys(filePath: string, required = [ 'MYSQL_HOST', 'MYSQL_DATABASE', 'JWT_SECRET' ]): void {
const content = fs.readFileSync(filePath, 'utf8');
const missing = required.filter(key => !new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`, 'm').test(content));
if (missing.length) {
console.warn(`[WARN] ${filePath} 缺少 ${missing.join(', ')},确认这是生产配置后再发布(该文件会覆盖服务端共享配置)。`);
}
}
/**
* 发布(默认前后端同时发布)
*
* npm run deploy # 构建前端 → 打包前后端 → 上传 → 一次 SSH 完成切换
* npm run deploy -- --dry-run # 只做本地构建与打包,打印远端脚本,不连服务器
* npm run deploy -- --skip-build # 复用已有 frontend/dist
* npm run deploy -- --allow-dirty # 允许工作区有未提交改动(发布受限于 git)
*/
export function runDeploy(args: string[], targets: DeployTargets): void {
const parsed = parseArgs(args);
const dryRun = parsed.flags.has('dry-run');
const skipBuild = parsed.flags.has('skip-build');
const allowDirty = parsed.flags.has('allow-dirty');
const config = loadDeployConfig(parsed.env, { allowMissingSecrets: dryRun });
const backend = targets.backend ? config.backend : null;
const frontend = targets.frontend ? config.frontend : null;
if (targets.backend && !backend) throw new Error('当前配置未启用 backend,无法发布后端。');
if (targets.frontend && !frontend) throw new Error('当前配置未启用 frontend,无法发布前端。');
// 发布受限于 git:默认要求工作区干净
const git = getGitInfo();
assertCleanWorktree(git, config.allowDirtyGit, allowDirty);
const targetsLabel = [ backend ? '后端' : '', frontend ? '前端' : '' ].filter(Boolean).join(' + ');
console.log(`[deploy] 环境: ${config.envName} 目标: ${config.username}@${config.host}`);
console.log(`[deploy] 分支: ${git.branch} 提交: ${git.commit}${git.dirty ? '(工作区有未提交改动)' : ''}`);
console.log(`[deploy] 发布内容: ${targetsLabel}`);
ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。');
if (!dryRun) {
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
}
if (frontend) {
if (skipBuild) {
console.log('[deploy] 跳过前端构建(--skip-build),使用现有 dist');
} else {
console.log(`[deploy] 构建前端: ${frontend.buildCommand}(cwd=frontend)`);
runBuildCommand(frontend.buildCommand, FRONTEND_ROOT);
}
}
const stamp = getNowStamp();
const releaseName = frontend ? getReleaseName() : '';
const pkg = JSON.parse(fs.readFileSync(path.join(BACKEND_ROOT, 'package.json'), 'utf8')) as { version?: string };
const backendArchive = backend ? buildBackendArchive(stamp, backend) : null;
if (backendArchive) {
console.log(`[deploy] 后端发布包: backend-${stamp}.tar.gz(${backendArchive.fileCount} 个文件,${formatBytes(backendArchive.size)})`);
}
const frontendArchive = frontend ? buildFrontendArchive(stamp, frontend) : null;
if (frontendArchive) {
console.log(`[deploy] 前端发布包: frontend-${stamp}.tar.gz(${formatBytes(frontendArchive.size)})`);
}
const remoteBackendArchive = backend ? `${backend.incomingDir}/backend-${stamp}.tar.gz` : '';
const remoteFrontendArchive = frontend ? frontendArchiveRemotePath(frontend, releaseName) : '';
const backendScript = backend
? buildBackendDeployScript(config, { stamp, remoteArchive: remoteBackendArchive, frontendRelease: releaseName })
: '';
const frontendScript = frontend ? buildFrontendDeployScript(frontend!, releaseName) : '';
// 本机生产环境变量若存在,发布前会覆盖服务端共享配置:先做一次关键项检查
const localEnvPath = backend && backend.uploadEnvFile && backend.sharedConfigDir ? backend.envFileLocalPath : '';
if (localEnvPath && fs.existsSync(localEnvPath)) warnMissingEnvKeys(localEnvPath);
if (dryRun) {
console.log('\n[deploy] --dry-run:跳过 SSH 上传与远端执行,远端脚本如下:\n');
console.log('==================== 后端脚本 ====================');
console.log(backendScript || '(未启用后端)');
console.log('==================== 前端脚本 ====================');
console.log(frontendScript || '(未启用前端)');
console.log('==================================================');
console.log('\n[deploy] --dry-run 完成(本地发布包已生成)');
if (backend) console.log(`[deploy] 后端共享配置: ${backend.sharedConfigDir || '(未配置)'}`);
return;
}
// ---- 1. 后端:先上线并通过健康检查、切换 Nginx ----
if (backend) {
console.log('[deploy] 准备后端远端目录…');
const dirs = new Set<string>([ backend.deployRoot, backend.incomingDir, backend.backupDir, backend.stateDir ]);
if (backend.sharedConfigDir) dirs.add(backend.sharedConfigDir);
runSsh(config, [ 'set -euo pipefail', `mkdir -p ${[ ...dirs ].map(quoteForBash).join(' ')}` ].join('\n'), 'pipe');
// 本地发布时覆盖服务端共享配置(后端的配置共享出来,本地有权威副本时覆盖它)
if (backend.uploadEnvFile && backend.sharedConfigDir) {
if (backend.envFileLocalPath && fs.existsSync(backend.envFileLocalPath)) {
const remoteEnvPath = `${backend.sharedConfigDir}/${backend.envFile}`;
console.log(`[deploy] 覆盖服务端共享配置: ${backend.envFileLocalPath} → ${remoteEnvPath}`);
runScp(config, backend.envFileLocalPath, remoteEnvPath);
} else {
console.log('[deploy] 本机没有生产环境变量文件,沿用服务端 shared-config 现有配置');
}
}
console.log(`[deploy] 上传后端发布包 → ${remoteBackendArchive}`);
runScp(config, backendArchive!.archivePath, remoteBackendArchive);
console.log('[deploy] 后端部署中…\n');
runSsh(config, backendScript);
}
// ---- 2. 后端就绪后再切前端(后端失败时前端完全不执行)----
if (frontend) {
console.log('[deploy] 上传前端发布包…');
runSsh(config, [ 'set -euo pipefail', `mkdir -p ${quoteForBash(`${frontend.basePath}/releases/${releaseName}`)}` ].join('\n'), 'pipe');
runScp(config, frontendArchive!.archivePath, remoteFrontendArchive);
console.log('[deploy] 前端发布中…\n');
runSsh(config, frontendScript);
}
if (backend) {
try {
recordVersion(config, {
version: pkg.version || '0.0.0',
commit: git.commit,
branch: git.branch,
env: config.envName,
dirty: git.dirty,
targets: [ 'backend', frontend ? 'frontend' : '' ].filter(Boolean),
frontendRelease: frontend ? releaseName : '',
operator: process.env.USERNAME || process.env.USER || '',
time: getIsoTime(),
files: backendArchive ? backendArchive.fileCount : 0,
size: backendArchive ? backendArchive.size : 0,
});
} catch (err) {
console.warn(`[WARN] 版本记录写入失败: ${(err as Error).message}`);
}
}
console.log('\n[deploy] ✅ 发布完成');
if (frontend) console.log(`[deploy] 前端版本: ${releaseName}`);
}

View File

@ -0,0 +1,58 @@
import { parseArgs } from '../lib/args';
import { buildBackendRollbackScript, readRemoteCurrentVersion, resolveRollbackTarget } from '../lib/backend-remote';
import { loadDeployConfig } from '../lib/config';
import { buildFrontendRollbackScript } from '../lib/frontend-remote';
import { ensureCommandAvailable } from '../lib/shell';
import { runSsh } from '../lib/ssh';
import type { DeployTargets } from './deploy';
/**
* 回滚(后端切回另一套版本目录 + 前端 current 软链切回上一个版本)
*
* npm run rollback # 前后端一起回滚
* npm run rollback -- --to=v1 # 指定后端回滚到 v1(前端仍回上一个版本)
* npm run rollback -- --dry-run # 只打印远端脚本
*/
export function runRollback(args: string[], targets: DeployTargets): void {
const parsed = parseArgs(args);
const dryRun = parsed.flags.has('dry-run');
const config = loadDeployConfig(parsed.env, { allowMissingSecrets: dryRun });
const backend = targets.backend ? config.backend : null;
const frontend = targets.frontend ? config.frontend : null;
if (targets.backend && !backend) throw new Error('当前配置未启用 backend,无法回滚后端。');
if (targets.frontend && !frontend) throw new Error('当前配置未启用 frontend,无法回滚前端。');
if (!dryRun) ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
const requested = parsed.values.to || '';
let backendScript = '';
if (backend) {
if (dryRun) {
backendScript = buildBackendRollbackScript(config, requested);
console.log(`[rollback] 后端(dry-run): 目标 ${requested || '另一套版本'}`);
} else {
const currentVersion = readRemoteCurrentVersion(config);
const targetVersion = resolveRollbackTarget(currentVersion, requested);
backendScript = buildBackendRollbackScript(config, targetVersion);
console.log(`[rollback] 后端: ${currentVersion} → ${targetVersion}`);
}
}
const frontendScript = frontend ? buildFrontendRollbackScript(frontend) : '';
if (frontend) console.log('[rollback] 前端: current → releases 里的上一个版本');
const remoteScript = [ backendScript, frontendScript ].filter(Boolean).join('\n\n');
if (dryRun) {
console.log('\n[rollback] --dry-run:远端脚本如下:\n');
console.log('============================================================');
console.log(remoteScript);
console.log('============================================================');
return;
}
runSsh(config, remoteScript);
console.log('\n[rollback] ✅ 回滚完成');
}

108
tools/src/lib/archive.ts Normal file
View File

@ -0,0 +1,108 @@
import fs from 'node:fs';
import path from 'node:path';
import type { BackendSection, FrontendSection } from './config';
import { BACKEND_ROOT, TEMP_DIR } from './paths';
import { runCommand } from './shell';
const REQUIRED_BACKEND_FILES = [ 'app.js', 'package.json' ];
const LOCAL_ARCHIVE_KEEP = 3;
/**
* 判断路径是否命中规则(`a/**` 匹配 a 及其全部子项,其余为精确匹配)
*/
export function pathMatchesRule(filePath: string, rule: string): boolean {
const normalizedPath = String(filePath || '').replace(/\\/g, '/');
const normalizedRule = String(rule || '').replace(/\\/g, '/').trim();
if (!normalizedRule) return false;
if (normalizedRule.endsWith('/**')) {
const prefix = normalizedRule.slice(0, -3);
return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`);
}
return normalizedPath === normalizedRule;
}
function ensureTempDir(name: string): string {
const dir = path.join(TEMP_DIR, name);
fs.mkdirSync(dir, { recursive: true });
return dir;
}
/** 只保留最近几个本地发布包 */
function pruneLocalArchives(dir: string, keep = LOCAL_ARCHIVE_KEEP): void {
const archives = fs.readdirSync(dir)
.filter(name => /\.tar\.gz$/.test(name))
.sort()
.reverse();
for (const name of archives.slice(keep)) {
fs.rmSync(path.join(dir, name), { force: true });
}
}
/**
* 列出后端可发布文件:以 git 的视角取文件(受限于 git),再按 include / exclude 规则过滤。
*/
export function listBackendFiles(backend: BackendSection): string[] {
const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ], { cwd: BACKEND_ROOT });
return Array.from(new Set(
output
.split(/\r?\n/)
.map(item => item.trim())
.filter(Boolean)
.filter(item => !item.startsWith('.git/'))
.filter(item => fs.existsSync(path.join(BACKEND_ROOT, item)))
.filter(item => backend.deployIncludePaths.some(rule => pathMatchesRule(item, rule)))
.filter(item => !backend.deployExcludePaths.some(rule => pathMatchesRule(item, rule)))
)).sort();
}
/**
* 构建后端发布包(tar.gz),返回路径 / 文件数 / 字节数
*/
export function buildBackendArchive(stamp: string, backend: BackendSection): { archivePath: string; fileCount: number; size: number } {
const tempDir = ensureTempDir('backend');
const listPath = path.join(tempDir, `deploy-files-${stamp}.txt`);
const archivePath = path.join(tempDir, `backend-${stamp}.tar.gz`);
const files = listBackendFiles(backend);
if (!files.length) throw new Error('未找到可发布的后端文件(请检查 git 状态与 deployIncludePaths 配置)。');
const missing = REQUIRED_BACKEND_FILES.filter(name => !files.includes(name));
if (missing.length) {
throw new Error(`后端发布包缺少必需文件: ${missing.join(', ')},请检查 deployIncludePaths / deployExcludePaths 配置。`);
}
fs.writeFileSync(listPath, `${files.join('\n')}\n`, 'utf8');
runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { cwd: BACKEND_ROOT, stdio: 'inherit' });
const size = fs.statSync(archivePath).size;
pruneLocalArchives(tempDir);
return { archivePath, fileCount: files.length, size };
}
/**
* 构建前端发布包(tar.gz,内容为 dist 目录),返回路径与字节数
*/
export function buildFrontendArchive(stamp: string, frontend: FrontendSection): { archivePath: string; size: number } {
if (!fs.existsSync(path.join(frontend.distDir, 'index.html')) || !fs.existsSync(path.join(frontend.distDir, 'assets'))) {
throw new Error(`前端构建产物不完整(缺少 index.html 或 assets): ${frontend.distDir},中止发布。`);
}
const tempDir = ensureTempDir('frontend');
const archivePath = path.join(tempDir, `frontend-${stamp}.tar.gz`);
runCommand('tar', [ '-czf', archivePath, '-C', frontend.distDir, '.' ], { stdio: 'inherit' });
const size = fs.statSync(archivePath).size;
pruneLocalArchives(tempDir);
return { archivePath, size };
}
/** 人类可读的体积 */
export function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}

32
tools/src/lib/args.ts Normal file
View File

@ -0,0 +1,32 @@
export interface ParsedArgs {
/** 环境名(首个非版本标识的位置参数,默认 production) */
env: string;
positional: string[];
/** 无值开关,如 --dry-run */
flags: Set<string>;
/** --key=value 形式的参数 */
values: Record<string, string>;
}
/**
* 解析命令行参数:`--flag` / `--key=value` / 位置参数。
*/
export function parseArgs(args: string[], defaultEnv = 'production'): ParsedArgs {
const positional: string[] = [];
const flags = new Set<string>();
const values: Record<string, string> = {};
for (const item of args) {
if (!item.startsWith('--')) {
positional.push(item);
continue;
}
const body = item.slice(2);
const eq = body.indexOf('=');
if (eq === -1) flags.add(body);
else values[body.slice(0, eq)] = body.slice(eq + 1);
}
const env = positional.find(item => !/^v[12]$/.test(item)) || defaultEnv;
return { env, positional, flags, values };
}

View File

@ -0,0 +1,218 @@
import type { DeployConfig } from './config';
import { VERSIONS, otherVersion } from './config';
import type { Version } from './config';
import { quoteForBash } from './shell';
import {
BASH_KILL_PORT_FUNCTION,
buildHealthCheckLines,
buildNginxSwitchLines,
buildRemoteCleanupGuard,
buildScopedEggStopLines,
buildSharedConfigLines,
buildStartInstanceLines,
} from './remote-scripts';
import { runSsh } from './ssh';
export interface BackendDeployParams {
stamp: string;
remoteArchive: string;
frontendRelease: string;
}
/**
* 读取远端当前活跃版本;尚未初始化(无 current.md)时返回空字符串。
*/
export function readRemoteCurrentVersion(config: DeployConfig): string {
const backend = config.backend;
if (!backend) return '';
const output = runSsh(config, `cat ${quoteForBash(backend.currentFile)} 2>/dev/null || true`, 'pipe')
.replace(/\r/g, '')
.trim();
if (!output) return '';
if (!VERSIONS.includes(output as Version)) {
throw new Error(`远端 ${backend.currentFile} 内容无效: "${output}",期望 v1 或 v2。`);
}
return output;
}
/**
* 后端蓝绿发布脚本(单次 SSH 执行):
* 确定空闲槽位 → 备份 → 清理并解压 → 应用共享配置 → 安装依赖/迁移
* → 启动新实例 → 健康检查 → 切 Nginx → 写 current.md → 停旧实例 → 清理旧备份
*/
export function buildBackendDeployScript(config: DeployConfig, params: BackendDeployParams): string {
const backend = config.backend;
if (!backend) return '';
return [
'set -euo pipefail',
`DEPLOY_ROOT=${quoteForBash(backend.deployRoot)}`,
`V1_PORT=${backend.ports.v1}`,
`V2_PORT=${backend.ports.v2}`,
`STAMP=${quoteForBash(params.stamp)}`,
`ARCHIVE=${quoteForBash(params.remoteArchive)}`,
`INSTALL_COMMAND=${quoteForBash(backend.installCommand)}`,
`START_COMMAND=${quoteForBash(backend.startCommand)}`,
`HEALTH_PATH=${quoteForBash(backend.healthCheckPath)}`,
`HEALTH_ATTEMPTS=${backend.healthCheckAttempts}`,
`HEALTH_INTERVAL=${backend.healthCheckInterval}`,
`KEEP_BACKUPS=${config.keepBackups}`,
`RUN_MIGRATIONS=${backend.runMigrations ? 1 : 0}`,
`SHARED_CONFIG_DIR=${quoteForBash(backend.sharedConfigDir)}`,
'',
BASH_KILL_PORT_FUNCTION,
'',
'cd "$DEPLOY_ROOT"',
'mkdir -p .deploy/incoming .deploy/backups .deploy/state .deploy/logs v1 v2',
'if [ -n "$SHARED_CONFIG_DIR" ]; then mkdir -p "$SHARED_CONFIG_DIR"; fi',
'',
'echo "---- 1/7 计算目标槽位 ----"',
'ACTIVE=""',
'if [ -f current.md ]; then ACTIVE=$(tr -d " \\r\\n" < current.md); fi',
'case "$ACTIVE" in v1|v2) ;; *) ACTIVE="" ;; esac',
'if [ "$ACTIVE" = "v1" ]; then TARGET_SLOT=v2; else TARGET_SLOT=v1; fi',
'if [ "$TARGET_SLOT" = "v1" ]; then TARGET_PORT=$V1_PORT; else TARGET_PORT=$V2_PORT; fi',
'OLD_PORT=""',
'if [ "$ACTIVE" = "v1" ]; then OLD_PORT=$V1_PORT; elif [ "$ACTIVE" = "v2" ]; then OLD_PORT=$V2_PORT; fi',
'TARGET_DIR="$DEPLOY_ROOT/$TARGET_SLOT"',
'START_LOG="$DEPLOY_ROOT/.deploy/logs/$TARGET_SLOT-start.log"',
'echo "当前活跃实例: $ACTIVE → 本次发布: $TARGET_SLOT (:$TARGET_PORT)"',
'',
'echo "---- 2/7 释放目标端口并准备目录 ----"',
'kill_port "$TARGET_PORT"',
'if [ -d "$TARGET_DIR" ]; then',
' tar -czf "$DEPLOY_ROOT/.deploy/backups/$TARGET_SLOT-$STAMP.tar.gz" -C "$DEPLOY_ROOT" "$TARGET_SLOT" 2>/dev/null || true',
'fi',
'mkdir -p "$TARGET_DIR"',
`( cd "$TARGET_DIR" && find . -mindepth 1 -maxdepth 1 ${buildRemoteCleanupGuard(backend.sharedDirs)} -exec rm -rf {} + )`,
'tar -xzf "$ARCHIVE" -C "$TARGET_DIR"',
'rm -f "$ARCHIVE"',
'echo "代码已解压到 $TARGET_DIR"',
'',
'echo "---- 3/7 应用服务端共享配置 ----"',
...buildSharedConfigLines(backend.sharedConfigDir, backend.envFile, backend.deployRoot),
'',
'echo "---- 4/7 安装依赖 / 数据库迁移 ----"',
'cd "$TARGET_DIR"',
'echo "安装依赖: $INSTALL_COMMAND"',
'eval "$INSTALL_COMMAND"',
'if [ "$RUN_MIGRATIONS" = "1" ]; then',
' echo "执行数据库迁移: npm run migration:up"',
' npm run migration:up',
'else',
' echo "runMigrations=false,跳过数据库迁移"',
'fi',
'',
'echo "---- 5/7 启动新实例并健康检查 ----"',
'DEPLOY_OK=0',
'cleanup_on_fail() {',
' RC=$?',
' if [ "$DEPLOY_OK" != "1" ]; then',
' echo "发布失败,停止新实例 $TARGET_SLOT(当前实例 $ACTIVE 继续服务)" >&2',
' tail -n 30 "$START_LOG" 2>/dev/null || true',
' kill_port "$TARGET_PORT" || true',
' fi',
' exit $RC',
'}',
'trap cleanup_on_fail EXIT',
...buildStartInstanceLines('$TARGET_DIR', backend.startCommand, '$START_LOG', '$TARGET_PORT'),
...buildHealthCheckLines('$TARGET_PORT', backend.healthCheckPath, '$TARGET_SLOT', backend.healthCheckAttempts, backend.healthCheckInterval),
'',
'echo "---- 6/7 切换 Nginx / 记录活跃槽位 / 停止旧实例 ----"',
...buildNginxSwitchLines(backend.nginxUpstreamFile, backend.nginxReloadCommand, '$TARGET_PORT'),
'cd "$DEPLOY_ROOT"',
'echo "$TARGET_SLOT" > current.md',
'if [ -n "$ACTIVE" ] && [ "$ACTIVE" != "$TARGET_SLOT" ]; then',
...buildScopedEggStopLines('$DEPLOY_ROOT/$ACTIVE', 'STOP_OLD'),
' kill_port "$OLD_PORT"',
' echo "旧实例 $ACTIVE 已停止"',
'else',
' echo "首次发布,无旧实例需要停止"',
'fi',
'',
'echo "---- 7/7 清理旧备份 ----"',
'ls -1t "$DEPLOY_ROOT"/.deploy/backups/*.tar.gz 2>/dev/null | tail -n +$((KEEP_BACKUPS + 1)) | xargs -r rm -f || true',
'',
'DEPLOY_OK=1',
`echo "BACKEND_DEPLOY_OK slot=$TARGET_SLOT port=$TARGET_PORT frontend=${params.frontendRelease}"`,
].join('\n');
}
/**
* 后端回滚脚本:切回另一套已发布过的版本目录(不重新构建/上传)。
*/
export function buildBackendRollbackScript(config: DeployConfig, requestedVersion: string): string {
const backend = config.backend;
if (!backend) return '';
return [
'set -euo pipefail',
`DEPLOY_ROOT=${quoteForBash(backend.deployRoot)}`,
`V1_PORT=${backend.ports.v1}`,
`V2_PORT=${backend.ports.v2}`,
`REQUESTED=${quoteForBash(requestedVersion)}`,
`INSTALL_COMMAND=${quoteForBash(backend.installCommand)}`,
`START_COMMAND=${quoteForBash(backend.startCommand)}`,
`HEALTH_PATH=${quoteForBash(backend.healthCheckPath)}`,
`HEALTH_ATTEMPTS=${backend.healthCheckAttempts}`,
`HEALTH_INTERVAL=${backend.healthCheckInterval}`,
`SHARED_CONFIG_DIR=${quoteForBash(backend.sharedConfigDir)}`,
'',
BASH_KILL_PORT_FUNCTION,
'',
'cd "$DEPLOY_ROOT"',
'ACTIVE=""',
'if [ -f current.md ]; then ACTIVE=$(tr -d " \\r\\n" < current.md); fi',
'if [ -z "$ACTIVE" ]; then echo "远端没有 current.md,无法回滚" >&2; exit 1; fi',
'if [ -n "$REQUESTED" ]; then TARGET_SLOT="$REQUESTED"; elif [ "$ACTIVE" = "v1" ]; then TARGET_SLOT=v2; else TARGET_SLOT=v1; fi',
'if [ "$TARGET_SLOT" != "v1" ] && [ "$TARGET_SLOT" != "v2" ]; then echo "目标版本无效: $TARGET_SLOT" >&2; exit 1; fi',
'if [ "$TARGET_SLOT" = "$ACTIVE" ]; then echo "目标版本与当前活跃版本相同($ACTIVE),无需回滚" >&2; exit 1; fi',
'if [ "$TARGET_SLOT" = "v1" ]; then TARGET_PORT=$V1_PORT; else TARGET_PORT=$V2_PORT; fi',
'if [ "$ACTIVE" = "v1" ]; then OLD_PORT=$V1_PORT; else OLD_PORT=$V2_PORT; fi',
'TARGET_DIR="$DEPLOY_ROOT/$TARGET_SLOT"',
'START_LOG="$DEPLOY_ROOT/.deploy/logs/$TARGET_SLOT-start.log"',
'echo "当前活跃: $ACTIVE → 回滚目标: $TARGET_SLOT (:$TARGET_PORT)"',
'',
'if [ ! -f "$TARGET_DIR/package.json" ]; then',
' echo "目标版本目录不可用(该版本尚未发布过): $TARGET_DIR" >&2',
' exit 1',
'fi',
'',
...buildSharedConfigLines(backend.sharedConfigDir, backend.envFile, backend.deployRoot),
'',
'kill_port "$TARGET_PORT"',
'cd "$TARGET_DIR"',
'if [ ! -d node_modules ]; then echo "目标版本缺少 node_modules,先安装依赖"; eval "$INSTALL_COMMAND"; fi',
'',
'DEPLOY_OK=0',
'cleanup_on_fail() {',
' RC=$?',
' if [ "$DEPLOY_OK" != "1" ]; then',
' echo "回滚失败,停止目标实例 $TARGET_SLOT(当前实例 $ACTIVE 继续服务)" >&2',
' tail -n 30 "$START_LOG" 2>/dev/null || true',
' kill_port "$TARGET_PORT" || true',
' fi',
' exit $RC',
'}',
'trap cleanup_on_fail EXIT',
...buildStartInstanceLines('$TARGET_DIR', backend.startCommand, '$START_LOG', '$TARGET_PORT'),
...buildHealthCheckLines('$TARGET_PORT', backend.healthCheckPath, '$TARGET_SLOT', backend.healthCheckAttempts, backend.healthCheckInterval),
...buildNginxSwitchLines(backend.nginxUpstreamFile, backend.nginxReloadCommand, '$TARGET_PORT'),
'cd "$DEPLOY_ROOT"',
'echo "$TARGET_SLOT" > current.md',
...buildScopedEggStopLines('$DEPLOY_ROOT/$ACTIVE', 'STOP_ROLLED_BACK'),
'kill_port "$OLD_PORT"',
'DEPLOY_OK=1',
'echo "BACKEND_ROLLBACK_OK slot=$TARGET_SLOT port=$TARGET_PORT"',
].join('\n');
}
/** 回滚目标预检(本地):未指定时切到另一套版本 */
export function resolveRollbackTarget(currentVersion: string, requested: string): string {
if (!currentVersion) throw new Error('远端没有 current.md,没有可回滚的后端版本。');
const target = requested || otherVersion(currentVersion);
if (target === currentVersion) throw new Error(`目标版本与当前活跃版本相同(${target}),无需回滚。`);
return target;
}

283
tools/src/lib/config.ts Normal file
View File

@ -0,0 +1,283 @@
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
import { DEPLOY_CONFIG_EXAMPLE_PATH, DEPLOY_CONFIG_PATH, ENV_EXAMPLE_PATH, REPO_ROOT, displayPath } from './paths';
import { assertPrivateKeyExists, resolvePrivateKeyPath, withGuardedOptions } from './ssh';
import type { SshTarget } from './ssh';
export const VERSIONS = [ 'v1', 'v2' ] as const;
export type Version = (typeof VERSIONS)[number];
export const DEFAULT_ENV = 'production';
/** 发布包默认包含的文件(相对 backend 根目录) */
const DEFAULT_INCLUDE_PATHS = [
'.sequelizerc',
'app.js',
'app/**',
'config/**',
'database/**',
'package.json',
'package-lock.json',
];
/** 发布包默认排除(叠加在 include 之上) */
const DEFAULT_EXCLUDE_PATHS = [
'.env',
'.env.*',
'uploads/**',
'logs/**',
'run/**',
'temp/**',
'test/**',
'swagger.json',
];
interface RawBackendConfig {
deployRoot?: string;
ports?: Partial<Record<Version, number | string>>;
healthCheckPath?: string;
healthCheckAttempts?: number | string;
healthCheckInterval?: number | string;
sharedDirs?: string[];
deployIncludePaths?: string[];
deployExcludePaths?: string[];
installCommand?: string;
startCommand?: string;
runMigrations?: boolean;
startTitlePrefix?: string;
sharedConfigDir?: string;
envFile?: string;
envFileLocalPath?: string;
uploadEnvFile?: boolean;
nginxUpstreamFile?: string;
nginxReloadCommand?: string;
}
interface RawFrontendConfig {
enabled?: boolean;
basePath?: string;
distDir?: string;
buildCommand?: string;
keepReleases?: number | string;
siteHost?: string;
}
interface RawDeployConfig {
host?: string;
port?: number | string;
username?: string;
privateKeyPath?: string;
sshOptions?: string[];
allowDirtyGit?: boolean;
keepVersions?: number | string;
keepBackups?: number | string;
backend?: RawBackendConfig | false;
frontend?: RawFrontendConfig | false;
}
export interface BackendSection {
deployRoot: string;
incomingDir: string;
backupDir: string;
stateDir: string;
stateFile: string;
currentFile: string;
ports: Record<Version, number>;
healthCheckPath: string;
healthCheckAttempts: number;
healthCheckInterval: number;
sharedConfigDir: string;
envFile: string;
envFileLocalPath: string;
uploadEnvFile: boolean;
nginxUpstreamFile: string;
nginxReloadCommand: string;
installCommand: string;
startCommand: string;
startTitlePrefix: string;
runMigrations: boolean;
sharedDirs: string[];
deployIncludePaths: string[];
deployExcludePaths: string[];
}
export interface FrontendSection {
basePath: string;
distDir: string;
buildCommand: string;
keepReleases: number;
siteHost: string;
}
export interface DeployConfig extends SshTarget {
envName: string;
allowDirtyGit: boolean;
keepVersions: number;
keepBackups: number;
backend: BackendSection | null;
frontend: FrontendSection | null;
}
const requireFromHere = createRequire(__filename);
/** 是否为空或未填写的占位值 */
function isPlaceholder(value: unknown): boolean {
return !value || String(value).includes('__FILL_');
}
/** 相对仓库根目录的路径解析(绝对路径原样返回) */
function resolveFromRepo(value: string): string {
return path.isAbsolute(value) ? value : path.resolve(REPO_ROOT, value);
}
function normalizeBackend(raw: RawBackendConfig): BackendSection {
const deployRoot = String(raw.deployRoot || '/www/wwwroot/api.oms.gztbyc.com').replace(/\/+$/, '');
const ports = {
v1: Number((raw.ports && raw.ports.v1) ?? 6090),
v2: Number((raw.ports && raw.ports.v2) ?? 6091),
};
if (!Number.isInteger(ports.v1) || !Number.isInteger(ports.v2) || ports.v1 === ports.v2) {
throw new Error(`后端端口配置无效: ${JSON.stringify(ports)},v1 / v2 必须是两个不同的整数端口。`);
}
const sharedConfigDir = raw.sharedConfigDir === undefined
? `${deployRoot}/shared-config`
: String(raw.sharedConfigDir || '');
const nginxUpstreamFile = raw.nginxUpstreamFile === undefined
? `${deployRoot}/nginx-upstream.conf`
: String(raw.nginxUpstreamFile || '');
const nginxReloadCommand = raw.nginxReloadCommand === undefined
? 'nginx -t && nginx -s reload'
: String(raw.nginxReloadCommand || '');
const envFile = String(raw.envFile || '.env');
return {
deployRoot,
incomingDir: `${deployRoot}/.deploy/incoming`,
backupDir: `${deployRoot}/.deploy/backups`,
stateDir: `${deployRoot}/.deploy/state`,
stateFile: `${deployRoot}/.deploy/state/versions`,
currentFile: `${deployRoot}/current.md`,
ports,
healthCheckPath: raw.healthCheckPath || '/',
healthCheckAttempts: Number(raw.healthCheckAttempts || 10),
healthCheckInterval: Number(raw.healthCheckInterval || 2),
sharedConfigDir,
envFile,
envFileLocalPath: raw.envFileLocalPath ? resolveFromRepo(String(raw.envFileLocalPath)) : '',
uploadEnvFile: raw.uploadEnvFile !== false,
nginxUpstreamFile,
nginxReloadCommand,
installCommand: raw.installCommand || 'npm install --production',
startCommand: raw.startCommand || 'npm start',
startTitlePrefix: raw.startTitlePrefix || 'oms',
runMigrations: Boolean(raw.runMigrations),
sharedDirs: Array.isArray(raw.sharedDirs) && raw.sharedDirs.length
? [ ...raw.sharedDirs ]
: [ 'logs', 'run', 'node_modules' ],
deployIncludePaths: Array.isArray(raw.deployIncludePaths) && raw.deployIncludePaths.length
? [ ...raw.deployIncludePaths ]
: DEFAULT_INCLUDE_PATHS,
deployExcludePaths: Array.isArray(raw.deployExcludePaths)
? [ ...raw.deployExcludePaths ]
: DEFAULT_EXCLUDE_PATHS,
};
}
function normalizeFrontend(raw: RawFrontendConfig): FrontendSection {
const basePath = String(raw.basePath || '').replace(/\/+$/, '');
if (!basePath) throw new Error('前端配置缺少 basePath(站点根目录)。');
const keepReleases = Number(raw.keepReleases);
return {
basePath,
distDir: resolveFromRepo(String(raw.distDir || 'frontend/dist')),
buildCommand: String(raw.buildCommand || 'npm run build'),
keepReleases: keepReleases > 0 ? keepReleases : 5,
siteHost: String(raw.siteHost || ''),
};
}
/**
* 加载统一发布配置。
* @param options.allowMissingSecrets --dry-run 用:允许占位/缺失的 SSH 信息与私钥
*/
export function loadDeployConfig(envName: string = DEFAULT_ENV, options: { allowMissingSecrets?: boolean } = {}): DeployConfig {
const configPath = displayPath(DEPLOY_CONFIG_PATH);
if (!fs.existsSync(DEPLOY_CONFIG_PATH)) {
throw new Error(`缺少发布配置 ${configPath}。请执行 npm run init(模板:${displayPath(DEPLOY_CONFIG_EXAMPLE_PATH)})并填写 SSH 信息。`);
}
const resolved = requireFromHere.resolve(DEPLOY_CONFIG_PATH);
delete requireFromHere.cache[resolved];
const loaded = requireFromHere(resolved) as Record<string, RawDeployConfig | undefined>;
const raw = loaded[envName];
if (!raw) throw new Error(`${configPath} 中未找到 ${envName} 配置。`);
if (!options.allowMissingSecrets) {
const missing: string[] = [];
if (isPlaceholder(raw.host)) missing.push('host');
if (isPlaceholder(raw.username)) missing.push('username');
if (isPlaceholder(raw.privateKeyPath)) missing.push('privateKeyPath');
if (missing.length) {
throw new Error(`请先完善 SSH 配置字段: ${missing.join(', ')}。配置文件: ${configPath}`);
}
}
const backend = raw.backend === false ? null : normalizeBackend(raw.backend || {});
const frontend = raw.frontend === false ? null : normalizeFrontend(raw.frontend || {});
if (!backend && !frontend) throw new Error('配置中 backend 与 frontend 都不可用,没有可发布的内容。');
const config: DeployConfig = {
envName,
host: String(raw.host || ''),
port: Number(raw.port || 22),
username: String(raw.username || ''),
privateKeyPath: options.allowMissingSecrets ? '' : resolvePrivateKeyPath(raw.privateKeyPath),
sshOptions: withGuardedOptions(Array.isArray(raw.sshOptions) ? [ ...raw.sshOptions ] : []),
allowDirtyGit: Boolean(raw.allowDirtyGit),
keepVersions: Number(raw.keepVersions || 30),
keepBackups: Number(raw.keepBackups || 5),
backend,
frontend,
};
if (!options.allowMissingSecrets) assertPrivateKeyExists(config, configPath);
return config;
}
/**
* 初始化发布配置:把模板复制为本地配置(已存在则不覆盖)。
*/
export function initDeployConfig(): void {
if (fs.existsSync(DEPLOY_CONFIG_PATH)) {
console.log(`ℹ️ ${displayPath(DEPLOY_CONFIG_PATH)} 已存在,未覆盖。`);
console.log(` 如需重新生成,请先删除该文件:${DEPLOY_CONFIG_PATH}`);
} else {
fs.copyFileSync(DEPLOY_CONFIG_EXAMPLE_PATH, DEPLOY_CONFIG_PATH);
console.log(`✅ 已生成 ${displayPath(DEPLOY_CONFIG_PATH)}`);
}
console.log(` 请确认 SSH(host / username / privateKeyPath)、后端 deployRoot / ports、前端 basePath 等字段。`);
console.log(` 生产环境变量可用 ${displayPath(ENV_EXAMPLE_PATH)} 作为模板复制为 tools/config/env.production.local(已 gitignore)。`);
}
/** 版本标识是否合法 */
export function assertVersion(version: string): Version {
if (!VERSIONS.includes(version as Version)) throw new Error(`版本标识无效: ${version}(支持 v1 / v2)`);
return version as Version;
}
/** 取另一个版本标识(v1 ↔ v2);首次发布返回 v1 */
export function otherVersion(version: string): Version {
if (!version) return 'v1';
return assertVersion(version) === 'v1' ? 'v2' : 'v1';
}
/** 取版本对应端口 */
export function portOf(backend: BackendSection, version: string): number {
return backend.ports[assertVersion(version)];
}

View File

@ -0,0 +1,65 @@
import fs from 'node:fs';
import path from 'node:path';
import type { FrontendSection } from './config';
import { REMOTE_SCRIPT_DIR } from './paths';
import { quoteForBash } from './shell';
/** 前端版本目录:<basePath>/releases/<版本名> */
export function frontendReleaseDir(frontend: FrontendSection, releaseName: string): string {
return `${frontend.basePath}/releases/${releaseName}`;
}
/** 远端发布包在服务器上的路径 */
export function frontendArchiveRemotePath(frontend: FrontendSection, releaseName: string): string {
return `${frontendReleaseDir(frontend, releaseName)}/dist.tar.gz`;
}
/**
* 前端发布脚本(内联 remote/deploy.sh,参数通过环境变量传入)
*/
export function buildFrontendDeployScript(frontend: FrontendSection, releaseName: string): string {
const body = fs.readFileSync(path.join(REMOTE_SCRIPT_DIR, 'deploy.sh'), 'utf8');
return [
'set -euo pipefail',
`RELEASE=${quoteForBash(frontendReleaseDir(frontend, releaseName))}`,
`BASE=${quoteForBash(frontend.basePath)}`,
`KEEP=${frontend.keepReleases}`,
`HOST=${quoteForBash(frontend.siteHost)}`,
'mkdir -p "$RELEASE"',
// 失败时清理未上线的版本目录(current 软链未切换,线上不受影响)
'FRONTEND_OK=0',
'cleanup_frontend_on_fail() {',
' RC=$?',
' if [ "$FRONTEND_OK" != "1" ]; then',
' CURRENT_TARGET="$(readlink -f "$BASE/current" 2>/dev/null || true)"',
' RELEASE_TARGET="$(readlink -f "$RELEASE" 2>/dev/null || echo "$RELEASE")"',
' if [ "$CURRENT_TARGET" != "$RELEASE_TARGET" ]; then',
' echo "前端发布失败,清理未上线目录 $RELEASE" >&2',
' rm -rf "$RELEASE"',
' fi',
' fi',
' exit $RC',
'}',
'trap cleanup_frontend_on_fail EXIT',
'',
body,
'',
'FRONTEND_OK=1',
`echo "FRONTEND_DEPLOY_OK release=${releaseName}"`,
].join('\n');
}
/**
* 前端回滚脚本(内联 remote/rollback.sh):current 软链接切回上一个版本。
*/
export function buildFrontendRollbackScript(frontend: FrontendSection): string {
const body = fs.readFileSync(path.join(REMOTE_SCRIPT_DIR, 'rollback.sh'), 'utf8');
return [
'set -euo pipefail',
`BASE=${quoteForBash(frontend.basePath)}`,
'',
body,
].join('\n');
}

52
tools/src/lib/git.ts Normal file
View File

@ -0,0 +1,52 @@
import { REPO_ROOT } from './paths';
import { runCommand } from './shell';
export interface GitInfo {
branch: string;
commit: string;
commitFull: string;
dirty: boolean;
dirtyFiles: string[];
}
/**
* 读取当前仓库 git 信息(用于发布约束与版本记录)。
*/
export function getGitInfo(): GitInfo {
const safe = (args: string[], fallback = ''): string => {
try {
return runCommand('git', args, { cwd: REPO_ROOT });
} catch {
return fallback;
}
};
const status = safe([ 'status', '--porcelain' ]);
return {
branch: safe([ 'rev-parse', '--abbrev-ref', 'HEAD' ], 'unknown'),
commit: safe([ 'rev-parse', '--short', 'HEAD' ], 'unknown'),
commitFull: safe([ 'rev-parse', 'HEAD' ], 'unknown'),
dirty: Boolean(status),
dirtyFiles: status ? status.split(/\r?\n/).filter(Boolean) : [],
};
}
/**
* 发布受限于 git:工作区有未提交改动时默认禁止发布。
*/
export function assertCleanWorktree(info: GitInfo, allowDirtyConfig: boolean, allowDirtyFlag: boolean): void {
if (!info.dirty) return;
if (allowDirtyConfig || allowDirtyFlag) {
console.warn(`[WARN] 工作区有 ${info.dirtyFiles.length} 个未提交改动,本次仍继续发布(版本记录会标记 dirty)。`);
return;
}
const preview = info.dirtyFiles.slice(0, 10).join('\n');
const more = info.dirtyFiles.length > 10 ? `\n...另有 ${info.dirtyFiles.length - 10} 个文件` : '';
throw new Error(
`工作区存在未提交改动(${info.dirtyFiles.length} 个文件),发布受 git 约束,请先提交;` +
`确认要带改动发布可加 --allow-dirty。\n${preview}${more}`
);
}

23
tools/src/lib/paths.ts Normal file
View File

@ -0,0 +1,23 @@
import path from 'node:path';
/** tools 包根目录(本文件位于 src/lib 或 dist/lib,上溯两级即为包根) */
export const TOOLS_ROOT = path.resolve(__dirname, '..', '..');
export const REPO_ROOT = path.resolve(TOOLS_ROOT, '..');
export const BACKEND_ROOT = path.join(REPO_ROOT, 'backend');
export const FRONTEND_ROOT = path.join(REPO_ROOT, 'frontend');
export const CONFIG_DIR = path.join(TOOLS_ROOT, 'config');
export const DEPLOY_CONFIG_PATH = path.join(CONFIG_DIR, 'deploy.config.local.cjs');
export const DEPLOY_CONFIG_EXAMPLE_PATH = path.join(CONFIG_DIR, 'deploy.config.example.cjs');
export const ENV_EXAMPLE_PATH = path.join(CONFIG_DIR, 'env.production.example');
/** 前端服务器端 bash 脚本目录 */
export const REMOTE_SCRIPT_DIR = path.join(TOOLS_ROOT, 'remote');
/** 本地临时工作目录(发布包、文件清单,已被 .gitignore 排除) */
export const TEMP_DIR = path.join(TOOLS_ROOT, 'temp');
/** 生成相对 tools 根目录的展示路径,便于日志/报错里引用 */
export function displayPath(targetPath: string): string {
const relative = path.relative(TOOLS_ROOT, targetPath);
return relative && !relative.startsWith('..') ? relative.replace(/\\/g, '/') : targetPath;
}

View File

@ -0,0 +1,170 @@
import { quoteForBash, shellValue } from './shell';
/** 端口既可传数字,也可传远端 shell 变量表达式(如 `$TARGET_PORT`) */
export type PortToken = number | string;
function portValue(port: PortToken): string {
return typeof port === 'number' ? String(port) : port;
}
/** 远端按端口停止进程的 bash 函数(Egg 多进程时终止监听进程) */
export const BASH_KILL_PORT_FUNCTION = [
'kill_port() {',
' PORT="$1"',
' if [ -z "$PORT" ]; then return 0; fi',
` PID=$(ss -tlnp 2>/dev/null | awk -v p=":$PORT " 'index($0, p)' | grep -oP 'pid=\\K[0-9]+' | head -1 || true)`,
' if [ -z "$PID" ]; then',
' echo "端口 $PORT 空闲"',
' return 0',
' fi',
' echo "停止端口 $PORT 上的进程 $PID"',
' kill "$PID" 2>/dev/null || true',
' sleep 3',
' if ss -tln 2>/dev/null | grep -q ":$PORT "; then',
' echo "端口 $PORT 仍被占用,强制停止 $PID"',
' kill -9 "$PID" 2>/dev/null || true',
' fuser -k "$PORT/tcp" 2>/dev/null || true',
' fi',
'}',
].join('\n');
/**
* 生成「启动实例」的远端脚本行(后台运行,输出重定向到启动日志)。
* 端口通过 EGG_PORT 注入:dotenv 不覆盖已存在的环境变量,因此优先于 .env 里的设置。
*/
export function buildStartInstanceLines(dirPath: string, startCommand: string, logPath: string, port?: PortToken): string[] {
const envPrefix = port === undefined ? '' : `EGG_PORT="${portValue(port)}" `;
const portLabel = port === undefined ? '默认' : portValue(port);
return [
`mkdir -p $(dirname ${shellValue(logPath)})`,
`cd ${shellValue(dirPath)}`,
`${envPrefix}nohup bash -lc ${quoteForBash(startCommand)} > ${shellValue(logPath)} 2>&1 < /dev/null &`,
`echo "已启动实例: ${dirPath}(端口 ${portLabel}),启动日志: ${logPath}"`,
];
}
/**
* 生成「健康检查」的远端脚本行(轮询 http://127.0.0.1:<端口><路径>)
*/
export function buildHealthCheckLines(
port: PortToken,
healthPath: string,
label: string,
attempts = 10,
interval = 2
): string[] {
return [
`TARGET_PORT="${portValue(port)}"`,
`HEALTH_PATH=${quoteForBash(healthPath)}`,
'HEALTH_OK=0',
`for attempt in $(seq 1 ${attempts}); do`,
' if curl -fsS --connect-timeout 2 --max-time 5 "http://127.0.0.1:$TARGET_PORT$HEALTH_PATH" >/dev/null 2>&1; then',
' HEALTH_OK=1',
' break',
' fi',
` echo "健康检查等待中($attempt/${attempts})..."`,
` sleep ${interval}`,
'done',
'if [ "$HEALTH_OK" != "1" ]; then',
` echo "健康检查失败: ${label}(端口 $TARGET_PORT) $HEALTH_PATH" >&2`,
' exit 1',
'fi',
`echo "健康检查通过: ${label}(端口 $TARGET_PORT)"`,
];
}
/**
* 生成「写 Nginx upstream 并 reload」的远端脚本行;两者可独立关闭。
*/
export function buildNginxSwitchLines(upstreamPath: string, reloadCommand: string, port: PortToken): string[] {
const lines: string[] = [];
if (upstreamPath) {
lines.push(
`printf 'proxy_pass http://127.0.0.1:%s;\\n' "${portValue(port)}" > ${quoteForBash(`${upstreamPath}.tmp`)}`,
`mv ${quoteForBash(`${upstreamPath}.tmp`)} ${quoteForBash(upstreamPath)}`,
`echo "Nginx upstream 已切换至 127.0.0.1:${portValue(port)}"`
);
}
if (reloadCommand) {
lines.push(
`if ${reloadCommand}; then`,
' echo "Nginx 已重载"',
'else',
' echo "[WARN] Nginx 重载失败,请人工执行 nginx -t && nginx -s reload" >&2',
'fi'
);
}
return lines;
}
/**
* 生成远端清理守卫:`find . -mindepth 1 -maxdepth 1 <守卫> -exec rm -rf {} +`
* 保留 .deploy 与 sharedDirs(logs / run / node_modules 等)
*/
export function buildRemoteCleanupGuard(sharedDirs: string[]): string {
const preserved = [ '.deploy', ...sharedDirs ];
return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' ');
}
/**
* 生成「按目录停止 egg 进程」的远端脚本行(精确匹配版本目录,避免 v1/v2 互相误杀)。
*/
export function buildScopedEggStopLines(dirPath: string, label: string): string[] {
const matchNode = '$2 == "node" || $2 ~ /\\/node$/';
const awkProgram = `index($0, root) && (${matchNode}) { print $1 }`;
return [
`STOP_DIR=${shellValue(dirPath)}`,
`STOP_PIDS=$(ps -eo pid=,args= | awk -v root="$STOP_DIR" ${quoteForBash(awkProgram)})`,
'if [ -z "$STOP_PIDS" ]; then',
` echo "${label}_NONE"`,
'else',
` echo "${label} $STOP_PIDS"`,
' kill $STOP_PIDS || true',
' sleep 3',
` REMAIN_PIDS=$(ps -eo pid=,args= | awk -v root="$STOP_DIR" ${quoteForBash(awkProgram)})`,
' if [ -n "$REMAIN_PIDS" ]; then',
` echo "${label}_FORCE $REMAIN_PIDS"`,
' kill -9 $REMAIN_PIDS || true',
' fi',
'fi',
];
}
/**
* 生成「应用服务端共享配置」的远端脚本行(依赖远端变量 TARGET_DIR):
* shared-config/config.*.js → 版本目录 config/
* shared-config/<envFile> → 版本目录 .env(每次覆盖)
* 老部署的 <deployRoot>/<envFile> 会在首次自动迁移为共享配置。
*/
export function buildSharedConfigLines(sharedConfigDir: string, envFile: string, deployRoot: string): string[] {
if (!sharedConfigDir) return [ 'echo "未配置 sharedConfigDir,跳过共享配置"' ];
const sharedEnvPath = `${sharedConfigDir}/${envFile}`;
const legacyEnvPath = `${deployRoot}/${envFile}`;
return [
`SHARED_CONFIG_DIR=${quoteForBash(sharedConfigDir)}`,
`SHARED_ENV_FILE=${quoteForBash(sharedEnvPath)}`,
'mkdir -p "$SHARED_CONFIG_DIR" "$TARGET_DIR/config"',
'if [ ! -f "$SHARED_ENV_FILE" ]; then',
` if [ -f ${quoteForBash(legacyEnvPath)} ]; then`,
` cp -a ${quoteForBash(legacyEnvPath)} "$SHARED_ENV_FILE"`,
` echo "已将老配置 ${legacyEnvPath} 迁移为共享配置 $SHARED_ENV_FILE"`,
' fi',
'fi',
'for f in "$SHARED_CONFIG_DIR"/config.*.js; do',
' [ -e "$f" ] || continue',
' cp -a "$f" "$TARGET_DIR/config/"',
' echo "已应用共享配置: $(basename "$f")"',
'done',
'if [ -f "$SHARED_ENV_FILE" ]; then',
' cp -a "$SHARED_ENV_FILE" "$TARGET_DIR/.env"',
' echo "已应用共享环境变量: $SHARED_ENV_FILE → $TARGET_DIR/.env"',
'else',
' echo "[WARN] 未找到共享环境变量 $SHARED_ENV_FILE(本地可用 envFileLocalPath 上传覆盖)" >&2',
'fi',
];
}

89
tools/src/lib/shell.ts Normal file
View File

@ -0,0 +1,89 @@
import { spawnSync } from 'node:child_process';
import type { StdioOptions } from 'node:child_process';
import { REPO_ROOT } from './paths';
export interface RunOptions {
cwd?: string;
stdio?: StdioOptions;
input?: string;
}
/**
* 执行本地命令并返回 stdout(trim 后);非零退出码抛错。
*/
export function runCommand(command: string, args: string[], options: RunOptions = {}): string {
const result = spawnSync(command, args, {
cwd: options.cwd || REPO_ROOT,
encoding: 'utf8',
stdio: options.stdio || 'pipe',
input: options.input,
shell: false,
});
if (result.error) throw result.error;
if (typeof result.status === 'number' && result.status !== 0) {
const stderr = (result.stderr || '').trim();
const stdout = (result.stdout || '').trim();
throw new Error(stderr || stdout || `${command} 退出码 ${result.status}`);
}
return (result.stdout || '').trim();
}
/**
* 前台执行本地命令(输出直通终端);非零退出码抛错。
*/
export function runForeground(command: string, args: string[], cwd?: string, shell = false): void {
const result = spawnSync(command, args, { cwd: cwd || REPO_ROOT, stdio: 'inherit', shell });
if (result.error) throw result.error;
if (typeof result.status === 'number' && result.status !== 0) {
throw new Error(`${command} ${args.join(' ')} 退出码 ${result.status}`);
}
}
/**
* 在指定项目目录执行 npm 脚本。
* Windows 下 npm 入口是 npm.cmd,spawnSync 无法直接执行(EINVAL):
* 优先用当前 node 直接跑 npm-cli.js,拿不到时退回 shell。
*/
export function runNpm(args: string[], cwd: string): void {
const npmCli = process.env.npm_execpath;
if (process.platform === 'win32') {
if (npmCli && /npm-cli\.js$/i.test(npmCli)) {
runForeground(process.execPath, [npmCli, ...args], cwd);
return;
}
runForeground('npm.cmd', args, cwd, true);
return;
}
runForeground('npm', args, cwd);
}
/**
* 检查本地命令是否存在,不存在时给出安装提示。
*/
export function ensureCommandAvailable(command: string, installHint: string): void {
const result = spawnSync(command, [], { cwd: REPO_ROOT, encoding: 'utf8', stdio: 'pipe', shell: false });
if (result.error && (result.error as NodeJS.ErrnoException).code === 'ENOENT') {
throw new Error(`${command} 不可用。${installHint}`);
}
}
/**
* bash 单引号字符串里的单引号转义(' → '\'')。
*/
export function quoteForBash(value: string | number): string {
return `'${String(value).replace(/'/g, "'\\''")}'`;
}
/**
* 远端 shell 片段里的路径/取值:`$` 开头视为远端变量表达式(加双引号防空格),
* 其余按字面量单引号转义。
*/
export function shellValue(value: string): string {
return value.trim().startsWith('$') ? `"${value}"` : quoteForBash(value);
}

109
tools/src/lib/ssh.ts Normal file
View File

@ -0,0 +1,109 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { REPO_ROOT } from './paths';
import { quoteForBash, runCommand } from './shell';
/** 统一的 SSH 连接参数(后端 .cjs 配置与前端 .json 配置都会归一化成它) */
export interface SshTarget {
host: string;
port: number;
username: string;
/** 私钥路径;为空表示使用 ssh 默认密钥/agent */
privateKeyPath: string;
sshOptions: string[];
}
/** 后端沿用的「只允许公钥、禁止交互」加固选项 */
export const GUARDED_SSH_OPTIONS = [
'IdentitiesOnly=yes',
'PreferredAuthentications=publickey',
'PubkeyAuthentication=yes',
'PasswordAuthentication=no',
'KbdInteractiveAuthentication=no',
'BatchMode=yes',
'ConnectTimeout=10',
];
/**
* 合并用户选项与加固选项(同名选项以用户配置为准)。
*/
export function withGuardedOptions(options: string[]): string[] {
const merged = [ ...options ];
for (const option of GUARDED_SSH_OPTIONS) {
const key = option.split('=')[0];
if (!merged.some(item => new RegExp(`^${key}=`, 'i').test(item))) merged.push(option);
}
return merged;
}
/**
* 解析私钥路径:支持 `~/...`、绝对路径,其余按仓库根目录解析;空值表示不指定。
*/
export function resolvePrivateKeyPath(value: string | undefined): string {
if (!value) return '';
if (value.startsWith('~')) return path.join(os.homedir(), value.slice(1));
if (path.isAbsolute(value)) return value;
return path.resolve(REPO_ROOT, value);
}
/**
* 校验私钥文件存在(配置了私钥但文件缺失时提前报错,而不是等 ssh 失败)。
*/
export function assertPrivateKeyExists(target: SshTarget, configPath: string): void {
if (!target.privateKeyPath) return;
if (!fs.existsSync(target.privateKeyPath)) {
throw new Error(`SSH 私钥不存在: ${target.privateKeyPath}。请修正 ${configPath} 中的私钥路径。`);
}
}
export function buildSshArgs(target: SshTarget): string[] {
const args = [ '-p', String(target.port) ];
if (target.privateKeyPath) args.push('-i', target.privateKeyPath);
for (const option of target.sshOptions) args.push('-o', option);
return args;
}
export function buildScpArgs(target: SshTarget): string[] {
const args = [ '-P', String(target.port) ];
if (target.privateKeyPath) args.push('-i', target.privateKeyPath);
for (const option of target.sshOptions) args.push('-o', option);
return args;
}
/**
* 在服务器上执行 bash 脚本(通过 bash -lc,保证加载登录环境里的 node/npm)。
*/
export function runSsh(target: SshTarget, remoteScript: string, stdio: 'pipe' | 'inherit' = 'inherit'): string {
const args = [
...buildSshArgs(target),
`${target.username}@${target.host}`,
`bash -lc ${quoteForBash(remoteScript)}`,
];
return runCommand('ssh', args, { stdio });
}
/**
* 通过 stdin 把本地 bash 脚本送到服务器执行(`[ENV=...] bash -s`)。
*/
export function runRemoteScript(target: SshTarget, script: string, env: Record<string, string | number> = {}): void {
const envPrefix = Object.entries(env)
.map(([ key, value ]) => `${key}=${quoteForBash(value)}`)
.join(' ');
const command = envPrefix ? `${envPrefix} bash -s` : 'bash -s';
runCommand('ssh', [ ...buildSshArgs(target), `${target.username}@${target.host}`, command ], {
// 用 stdin 传脚本,stdout/stderr 直通终端
stdio: [ 'pipe', 'inherit', 'inherit' ],
input: script,
});
}
/**
* 上传文件到服务器。
*/
export function runScp(target: SshTarget, localPath: string, remotePath: string): string {
return runCommand('scp', [ ...buildScpArgs(target), localPath, `${target.username}@${target.host}:${remotePath}` ], {
stdio: 'inherit',
});
}

19
tools/src/lib/time.ts Normal file
View File

@ -0,0 +1,19 @@
function pad(value: number): string {
return String(value).padStart(2, '0');
}
/** yyyyMMddHHmmss 时间戳 */
export function getNowStamp(date: Date = new Date()): string {
return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
}
/** 前端发布版本名:v<yyyyMMdd_HHmmss>_<pid>(带 PID,避免并发/重复发布冲突) */
export function getReleaseName(date: Date = new Date()): string {
const stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
return `v${stamp}_${process.pid}`;
}
/** ISO 时间(写入版本记录) */
export function getIsoTime(date: Date = new Date()): string {
return date.toISOString();
}

View File

@ -0,0 +1,38 @@
import type { DeployConfig } from './config';
import { quoteForBash } from './shell';
import { runSsh } from './ssh';
export interface VersionEntry {
version: string;
commit: string;
branch: string;
env: string;
dirty: boolean;
targets: string[];
frontendRelease: string;
operator: string;
time: string;
files: number;
size: number;
}
/**
* 追加一条发布版本记录到远端 <deployRoot>/.deploy/state/versions.jsonl(保留最近 keepVersions 条)。
*/
export function recordVersion(config: DeployConfig, entry: VersionEntry): void {
const backend = config.backend;
if (!backend) return;
const stateFile = `${backend.stateDir}/versions.jsonl`;
runSsh(config, [
'set -euo pipefail',
`STATE_FILE=${quoteForBash(stateFile)}`,
`KEEP=${config.keepVersions}`,
'mkdir -p "$(dirname "$STATE_FILE")"',
`ENTRY_JSON=${quoteForBash(JSON.stringify(entry))}`,
`printf '%s\\n' "$ENTRY_JSON" >> "$STATE_FILE"`,
'tail -n "$KEEP" "$STATE_FILE" > "$STATE_FILE.tmp" && mv "$STATE_FILE.tmp" "$STATE_FILE"',
'echo "版本记录已写入 $STATE_FILE"',
].join('\n'), 'pipe');
}

21
tools/tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "node16",
"moduleResolution": "node16",
"lib": ["ES2022"],
"rootDir": "src",
"outDir": "dist",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"sourceMap": true,
"declaration": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist"]
}