feat: 初始提交
This commit is contained in:
170
scripts/build.ts
Normal file
170
scripts/build.ts
Normal file
@@ -0,0 +1,170 @@
|
||||
import { readdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join, relative, sep } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { APP } from "../src/shared/app";
|
||||
import { validateVersion } from "./bump-version-logic";
|
||||
|
||||
const projectRoot = fileURLToPath(new URL("..", import.meta.url));
|
||||
const distWebDir = join(projectRoot, "dist/web");
|
||||
const buildDir = join(projectRoot, ".build");
|
||||
const executablePath = join(projectRoot, `dist/${APP.name}`);
|
||||
const packageJsonPath = join(projectRoot, "package.json");
|
||||
|
||||
async function build() {
|
||||
try {
|
||||
await viteBuild();
|
||||
await codeGeneration();
|
||||
await bunCompile();
|
||||
await cleanup();
|
||||
console.log(`Built executable: ${executablePath}`);
|
||||
} catch (error) {
|
||||
await cleanup();
|
||||
console.error("Build failed:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function bunCompile() {
|
||||
console.log("Step 3/3: Bun compile...");
|
||||
await rm(executablePath, { force: true });
|
||||
|
||||
const target = process.env["BUN_TARGET"] ?? process.env["BUILD_TARGET"];
|
||||
const result = await Bun.build({
|
||||
compile: target
|
||||
? {
|
||||
autoloadBunfig: true,
|
||||
autoloadDotenv: true,
|
||||
outfile: executablePath,
|
||||
target: target as Bun.Build.CompileTarget,
|
||||
}
|
||||
: {
|
||||
autoloadBunfig: true,
|
||||
autoloadDotenv: true,
|
||||
outfile: executablePath,
|
||||
},
|
||||
entrypoints: [join(buildDir, "server-entry.ts")],
|
||||
minify: true,
|
||||
sourcemap: "linked",
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
console.error("Bun compile failed:", result.logs);
|
||||
await cleanup();
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function cleanup() {
|
||||
await rm(buildDir, { force: true, recursive: true });
|
||||
}
|
||||
|
||||
async function codeGeneration() {
|
||||
console.log("Step 2/3: Code generation...");
|
||||
await rm(buildDir, { force: true, recursive: true });
|
||||
await Bun.write(join(buildDir, ".gitkeep"), "");
|
||||
|
||||
const packageJson = (await Bun.file(packageJsonPath).json()) as { version: string };
|
||||
const version = packageJson.version;
|
||||
if (typeof version !== "string") {
|
||||
console.error("package.json does not have a valid version field");
|
||||
process.exit(1);
|
||||
}
|
||||
validateVersion(version);
|
||||
|
||||
const allFiles = await scanDir(distWebDir, "/");
|
||||
const importLines: string[] = [];
|
||||
const fileEntries: string[] = [];
|
||||
let indexHtmlVar = "";
|
||||
|
||||
for (let i = 0; i < allFiles.length; i++) {
|
||||
const urlPath = allFiles[i]!;
|
||||
const varName = `f${i}`;
|
||||
const filePath = toImportSpecifier(buildDir, join(distWebDir, urlPath.slice(1)));
|
||||
importLines.push(`import ${varName} from "./${filePath}" with { type: "file" };`);
|
||||
|
||||
if (urlPath === "/index.html") {
|
||||
indexHtmlVar = varName;
|
||||
} else {
|
||||
fileEntries.push(` "${urlPath}": Bun.file(${varName}),`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!indexHtmlVar) {
|
||||
console.error("index.html not found in dist/web/");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const staticAssetsTs = [
|
||||
`import type { StaticAssets } from "../src/server/static";`,
|
||||
"",
|
||||
...importLines,
|
||||
"",
|
||||
`export const staticAssets: StaticAssets = {`,
|
||||
` files: {`,
|
||||
...fileEntries,
|
||||
` },`,
|
||||
` indexHtml: Bun.file(${indexHtmlVar}),`,
|
||||
`};`,
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
await writeFile(join(buildDir, "static-assets.ts"), staticAssetsTs);
|
||||
|
||||
const serverEntryTs = [
|
||||
`import { bootstrap } from "../src/server/bootstrap";`,
|
||||
`import { parseRuntimeArgs } from "../src/server/config";`,
|
||||
`import { createConsoleFallback } from "../src/server/logger";`,
|
||||
`import { staticAssets } from "./static-assets";`,
|
||||
"",
|
||||
`const APP_VERSION = "${version}" as const;`,
|
||||
"",
|
||||
`async function main() {`,
|
||||
` const { configPath } = parseRuntimeArgs();`,
|
||||
` await bootstrap({ configPath, mode: "production", staticAssets, version: APP_VERSION });`,
|
||||
`}`,
|
||||
"",
|
||||
`void main().catch((error) => {`,
|
||||
` createConsoleFallback().fatal(\`启动失败: \${error instanceof Error ? error.message : String(error)}\`);`,
|
||||
` process.exit(1);`,
|
||||
`});`,
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
await writeFile(join(buildDir, "server-entry.ts"), serverEntryTs);
|
||||
}
|
||||
|
||||
async function scanDir(dir: string, prefix: string): Promise<string[]> {
|
||||
const entries = await readdir(dir, { withFileTypes: true });
|
||||
const paths: string[] = [];
|
||||
for (const entry of entries) {
|
||||
const fullPath = join(dir, entry.name);
|
||||
const urlPath = `${prefix}${entry.name}`;
|
||||
if (entry.isDirectory()) {
|
||||
paths.push(...(await scanDir(fullPath, `${urlPath}/`)));
|
||||
} else {
|
||||
paths.push(urlPath);
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
function toImportSpecifier(fromDir: string, targetPath: string) {
|
||||
return relative(fromDir, targetPath).split(sep).join("/");
|
||||
}
|
||||
|
||||
async function viteBuild() {
|
||||
console.log("Step 1/3: Vite build...");
|
||||
const proc = Bun.spawn(["bunx", "--bun", "vite", "build"], {
|
||||
cwd: projectRoot,
|
||||
stderr: "inherit",
|
||||
stdout: "inherit",
|
||||
});
|
||||
const exitCode = await proc.exited;
|
||||
if (exitCode !== 0) {
|
||||
console.error("Vite build failed");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
await build();
|
||||
40
scripts/bump-version-logic.ts
Normal file
40
scripts/bump-version-logic.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
const VERSION_REGEX = /^\d+\.\d+\.\d+$/;
|
||||
|
||||
export function bumpVersion(current: string, command: "major" | "minor" | "patch" | "set", target?: string): string {
|
||||
validateVersion(current);
|
||||
const [major, minor, patch] = parseVersion(current);
|
||||
|
||||
switch (command) {
|
||||
case "major":
|
||||
return formatVersion(major + 1, 0, 0);
|
||||
case "minor":
|
||||
return formatVersion(major, minor + 1, 0);
|
||||
case "patch":
|
||||
return formatVersion(major, minor, patch + 1);
|
||||
case "set": {
|
||||
if (!target) {
|
||||
throw new Error("set command requires a target version");
|
||||
}
|
||||
validateVersion(target);
|
||||
return target;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function formatVersion(major: number, minor: number, patch: number): string {
|
||||
return `${major}.${minor}.${patch}`;
|
||||
}
|
||||
|
||||
export function parseVersion(version: string): [number, number, number] {
|
||||
const parts = version.split(".").map((p) => parseInt(p, 10));
|
||||
if (parts.length !== 3 || parts.some(isNaN)) {
|
||||
throw new Error(`Invalid version format: ${version}`);
|
||||
}
|
||||
return [parts[0]!, parts[1]!, parts[2]!];
|
||||
}
|
||||
|
||||
export function validateVersion(version: string): void {
|
||||
if (!VERSION_REGEX.test(version)) {
|
||||
throw new Error(`Invalid version format: ${version}. Expected MAJOR.MINOR.PATCH (e.g., 0.1.0)`);
|
||||
}
|
||||
}
|
||||
45
scripts/bump-version.ts
Normal file
45
scripts/bump-version.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { bumpVersion, validateVersion } from "./bump-version-logic";
|
||||
|
||||
const PACKAGE_JSON_PATH = resolve(import.meta.dir, "..", "package.json");
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
if (args.length === 0) {
|
||||
console.error("Usage: bun run bump-version.ts <patch|minor|major|set> [version]");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const command = args[0];
|
||||
if (command !== "patch" && command !== "minor" && command !== "major" && command !== "set") {
|
||||
console.error(`Unknown command: ${command}. Expected patch, minor, major, or set`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (command === "set" && args.length < 2) {
|
||||
console.error("Usage: bun run bump-version.ts set <version>");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const packageJson = (await Bun.file(PACKAGE_JSON_PATH).json()) as { version: string };
|
||||
const currentVersion = packageJson.version;
|
||||
|
||||
if (typeof currentVersion !== "string") {
|
||||
console.error("package.json does not have a valid version field");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
validateVersion(currentVersion);
|
||||
|
||||
const targetVersion = command === "set" ? args[1] : undefined;
|
||||
const nextVersion = bumpVersion(currentVersion, command, targetVersion);
|
||||
|
||||
packageJson.version = nextVersion;
|
||||
writeFileSync(PACKAGE_JSON_PATH, JSON.stringify(packageJson, null, 2) + "\n");
|
||||
|
||||
console.log(`${currentVersion} -> ${nextVersion}`);
|
||||
}
|
||||
|
||||
void main();
|
||||
29
scripts/clean.ts
Normal file
29
scripts/clean.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { rm } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
const root = resolve(import.meta.dir, "..");
|
||||
|
||||
const dirs: Array<{ desc: string; path: string }> = [
|
||||
{ desc: "构建产物", path: "dist" },
|
||||
{ desc: "Bun 构建缓存", path: ".build" },
|
||||
{ desc: "Playwright 测试报告", path: "playwright-report" },
|
||||
{ desc: "测试结果", path: "test-results" },
|
||||
];
|
||||
|
||||
const filePatterns: Array<{ desc: string; glob: string }> = [{ desc: "Bun 构建临时文件", glob: ".*.bun-build" }];
|
||||
|
||||
for (const { desc, path } of dirs) {
|
||||
const full = resolve(root, path);
|
||||
await rm(full, { force: true, recursive: true });
|
||||
console.log(`已清理 ${desc}: ${path}`);
|
||||
}
|
||||
|
||||
for (const { desc, glob } of filePatterns) {
|
||||
const entries = await Array.fromAsync(new Bun.Glob(glob).scan({ cwd: root, dot: true }));
|
||||
if (entries.length === 0) continue;
|
||||
for (const entry of entries) {
|
||||
const full = resolve(root, entry);
|
||||
await rm(full, { force: true, recursive: true });
|
||||
console.log(`已清理 ${desc}: ${entry}`);
|
||||
}
|
||||
}
|
||||
26
scripts/dev.ts
Normal file
26
scripts/dev.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const projectRoot = fileURLToPath(new URL("..", import.meta.url));
|
||||
|
||||
const apiServer = Bun.spawn(["bun", "--watch", "src/server/dev.ts", ...process.argv.slice(2)], {
|
||||
cwd: projectRoot,
|
||||
stderr: "inherit",
|
||||
stdout: "inherit",
|
||||
});
|
||||
|
||||
const viteServer = Bun.spawn(["bunx", "--bun", "vite", "--host"], {
|
||||
cwd: projectRoot,
|
||||
stderr: "inherit",
|
||||
stdout: "inherit",
|
||||
});
|
||||
|
||||
function shutdown() {
|
||||
apiServer.kill();
|
||||
viteServer.kill();
|
||||
}
|
||||
|
||||
process.on("SIGINT", shutdown);
|
||||
process.on("SIGTERM", shutdown);
|
||||
|
||||
await Promise.race([apiServer.exited, viteServer.exited]);
|
||||
shutdown();
|
||||
15
scripts/generate-config-schema.ts
Normal file
15
scripts/generate-config-schema.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { createConfigJsonSchema } from "../src/server/config/schema/export";
|
||||
|
||||
const schemaPath = "config.schema.json";
|
||||
const schema = `${JSON.stringify(createConfigJsonSchema(), null, 2)}\n`;
|
||||
|
||||
if (process.argv.includes("--check")) {
|
||||
const existing = await Bun.file(schemaPath)
|
||||
.text()
|
||||
.catch(() => null);
|
||||
if (existing !== schema) {
|
||||
throw new Error(`${schemaPath} 未同步,请运行 bun run schema`);
|
||||
}
|
||||
} else {
|
||||
await Bun.write(schemaPath, schema);
|
||||
}
|
||||
Reference in New Issue
Block a user