48 lines
1.5 KiB
TypeScript
48 lines
1.5 KiB
TypeScript
import type { RuntimeMode } from "../shared/api";
|
|
import type { ServerConfig } from "./config";
|
|
import type { StartServerOptions } from "./server";
|
|
|
|
import { loadServerConfig } from "./config";
|
|
import { startServer } from "./server";
|
|
|
|
export interface BootstrapDependencies {
|
|
loadConfig?: (configPath?: string) => Promise<ServerConfig>;
|
|
logError?: (...data: unknown[]) => void;
|
|
onSignal?: (signal: "SIGINT" | "SIGTERM", handler: () => void) => void;
|
|
startServer?: (options: StartServerOptions) => unknown;
|
|
}
|
|
|
|
export interface BootstrapOptions {
|
|
config?: ServerConfig;
|
|
configPath?: string;
|
|
mode: RuntimeMode;
|
|
staticAssets?: StartServerOptions["staticAssets"];
|
|
version?: string;
|
|
}
|
|
|
|
export async function bootstrap(options: BootstrapOptions, dependencies: BootstrapDependencies = {}): Promise<void> {
|
|
const load = dependencies.loadConfig ?? loadServerConfig;
|
|
const serve = dependencies.startServer ?? startServer;
|
|
const onSignal =
|
|
dependencies.onSignal ??
|
|
((signal: "SIGINT" | "SIGTERM", handler: () => void) => {
|
|
process.on(signal, handler);
|
|
});
|
|
const logError = dependencies.logError ?? console.error;
|
|
|
|
try {
|
|
const config = options.config ?? (await load(options.configPath));
|
|
|
|
const shutdown = () => {
|
|
process.exit(0);
|
|
};
|
|
onSignal("SIGINT", shutdown);
|
|
onSignal("SIGTERM", shutdown);
|
|
|
|
serve({ config, mode: options.mode, staticAssets: options.staticAssets, version: options.version });
|
|
} catch (error) {
|
|
logError("启动失败:", error instanceof Error ? error.message : error);
|
|
process.exit(1);
|
|
}
|
|
}
|