packServer/backend/scripts/deploy/deploy-lib.cjs
liufumingren 228723e0c3 设备端扫码上报 + 桌面端/Android 正式包发布脚手架
AndroidStation(原中控改造为纯设备端)
- 只做三件事:UDP 48899 被桌面端发现、TCP 8087 推送 USB 扫码结果、离线语音播报
- 扫码不再经过 UI:去掉逐键重绘,50ms 自动提交,同一码重复扫码也一律上报
- 离线语音种子(数字/字母/“开始打包”/欢迎语)随包安装,MediaPlayer 播放,启动把音量拉满
- 启动播报「欢迎使用溯源系统,初始化已经完成,扫码即可开始打包」
- 移除 Device Owner / 设备管理员 / lock task / 网络与 IP 设置等非普通应用能力(仅保留开机自启)
- 正式签名 keystore + release 签名配置,versionName/versionCode 可由打包脚本覆盖

发布脚手架
- backend/android_client:Android 正式包构建(build.ps1 + package.config.json)
- backend/scripts/deploy/publish-android.cjs + npm run android:build / android:publish
- 桌面端安装包改为 download/desktop,Android 为 download/android_client;
  version.json 仍走 /download/version.json(老客户端写死),新增 /download/android_client/version.json
- 谷歌插件随桌面端 MSI 安装到 <安装目录>\extension,工具菜单新增「复制谷歌插件地址」
- git-safety-check 增加仓库级禁区(keystore.properties / *.jks / local.properties)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-21 05:53:27 +08:00

708 lines
25 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 发布脚手架公共库(参考 D:\wms\script\deploy-lib.cjs)
*
* 约定:
* - 远端采用 v1 / v2 双实例目录 + current.md 记录当前活跃版本,健康检查通过后才切 Nginx upstream;
* - 发布包只包含 git 跟踪的后端源码;前端构建产物单独发布到 deployRoot/frontend,由 nginx 直接托管;
* - 服务端私有配置(config/config.prod.js 等)与运行期目录(logs/run/temp、安装包)在发布前暂存、发布后放回。
*/
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
/** backend 根目录 */
const ROOT = path.resolve(__dirname, '..', '..');
/** git 仓库根目录(monorepo 根) */
const REPO_ROOT = path.resolve(ROOT, '..');
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 DEFAULT_PORTS = { v1: 7301, v2: 7302 };
/** 发布包包含的后端源码路径(相对 backend/) */
const DEFAULT_INCLUDE_PATHS = [
'.sequelizerc',
'jsconfig.json',
'package.json',
'package-lock.json',
'app/**',
'config/**',
'database/**',
'scripts/**',
'sql/**',
];
/** 默认保留的服务端私有文件/目录(清理前暂存,解压后放回) */
const DEFAULT_PRESERVE_PATHS = [
'config/config.prod.js',
'config/config.local.js',
'app/public/download',
'app/public/version',
];
/** 服务端托管的运行期目录:清理代码时保留 */
const DEFAULT_SHARED_DIRS = [ 'node_modules', 'logs', 'run', 'temp' ];
/** 无论配置怎么写都不允许进入发布包的私有配置 */
function isServerManagedConfig(relativePath) {
const normalized = String(relativePath || '').replace(/\\/g, '/');
const baseName = normalized.split('/').pop();
if (!normalized.startsWith('config/')) {
return false;
}
return baseName === 'config.prod.js'
|| baseName === 'config.local.js'
|| /^deploy\.config\..*\.cjs$/.test(baseName)
|| /^env\..*\.sh$/.test(baseName)
|| /\.local\.js$/.test(baseName);
}
function quoteForBash(value) {
return `'${String(value).replace(/'/g, "'\"'\"'")}'`;
}
function runCommand(command, args, options = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd || ROOT,
encoding: 'utf8',
stdio: options.stdio || 'pipe',
shell: Boolean(options.shell),
});
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} exited with code ${result.status}`);
}
return (result.stdout || '').trim();
}
function runNpm(args, cwd) {
if (process.platform === 'win32') {
const comspec = process.env.ComSpec || 'cmd.exe';
return runCommand(comspec, [ '/d', '/s', '/c', `npm ${args.join(' ')}` ], {
cwd: cwd || ROOT,
stdio: 'inherit',
});
}
return runCommand('npm', args, {
cwd: cwd || ROOT,
stdio: 'inherit',
});
}
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}`);
}
}
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())}`;
}
function ensureTempDeployDir() {
const tempDir = path.join(ROOT, 'temp', 'deploy');
fs.mkdirSync(tempDir, { recursive: true });
return tempDir;
}
function isPlaceholder(value) {
if (!value) {
return true;
}
return String(value).includes('__FILL_');
}
function normalizeDeployConfig(config, envName) {
const deployRoot = String(config.deployRoot || '/www/wwwroot/packService').replace(/\/+$/, '');
const privateKeyPath = config.privateKeyPath ? path.resolve(ROOT, config.privateKeyPath) : '';
const ports = {
v1: Number((config.ports && config.ports.v1) || DEFAULT_PORTS.v1),
v2: Number((config.ports && config.ports.v2) || DEFAULT_PORTS.v2),
};
if (!Number.isInteger(ports.v1) || !Number.isInteger(ports.v2) || ports.v1 === ports.v2) {
throw new Error(`部署端口配置无效: ${JSON.stringify(ports)},v1 / v2 必须是两个不同的整数端口。`);
}
const preservePaths = Array.isArray(config.preservePaths) && config.preservePaths.length > 0
? [ ...config.preservePaths ]
: [ ...DEFAULT_PRESERVE_PATHS ];
for (const item of preservePaths) {
if (path.posix.isAbsolute(String(item)) || String(item).split('/').includes('..')) {
throw new Error(`preservePaths 只允许 backend/ 下的相对路径: ${item}`);
}
}
const sshOptions = Array.isArray(config.sshOptions) ? [ ...config.sshOptions ] : [];
const requiredSshOptions = [
[ /^IdentitiesOnly=/i, 'IdentitiesOnly=yes' ],
[ /^PreferredAuthentications=/i, 'PreferredAuthentications=publickey' ],
[ /^PubkeyAuthentication=/i, 'PubkeyAuthentication=yes' ],
[ /^PasswordAuthentication=/i, 'PasswordAuthentication=no' ],
[ /^KbdInteractiveAuthentication=/i, 'KbdInteractiveAuthentication=no' ],
[ /^BatchMode=/i, 'BatchMode=yes' ],
[ /^ConnectTimeout=/i, 'ConnectTimeout=10' ],
];
for (const [ matcher, option ] of requiredSshOptions) {
if (!sshOptions.some(item => matcher.test(item))) {
sshOptions.push(option);
}
}
return {
envName,
host: config.host,
port: Number(config.port || 22),
username: config.username,
privateKeyPath,
deployRoot,
controlDir: `${deployRoot}/.deploy`,
incomingDir: `${deployRoot}/.deploy/incoming`,
backupDir: `${deployRoot}/.deploy/backups`,
stateDir: `${deployRoot}/.deploy/state`,
ports,
healthCheckPath: config.healthCheckPath || '/health',
healthCheckAttempts: Number(config.healthCheckAttempts || 30),
healthCheckInterval: Number(config.healthCheckInterval || 2),
nginxUpstreamFile: config.nginxUpstreamFile === undefined
? `${deployRoot}/nginx-upstream.conf`
: String(config.nginxUpstreamFile || ''),
// 服务端私有配置目录(不随发布包走):放 config.prod.js / config.local.js / env.prod.sh
sharedConfigDir: config.sharedConfigDir === undefined
? `${deployRoot}/shared-config`
: String(config.sharedConfigDir || ''),
envFile: config.envFile || 'env.prod.sh',
envFileLocalPath: path.resolve(ROOT, config.envFileLocalPath || path.join('config', config.envFile || 'env.prod.sh')),
uploadEnvFile: config.uploadEnvFile !== false,
sharedDirs: Array.isArray(config.sharedDirs) ? config.sharedDirs : [ ...DEFAULT_SHARED_DIRS ],
preservePaths,
keepBackups: Number(config.keepBackups || 5),
buildFrontend: config.buildFrontend !== false,
frontendDir: config.frontendDir || '../frontend',
frontendDeployDir: config.frontendDeployDir || `${deployRoot}/frontend`,
frontendPrevDir: `${config.frontendDeployDir || `${deployRoot}/frontend`}.prev`,
nginxFrontConf: config.nginxFrontConf === undefined ? `${deployRoot}/front.conf` : String(config.nginxFrontConf || ''),
manageNginxFrontConf: config.manageNginxFrontConf !== false,
serverName: config.serverName || '',
// 桌面端发布(npm run desktop:publish)
desktopBuildScript: config.desktopBuildScript || '../desktop/installer/build.ps1',
desktopOutDir: config.desktopOutDir || '../desktop/installer/out',
desktopDownloadDir: config.desktopDownloadDir || `${deployRoot}/download/desktop`,
// version.json 不放安装包目录里:nginx 对 /download/version.json 单独关缓存,安装包目录走长缓存
desktopVersionDir: config.desktopVersionDir || `${deployRoot}/download`,
desktopBaseUrl: config.desktopBaseUrl || (config.serverName ? `http://${config.serverName}` : ''),
desktopKeepVersions: Number(config.desktopKeepVersions || 5),
desktopOwner: config.desktopOwner || 'www:www',
// Android 设备端发布(npm run android:publish)
androidBuildScript: config.androidBuildScript || 'android_client/build.ps1',
androidOutDir: config.androidOutDir || 'android_client/out',
androidDownloadDir: config.androidDownloadDir || `${deployRoot}/download/android_client`,
androidVersionDir: config.androidVersionDir || config.androidDownloadDir || `${deployRoot}/download/android_client`,
androidBaseUrl: config.androidBaseUrl || config.desktopBaseUrl || (config.serverName ? `http://${config.serverName}` : ''),
androidKeepVersions: Number(config.androidKeepVersions || 5),
androidOwner: config.androidOwner || 'www:www',
remoteDbDeploy: Boolean(config.remoteDbDeploy),
deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length > 0
? [ ...config.deployIncludePaths ]
: [ ...DEFAULT_INCLUDE_PATHS ],
deployExcludePaths: Array.isArray(config.deployExcludePaths) ? [ ...config.deployExcludePaths ] : [],
sshOptions,
};
}
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 > 0) {
throw new Error(`请先完善 SSH 配置字段: ${missing.join(', ')}。配置文件: ${configPath}`);
}
const resolvedPrivateKeyPath = path.resolve(ROOT, config.privateKeyPath);
if (!fs.existsSync(resolvedPrivateKeyPath)) {
throw new Error(`SSH 私钥不存在: ${resolvedPrivateKeyPath}。请先修正 config/deploy.config.local.cjs 中的 privateKeyPath。`);
}
}
function loadDeployConfig(envName = DEFAULT_ENV) {
if (!fs.existsSync(LOCAL_CONFIG_PATH)) {
throw new Error(`缺少本地部署配置 ${LOCAL_CONFIG_PATH}。请复制 ${EXAMPLE_CONFIG_PATH} 并填入 SSH 信息。`);
}
delete require.cache[LOCAL_CONFIG_PATH];
const loaded = require(LOCAL_CONFIG_PATH);
const config = loaded[envName];
validateDeployConfig(config, LOCAL_CONFIG_PATH, envName);
return normalizeDeployConfig(config, envName);
}
function buildSshBaseArgs(config) {
const args = [ '-p', String(config.port), '-i', config.privateKeyPath ];
for (const option of config.sshOptions) {
args.push('-o', option);
}
return args;
}
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',
});
}
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' });
}
function normalizeRule(rule) {
return String(rule || '').replace(/\\/g, '/').trim();
}
function pathMatchesRule(filePath, rule) {
const normalizedPath = String(filePath || '').replace(/\\/g, '/');
const normalizedRule = normalizeRule(rule);
if (!normalizedRule) {
return false;
}
if (normalizedRule.endsWith('/**')) {
const prefix = normalizedRule.slice(0, -3);
return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`);
}
if (normalizedRule.endsWith('/')) {
return normalizedPath.startsWith(normalizedRule);
}
return normalizedPath === normalizedRule;
}
function listDeployableFiles(config) {
const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ]);
const includeRules = config.deployIncludePaths || DEFAULT_INCLUDE_PATHS;
const excludeRules = config.deployExcludePaths || [];
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 => includeRules.some(rule => pathMatchesRule(item, rule)))
.filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule)))
.filter(item => !isServerManagedConfig(item)),
));
}
function resolveFrontendDistDir(config) {
return path.resolve(ROOT, config.frontendDir, 'dist');
}
/**
* 生成发布包:只包含后端源码(前端由 buildFrontendArchive 单独发布)
*
* @param {string} stamp - 时间戳
* @param {object} config - 规范化后的部署配置
* @return {{ archivePath: string, fileCount: number }} 发布包路径与后端文件数量
*/
function buildArchive(stamp, config) {
const tempDir = ensureTempDeployDir();
const stageDir = path.join(tempDir, `stage-${stamp}`);
const archivePath = path.join(tempDir, `release-${stamp}.tar.gz`);
const files = listDeployableFiles(config);
if (files.length === 0) {
throw new Error('git ls-files 未返回可发布文件,无法生成发布包。');
}
fs.rmSync(stageDir, { recursive: true, force: true });
fs.mkdirSync(stageDir, { recursive: true });
for (const relativePath of files) {
const source = path.join(ROOT, relativePath);
const destination = path.join(stageDir, relativePath);
fs.mkdirSync(path.dirname(destination), { recursive: true });
fs.copyFileSync(source, destination);
}
try {
runCommand('tar', [ '-czf', archivePath, '-C', stageDir, '.' ], { stdio: 'inherit' });
} finally {
fs.rmSync(stageDir, { recursive: true, force: true });
}
return { archivePath, fileCount: files.length };
}
/**
* 生成前端发布包(frontend/dist → nginx 静态目录)
*
* @param {string} stamp - 时间戳
* @param {object} config - 部署配置
* @return {{ archivePath: string }} 前端发布包路径
*/
function buildFrontendArchive(stamp, config) {
const distDir = resolveFrontendDistDir(config);
if (!fs.existsSync(path.join(distDir, 'index.html'))) {
throw new Error(`前端构建产物不存在: ${path.join(distDir, 'index.html')}。请先执行 frontend 的 npm run build。`);
}
const archivePath = path.join(ensureTempDeployDir(), `frontend-${stamp}.tar.gz`);
runCommand('tar', [ '-czf', archivePath, '-C', distDir, '.' ], { stdio: 'inherit' });
return { archivePath };
}
/** 生成由 nginx 直接托管的前端 / 反代配置(front.conf) */
function buildFrontConf(config) {
const upstreamInclude = config.nginxUpstreamFile
? ` include ${config.nginxUpstreamFile};\n`
: '';
const proxyCommon = [
' proxy_set_header Host $http_host;',
' proxy_set_header X-Real-IP $remote_addr;',
' proxy_set_header X-Real-Port $remote_port;',
' proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;',
' proxy_set_header X-Forwarded-Proto $scheme;',
' proxy_set_header X-Forwarded-Host $host;',
' proxy_set_header X-Forwarded-Port $server_port;',
' proxy_connect_timeout 60s;',
' proxy_send_timeout 600s;',
' proxy_read_timeout 600s;',
' proxy_http_version 1.1;',
' proxy_set_header Upgrade $http_upgrade;',
' proxy_set_header Connection $connection_upgrade;',
].join('\n');
const proxyLocation = name => [
`${name} {`,
upstreamInclude + proxyCommon,
'}',
].join('\n');
// nginx 的 add_header 一旦在 location 里出现就不会继承 server 级配置,
// 因此每个自带 add_header 的 location 都要重复声明 HSTS。
const hsts = ' add_header Strict-Transport-Security "max-age=31536000" always;';
return [
'# 由 packService 发布脚本自动维护,请勿手工修改(改模板见 backend/scripts/deploy/deploy-lib.cjs)',
'',
'location / {',
` root ${config.frontendDeployDir};`,
' index index.html;',
hsts,
' try_files $uri $uri/ /index.html;',
'}',
'',
'location = /index.html {',
` root ${config.frontendDeployDir};`,
' add_header Cache-Control "no-cache, no-store, must-revalidate";',
hsts,
'}',
'',
'location ^~ /assets/ {',
` root ${config.frontendDeployDir};`,
' expires 30d;',
' add_header Cache-Control "public, immutable";',
hsts,
' try_files $uri =404;',
'}',
'',
...(config.nginxUpstreamFile
? [
proxyLocation('location ^~ /api/'),
'',
proxyLocation('location = /health'),
]
: [ '# nginxUpstreamFile 未配置,跳过 /api、/health 反代' ]),
'',
'# 桌面端 / Android 安装包:由 nginx 直接托管 deployRoot/download',
'# download/desktop/*.msi、download/android_client/*.apk 长缓存;',
'# version.json 一律不缓存(客户端靠它判断有没有新版本)。',
'location = /download/version.json {',
` root ${config.deployRoot};`,
' default_type application/json;',
' add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";',
' add_header Pragma "no-cache";',
hsts,
' expires 0;',
'}',
'',
'location = /download/android_client/version.json {',
` root ${config.deployRoot};`,
' default_type application/json;',
' add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";',
' add_header Pragma "no-cache";',
hsts,
' expires 0;',
'}',
'',
'location ^~ /download/ {',
` root ${config.deployRoot};`,
' expires 30d;',
' add_header Cache-Control "public";',
hsts,
' try_files $uri =404;',
'}',
'',
].join('\n');
}
function buildRemoteCleanupGuard(sharedDirs) {
const preserved = Array.from(new Set([ ...sharedDirs ]));
return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' ');
}
/**
* 写 front.conf(静态 /download + /api 反代)并 reload nginx
*
* 桌面端 / Android 发布脚本共用:只动静态托管配置,不碰 Egg 进程。
*/
function refreshNginx(config) {
if (!config.manageNginxFrontConf || !config.nginxFrontConf) {
console.log('未启用 nginxFrontConf 维护,跳过 nginx 配置更新。');
return;
}
const base64 = Buffer.from(buildFrontConf(config), 'utf8').toString('base64');
runSsh(config, [
'set -euo pipefail',
`TARGET=${quoteForBash(config.nginxFrontConf)}`,
'mkdir -p "$(dirname "$TARGET")"',
`printf '%s' ${quoteForBash(base64)} | base64 -d > "$TARGET"`,
'echo "FRONT_CONF_WRITTEN"',
].join('\n'), { stdio: 'pipe' });
try {
runSsh(config, 'set -euo pipefail; nginx -t && nginx -s reload', { stdio: 'pipe' });
console.log(`nginx 已刷新: ${config.nginxFrontConf}`);
} catch (err) {
console.warn(`[WARN] nginx reload 失败: ${err.message}`);
console.warn('[WARN] 请人工执行 nginx -t && nginx -s reload');
}
}
/**
* 生成「服务端私有文件保护」远端脚本行(发布 / 回退共用)
*
* @param {string} dirVar - 目标目录变量名,如 TARGET_DIR
* @param {string} stashDirVar - 暂存目录变量名,如 PINNED_DIR
* @param {string[]} preservePaths - backend/ 下的相对路径(文件或目录)
* @return {{ stash: string[], restore: string[] }} 远端脚本行
*/
function buildPinnedPathGuardLines(dirVar, stashDirVar, preservePaths) {
const quoted = preservePaths.map(quoteForBash);
const stash = [
`mkdir -p "$${stashDirVar}"`,
`for REL in ${quoted.join(' ')}; do`,
` if [ -e "$${dirVar}/$REL" ]; then`,
` mkdir -p "$${stashDirVar}/$(dirname "$REL")"`,
` rm -rf "$${stashDirVar}/$REL"`,
` cp -a "$${dirVar}/$REL" "$${stashDirVar}/$REL" && echo "PINNED_SAVED $REL"`,
' fi',
'done',
];
const restore = [
`for REL in ${quoted.join(' ')}; do`,
` if [ -e "$${stashDirVar}/$REL" ]; then`,
` rm -rf "$${dirVar}/$REL"`,
` mkdir -p "$${dirVar}/$(dirname "$REL")"`,
` cp -a "$${stashDirVar}/$REL" "$${dirVar}/$REL" && echo "PINNED_RESTORED $REL"`,
' fi',
'done',
`rm -rf "$${stashDirVar}"`,
];
return { stash, restore };
}
/** 生成释放指定端口的远端脚本 */
function buildKillPortScript(port) {
return [
'set -euo pipefail',
`TARGET_PORT=${Number(port)}`,
"PORT_PID=$(ss -tlnp 2>/dev/null | awk -v p=\":$TARGET_PORT \" 'index($0, p)' | 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)' | grep -oP 'pid=\\K[0-9]+' | head -1 || true)",
' if [ -n "$PORT_PID_CHECK" ]; then',
' echo "[WARN] 端口 $TARGET_PORT 仍有进程 $PORT_PID_CHECK,强制停止..."',
' kill -9 "$PORT_PID_CHECK" 2>/dev/null || true',
' fuser -k "$TARGET_PORT/tcp" 2>/dev/null || true',
' fi',
' echo "端口 $TARGET_PORT 已释放"',
'else',
' echo "端口 $TARGET_PORT 空闲,无需清理"',
'fi',
].join('\n');
}
/** 远端环境变量文件(由 start 脚本 source,里面的变量会导出给 npm start) */
function getRemoteEnvFile(config) {
if (!config.sharedConfigDir) {
return '';
}
return `${config.sharedConfigDir}/${config.envFile}`;
}
/** 生成在指定目录启动实例的远端脚本(前端已由 nginx 托管,不再注入 FRONTEND_DIST) */
function buildStartScript({ dir, port, envFile, logPath }) {
const envLines = envFile
? [
`if [ -f ${quoteForBash(envFile)} ]; then`,
` set -a; . ${quoteForBash(envFile)}; set +a`,
` echo "已加载服务端环境变量: ${envFile}"`,
'fi',
]
: [];
return [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(dir)}`,
'cd "$TARGET_DIR"',
...envLines,
`PORT=${Number(port)} nohup bash -lc 'npm start' > ${quoteForBash(logPath)} 2>&1 &`,
`echo "已在 $TARGET_DIR 启动实例(PORT=${port}),启动日志: ${logPath}"`,
].join('\n');
}
/** 生成健康检查远端脚本(失败退出码 1) */
function buildHealthCheckScript({ port, healthPath, attempts, interval }) {
return [
'set -euo pipefail',
`TARGET_PORT=${Number(port)}`,
`HEALTH_PATH=${quoteForBash(healthPath || '/health')}`,
`for attempt in $(seq 1 ${Number(attempts || 30)}); do`,
' if curl -fsS --connect-timeout 2 --max-time 5 "http://127.0.0.1:$TARGET_PORT$HEALTH_PATH" >/dev/null 2>&1; then',
' echo "健康检查通过: http://127.0.0.1:$TARGET_PORT$HEALTH_PATH"',
' exit 0',
' fi',
` sleep ${Number(interval || 2)}`,
'done',
'echo "健康检查超时: http://127.0.0.1:$TARGET_PORT$HEALTH_PATH" >&2',
'exit 1',
].join('\n');
}
/** 生成停止指定目录实例的远端脚本(kill + kill -9 兜底) */
function buildStopDirScript(dir, label) {
const safeLabel = String(label || 'instance');
return [
'set -euo pipefail',
`OLD_DIR=${quoteForBash(dir)}`,
`OLD_LABEL=${quoteForBash(safeLabel)}`,
"OLD_PIDS=$(ps -eo pid=,args= | awk -v root=\"$OLD_DIR\" 'index($0, root) && $2 ~ /node$/ { print $1 }')",
'if [ -z "$OLD_PIDS" ]; then',
' echo "未找到 $OLD_LABEL 进程,跳过停止步骤"',
'else',
' echo "正在停止 $OLD_LABEL: $OLD_PIDS"',
' kill $OLD_PIDS || true',
' sleep 30',
" OLD_PIDS_REMAIN=$(ps -eo pid=,args= | awk -v root=\"$OLD_DIR\" 'index($0, root) && $2 ~ /node$/ { print $1 }')",
' if [ -n "$OLD_PIDS_REMAIN" ]; then',
' echo "$OLD_LABEL 仍有残留进程,强制停止: $OLD_PIDS_REMAIN"',
' kill -9 $OLD_PIDS_REMAIN || true',
' fi',
' echo "$OLD_LABEL 已停止"',
'fi',
].join('\n');
}
/** 生成切换 Nginx upstream 并 reload 的远端脚本 */
function buildNginxSwitchScript(upstreamFile, port) {
return [
'set -euo pipefail',
`printf 'proxy_pass http://127.0.0.1:%s;\\n' ${Number(port)} > ${quoteForBash(upstreamFile)}`,
'nginx -t && nginx -s reload',
`echo "Nginx upstream 已切换至 127.0.0.1:${Number(port)}"`,
].join('\n');
}
/**
* 生成把 JSON 写入远端文件的脚本行
*
* @param {string} stateDir - 远端目录
* @param {string} fileName - 文件名
* @param {object} payload - JSON 对象
* @param {boolean} append - true 追加(jsonl),false 覆盖
* @return {string[]} 远端脚本行
*/
function buildRemoteJsonWriteLines(stateDir, fileName, payload, append) {
const content = append
? `${JSON.stringify(payload)}\n`
: `${JSON.stringify(payload, null, 2)}\n`;
const base64 = Buffer.from(content, 'utf8').toString('base64');
return [
`printf '%s' ${quoteForBash(base64)} | base64 -d ${append ? '>>' : '>'} ${quoteForBash(`${stateDir}/${fileName}`)}`,
];
}
module.exports = {
EXAMPLE_CONFIG_PATH,
LOCAL_CONFIG_PATH,
REPO_ROOT,
ROOT,
buildArchive,
buildFrontConf,
buildFrontendArchive,
buildHealthCheckScript,
buildKillPortScript,
buildNginxSwitchScript,
buildPinnedPathGuardLines,
buildRemoteCleanupGuard,
buildRemoteJsonWriteLines,
buildStartScript,
buildStopDirScript,
ensureCommandAvailable,
ensureTempDeployDir,
getNowStamp,
getRemoteEnvFile,
isServerManagedConfig,
listDeployableFiles,
loadDeployConfig,
quoteForBash,
refreshNginx,
resolveFrontendDistDir,
runCommand,
runNpm,
runScp,
runSsh,
};