feat: 展示小程序构建过程和日志

This commit is contained in:
que01 committed 2026-10-13 20:20:13 +08:00
1 parent 8b4d27b0ee
commit 998e32e49c
7 files changed
+182 -14

No files matched your search

@@ -89,6 +89,12 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
privateKey: "", privateKey: "",
}); });
}, [miniAppSettings.data, miniAppSettingsForm]); }, [miniAppSettings.data, miniAppSettingsForm]);
useEffect(() => {
const building = miniAppReleases.data?.find((task) => task.status === "building");
if (!building) return;
const timer = setInterval(() => void miniAppReleases.refetch(), 1500);
return () => clearInterval(timer);
}, [miniAppReleases.data, miniAppReleases]);
const refresh = () => { const refresh = () => {
for (const key of [ for (const key of [
"publication-brand", "publication-brand",
@@ -532,9 +538,11 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
color={ color={
task.status === "published" task.status === "published"
? "green" ? "green"
: task.status === "failed" : task.status === "failed" || task.status === "build_failed"
? "red" ? "red"
: "blue" : task.status === "building"
? "orange"
: "blue"
} }
> >
{task.status} {task.status}
@@ -545,7 +553,27 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
</Typography.Text> </Typography.Text>
)} )}
{task.error && <Typography.Text type="danger">{task.error}</Typography.Text>} {task.error && <Typography.Text type="danger">{task.error}</Typography.Text>}
{task.status === "built" && ( {task.status === "building" && (
<Typography.Text type="secondary">正在构建微信小程序...</Typography.Text>
)}
{task.status === "build_failed" && (
<Typography.Text type="secondary">微信小程序构建失败</Typography.Text>
)}
{task.buildLogs?.length ? (
<Space direction="vertical" style={{ width: "100%" }}>
{task.buildLogs.slice(-8).map((log, index) => (
<Typography.Paragraph
key={`${log.at}-${index}`}
type={log.stream === "stderr" ? "danger" : "secondary"}
style={{ marginBottom: 0, whiteSpace: "pre-wrap", fontSize: 12 }}
code
>
{log.message}
</Typography.Paragraph>
))}
</Space>
) : null}
{(task.status === "built" || task.status === "build_failed") && (
<Button <Button
size="small" size="small"
loading={uploadMiniAppRelease.isPending} loading={uploadMiniAppRelease.isPending}
@@ -0,0 +1,3 @@
ALTER TYPE "MiniAppReleaseStatus" ADD VALUE 'building' AFTER 'built';
ALTER TYPE "MiniAppReleaseStatus" ADD VALUE 'build_failed' AFTER 'building';
ALTER TABLE "MiniAppReleaseTask" ADD COLUMN "buildLogs" JSONB;
+3
View File
@@ -102,6 +102,8 @@ model CapabilityInstallation {
enum MiniAppReleaseStatus { enum MiniAppReleaseStatus {
built built
building
build_failed
uploaded uploaded
under_review under_review
rejected rejected
@@ -119,6 +121,7 @@ model MiniAppReleaseTask {
version Int version Int
status MiniAppReleaseStatus @default(built) status MiniAppReleaseStatus @default(built)
artifactPath String? artifactPath String?
buildLogs Json?
actorId String actorId String
error String? error String?
weappUploadId String? weappUploadId String?
@@ -10,6 +10,7 @@ import {
} from "@nestjs/common"; } from "@nestjs/common";
import type { FastifyRequest } from "fastify"; import type { FastifyRequest } from "fastify";
import { existsSync } from "node:fs"; import { existsSync } from "node:fs";
import { spawn } from "node:child_process";
import { resolve } from "node:path"; import { resolve } from "node:path";
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { getTemplatePackageManifest, templatePackageRegistry } from "@personal-brand/config"; import { getTemplatePackageManifest, templatePackageRegistry } from "@personal-brand/config";
@@ -52,6 +53,18 @@ interface MiniprogramCi {
}) => Promise<Record<string, unknown>>; }) => Promise<Record<string, unknown>>;
} }
interface BuildLog {
at: string;
message: string;
stream: "stdout" | "stderr";
}
interface BuildProcess {
stdout: NodeJS.ReadableStream;
stderr: NodeJS.ReadableStream;
on: (event: "close" | "error", listener: (code: number | null) => void) => void;
}
@Controller("admin/miniapp-releases") @Controller("admin/miniapp-releases")
export class AdminMiniAppReleaseController { export class AdminMiniAppReleaseController {
constructor( constructor(
@@ -170,10 +183,58 @@ export class AdminMiniAppReleaseController {
const templateKey = miniAppTemplateKey(brand.templateKey); const templateKey = miniAppTemplateKey(brand.templateKey);
if (!templateKey) throw new BadRequestException("当前品牌模板没有可上传的小程序包"); if (!templateKey) throw new BadRequestException("当前品牌模板没有可上传的小程序包");
const projectPath = resolve(MINIAPP_ARTIFACT_ROOT, templateKey, "weapp"); const projectPath = resolve(MINIAPP_ARTIFACT_ROOT, templateKey, "weapp");
if (!existsSync(projectPath) || !existsSync(resolve(projectPath, "app.json"))) const buildLogs: BuildLog[] = [
throw new BadRequestException( {
`小程序构建产物不存在:${projectPath},请先执行对应模板的微信小程序构建`, at: new Date().toISOString(),
); message: `开始构建 ${templateKey} 微信小程序`,
stream: "stdout",
},
];
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "building",
buildLogs,
});
const result = await this.buildWeApp(templateKey, (message, stream) => {
buildLogs.push({ at: new Date().toISOString(), message, stream });
void this.releases
.updateStatus(identity.brandId, identity.subject, taskId, { status: "building", buildLogs })
.catch(() => undefined);
});
if (result.exitCode !== 0) {
buildLogs.push({
at: new Date().toISOString(),
message: `构建失败,退出码 ${result.exitCode}`,
stream: "stderr",
});
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "build_failed",
error: `小程序构建失败,请查看构建日志`,
buildLogs,
});
throw new BadRequestException("小程序构建失败,请查看构建日志");
}
if (!existsSync(projectPath) || !existsSync(resolve(projectPath, "app.json"))) {
buildLogs.push({
at: new Date().toISOString(),
message: `构建完成但缺少产物:${projectPath}/app.json`,
stream: "stderr",
});
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "build_failed",
error: "小程序构建产物缺少 app.json",
buildLogs,
});
throw new BadRequestException("小程序构建产物缺少 app.json");
}
buildLogs.push({
at: new Date().toISOString(),
message: "构建完成,开始上传微信",
stream: "stdout",
});
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "built",
buildLogs,
});
const ci = (await import("miniprogram-ci")) as unknown as MiniprogramCi; const ci = (await import("miniprogram-ci")) as unknown as MiniprogramCi;
const project = new ci.Project({ const project = new ci.Project({
projectPath, projectPath,
@@ -182,7 +243,7 @@ export class AdminMiniAppReleaseController {
privateKey, privateKey,
}); });
try { try {
const result = await ci.upload({ const uploadResult = await ci.upload({
project, project,
version: body.version ?? String(task.version), version: body.version ?? String(task.version),
desc: body.desc ?? `brand content v${task.version}`, desc: body.desc ?? `brand content v${task.version}`,
@@ -191,14 +252,16 @@ export class AdminMiniAppReleaseController {
}); });
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, { return this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "uploaded", status: "uploaded",
buildLogs,
weappUploadId: weappUploadId:
typeof result.strUint64Version === "string" typeof uploadResult.strUint64Version === "string"
? result.strUint64Version ? uploadResult.strUint64Version
: String(task.version), : String(task.version),
}); });
} catch (error) { } catch (error) {
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, { await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "failed", status: "failed",
buildLogs,
error: error instanceof Error ? error.message : "微信代码上传失败", error: error instanceof Error ? error.message : "微信代码上传失败",
}); });
throw error; throw error;
@@ -226,6 +289,34 @@ export class AdminMiniAppReleaseController {
return value; return value;
} }
private buildWeApp(
templateKey: string,
onLog: (message: string, stream: "stdout" | "stderr") => void,
): Promise<{ exitCode: number }> {
return new Promise((resolvePromise, rejectPromise) => {
const child = spawn("pnpm", ["--filter", "@personal-brand/taro", "build:weapp"], {
cwd: resolve(process.cwd(), "../.."),
env: { ...process.env, TEMPLATE_KEY: templateKey, TARO_ENV: "weapp" },
shell: process.platform === "win32",
}) as BuildProcess;
const readStream = (stream: NodeJS.ReadableStream, name: "stdout" | "stderr") => {
let buffer = "";
stream.on("data", (chunk: Buffer | string) => {
buffer += chunk.toString();
for (const message of buffer.split("\n").slice(0, -1)) onLog(message, name);
buffer = buffer.slice(buffer.lastIndexOf("\n") + 1);
});
stream.on("end", () => {
if (buffer) onLog(buffer, name);
});
};
readStream(child.stdout, "stdout");
readStream(child.stderr, "stderr");
child.on("close", (code) => resolvePromise({ exitCode: code ?? 1 }));
child.on("error", () => rejectPromise(new Error("小程序构建进程启动失败")));
});
}
private jsonObject(value: unknown): Record<string, unknown> { private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value) return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>) ? (value as Record<string, unknown>)
@@ -8,8 +8,27 @@ export class CreateMiniAppReleaseDto {
} }
export class UpdateMiniAppReleaseStatusDto { export class UpdateMiniAppReleaseStatusDto {
@IsIn(["uploaded", "under_review", "approved", "rejected", "failed", "built", "published"]) @IsIn([
status!: "uploaded" | "under_review" | "approved" | "rejected" | "failed" | "built" | "published"; "uploaded",
"under_review",
"approved",
"rejected",
"failed",
"built",
"building",
"build_failed",
"published",
])
status!:
| "uploaded"
| "under_review"
| "approved"
| "rejected"
| "failed"
| "built"
| "building"
| "build_failed"
| "published";
@IsOptional() @IsOptional()
@IsString() @IsString()
@@ -9,6 +9,8 @@ import { PrismaService } from "../../prisma.service.js";
const transitions: Record<string, string[]> = { const transitions: Record<string, string[]> = {
built: ["uploaded", "under_review", "failed"], built: ["uploaded", "under_review", "failed"],
building: ["built", "build_failed"],
build_failed: ["built"],
uploaded: ["under_review", "failed"], uploaded: ["under_review", "failed"],
under_review: ["approved", "rejected", "failed"], under_review: ["approved", "rejected", "failed"],
approved: ["published", "failed"], approved: ["published", "failed"],
@@ -64,9 +66,18 @@ export class AdminMiniAppReleaseService {
taskId: string, taskId: string,
input: { input: {
status: status:
"uploaded" | "under_review" | "approved" | "rejected" | "failed" | "built" | "published"; | "uploaded"
| "under_review"
| "approved"
| "rejected"
| "failed"
| "built"
| "building"
| "build_failed"
| "published";
error?: string; error?: string;
weappUploadId?: string; weappUploadId?: string;
buildLogs?: unknown;
}, },
): Promise<unknown> { ): Promise<unknown> {
return this.prisma.$transaction( return this.prisma.$transaction(
@@ -89,6 +100,9 @@ export class AdminMiniAppReleaseService {
status: input.status, status: input.status,
error: input.error ?? null, error: input.error ?? null,
...(input.weappUploadId ? { weappUploadId: input.weappUploadId } : {}), ...(input.weappUploadId ? { weappUploadId: input.weappUploadId } : {}),
...(input.buildLogs !== undefined
? { buildLogs: input.buildLogs as Prisma.InputJsonValue }
: {}),
audit, audit,
}, },
}); });
+11 -1
View File
@@ -51,8 +51,18 @@ export interface BrandReleaseSummary {
export interface MiniAppReleaseTask { export interface MiniAppReleaseTask {
id: string; id: string;
version: number; version: number;
status: "built" | "uploaded" | "under_review" | "rejected" | "approved" | "published" | "failed"; status:
| "built"
| "building"
| "build_failed"
| "uploaded"
| "under_review"
| "rejected"
| "approved"
| "published"
| "failed";
artifactPath?: string | null; artifactPath?: string | null;
buildLogs?: Array<{ at: string; message: string; stream: "stdout" | "stderr" }> | null;
error?: string | null; error?: string | null;
weappUploadId?: string | null; weappUploadId?: string | null;
createdAt: string; createdAt: string;