Files
wukuang/apps/lcdp/scripts/dev-with-local-auth.mjs
2026-05-23 14:05:22 +08:00

97 lines
2.6 KiB
JavaScript

/**
* @description 开发启动脚本:为 Vite 与本地登录代理生成同一实例标识,便于前端按实例发现对应代理端口。
*/
import { spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { dirname, resolve } from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const pkgRoot = resolve(__dirname, '..');
const cliArgs = process.argv.slice(2);
const modeFlagIndex = cliArgs.findIndex(arg => arg === '--mode');
const modeArg = modeFlagIndex >= 0 ? String(cliArgs[modeFlagIndex + 1] || '').trim() : '';
const mode = modeArg || String(process.env.BUSINESS_RULES_MODE || 'dev').trim() || 'dev';
const instanceId = process.env.LOCAL_AUTH_INSTANCE_ID || `lcdp-local-auth-${randomUUID()}`;
/**
* @description 终止子进程。
* @param {import('node:child_process').ChildProcess | null} child 子进程。
*/
function stopChild(child) {
if (!child || child.killed) {
return;
}
child.kill('SIGTERM');
}
const sharedEnv = {
...process.env,
BUSINESS_RULES_MODE: mode,
LOCAL_AUTH_INSTANCE_ID: instanceId,
VITE_LOCAL_AUTH_INSTANCE_ID: instanceId,
};
console.log(`[dev-local-auth] mode: ${mode}`);
console.log(`[dev-local-auth] local auth instance: ${instanceId}`);
const children = /** @type {import('node:child_process').ChildProcess[]} */ ([]);
let shuttingDown = false;
function shutdownAll() {
if (shuttingDown) {
return;
}
shuttingDown = true;
for (const child of children) {
stopChild(child);
}
}
for (const signal of ['SIGINT', 'SIGTERM']) {
process.on(signal, () => {
shutdownAll();
});
}
const viteChild = spawn('node', ['./scripts/dev-vite.mjs', '--mode', mode], {
cwd: pkgRoot,
env: sharedEnv,
stdio: 'inherit',
});
children.push(viteChild);
const authChild = spawn('node', ['./scripts/local-auth-proxy.mjs', '--mode', mode], {
cwd: pkgRoot,
env: sharedEnv,
stdio: 'inherit',
});
children.push(authChild);
const exitCode = await new Promise((resolvePromise, rejectPromise) => {
const handleChildError = (error) => {
shutdownAll();
rejectPromise(error);
};
for (const child of children) {
child.on('error', handleChildError);
}
const handleExit = (name, code, signal) => {
shutdownAll();
if (signal) {
resolvePromise(1);
return;
}
resolvePromise(code ?? 0);
};
viteChild.on('exit', (code, signal) => handleExit('vite', code, signal));
authChild.on('exit', (code, signal) => handleExit('local-auth', code, signal));
});
process.exit(exitCode);