refactor: 拆分小程序发布与后台发布页面职责

This commit is contained in:
que01 committed 2026-10-15 14:20:17 +08:00
1 parent 8973338c64
commit 7c0f22ad7a
19 files changed
+797 -538

No files matched your search

@@ -0,0 +1,47 @@
import { Injectable } from "@nestjs/common";
import { spawn } from "node:child_process";
import { REPOSITORY_ROOT } from "./miniapp-artifact.js";
interface BuildProcess {
stdout: NodeJS.ReadableStream;
stderr: NodeJS.ReadableStream;
on: (event: "close" | "error", listener: (code: number | null) => void) => void;
}
@Injectable()
export class AdminMiniAppBuildService {
run(
templateKey: string,
buildConfig: { apiBaseUrl: string; appId: 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: REPOSITORY_ROOT,
env: {
...process.env,
TEMPLATE_KEY: templateKey,
TARO_ENV: "weapp",
API_BASE_URL: buildConfig.apiBaseUrl,
WEAPP_APP_ID: buildConfig.appId,
},
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("小程序构建进程启动失败")));
});
}
}
@@ -1,116 +1,37 @@
import {
BadRequestException,
BadGatewayException,
Body,
ConflictException,
Controller,
Get,
Param,
Patch,
Post,
Req,
} from "@nestjs/common";
import { Body, Controller, Get, Param, Patch, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { existsSync } from "node:fs";
import { spawn } from "node:child_process";
import { resolve } from "node:path";
import { Prisma } from "@prisma/client";
import { getTemplatePackageManifest, templatePackageRegistry } from "@personal-brand/config";
import { AdminAccessService } from "../../admin-access.service.js";
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
import { AdminMiniAppSettingsService } from "./admin-miniapp-settings.service.js";
import { AdminMiniAppUploadService } from "./admin-miniapp-upload.service.js";
import { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
import { miniappArtifactRoot, miniappProjectPath, REPOSITORY_ROOT } from "./miniapp-artifact.js";
import { miniappApiBaseUrl, validateApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
import { buildingStaleMs, isStaleBuilding } from "./miniapp-build-status.js";
import { decryptMiniAppCredential, encryptMiniAppCredential } from "./miniapp-credential-crypto.js";
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
import { runMiniAppUpload } from "./miniapp-upload.js";
import {
CreateMiniAppReleaseDto,
UpdateMiniAppReleaseStatusDto,
UploadMiniAppReleaseDto,
} from "./admin-miniapp-release.dto.js";
function miniAppTemplateKey(industryTemplateKey: string): string | null {
return (
getTemplatePackageManifest(industryTemplateKey)?.packageKey ??
templatePackageRegistry.find((item) =>
item.supportedIndustryTemplates.includes(industryTemplateKey),
)?.packageKey ??
null
);
}
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;
}
type AdminIdentity = { subject: string; brandId: string };
@Controller("admin/miniapp-releases")
export class AdminMiniAppReleaseController {
constructor(
private readonly access: AdminAccessService,
private readonly releases: AdminMiniAppReleaseService,
private readonly settingsService: AdminMiniAppSettingsService,
private readonly uploads: AdminMiniAppUploadService,
) {}
@Get("latest")
async latest(@Req() request: FastifyRequest): Promise<unknown> {
const identity = await this.identity(request);
const task = await this.releases.latest(identity.brandId);
return task ?? null;
return (await this.releases.latest(identity.brandId)) ?? null;
}
@Get("settings")
async settings(@Req() request: FastifyRequest): Promise<unknown> {
const identity = await this.identity(request);
const settings = this.jsonObject(await this.releases.settings(identity.brandId));
const buildConfig = this.buildConfigSummary(settings.apiBaseUrl, settings.appId);
return {
appId: "",
artifactPath: miniappArtifactRoot(),
build: {},
...settings,
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
privateKey: undefined,
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
hasStoredCredentials: Boolean(settings.credential),
...buildConfig,
};
}
private buildConfigSummary(
storedApiBaseUrl: unknown,
storedAppId: unknown,
): {
requestDomain: string | null;
buildError: string | null;
} {
try {
const base = miniappApiBaseUrl(storedApiBaseUrl);
weappAppId(storedAppId);
return { requestDomain: new URL(base).host, buildError: null };
} catch (error) {
return {
requestDomain: null,
buildError: error instanceof Error ? error.message : "小程序构建参数未配置",
};
}
}
/** 表单回显:品牌未显式配置时展示环境推导出的默认地址,便于管理员在其基础上修改。 */
private effectiveApiBaseUrl(storedApiBaseUrl: unknown): string {
try {
return miniappApiBaseUrl(storedApiBaseUrl);
} catch {
return typeof storedApiBaseUrl === "string" ? storedApiBaseUrl : "";
}
return this.settingsService.get(identity.brandId);
}
@Patch("settings")
@@ -120,53 +41,7 @@ export class AdminMiniAppReleaseController {
): Promise<unknown> {
const identity = await this.identity(request);
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
if (body.privateKey !== undefined) {
if (!body.privateKey.trim().startsWith("-----BEGIN"))
throw new BadRequestException("上传私钥格式无效:应为 -----BEGIN 开头的 PEM 内容");
const inspection = inspectPrivateKey(body.privateKey);
if (!inspection.valid)
throw new BadRequestException(
`上传私钥无法解析(${inspection.reason ?? "PEM 格式错误"})。请粘贴微信开发者工具生成的完整私钥,注意保留换行。`,
);
}
const current = this.jsonObject(await this.releases.settings(identity.brandId));
let apiBaseUrl: string | undefined;
if (body.apiBaseUrl !== undefined) {
const trimmed = body.apiBaseUrl.trim();
if (!trimmed) throw new BadRequestException("小程序请求地址不能为空");
try {
apiBaseUrl = validateApiBaseUrl(trimmed);
} catch (error) {
throw new BadRequestException(
error instanceof Error ? error.message : "小程序请求地址无效",
);
}
}
const credential =
body.privateKey === undefined
? current.credential
: encryptMiniAppCredential(normalizePrivateKey(body.privateKey));
const settings = {
...current,
appId: body.appId ?? current.appId ?? "",
apiBaseUrl: apiBaseUrl ?? current.apiBaseUrl ?? "",
build: {
...this.jsonObject(current.build),
...this.jsonObject(body.build),
} as Prisma.InputJsonObject,
...(credential ? { credential } : {}),
templateKey: current.templateKey ?? null,
} satisfies Prisma.InputJsonObject;
await this.releases.saveSettings(identity.brandId, settings);
return {
appId: settings.appId,
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
artifactPath: miniappArtifactRoot(),
build: settings.build,
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
hasStoredCredentials: Boolean(settings.credential),
...this.buildConfigSummary(settings.apiBaseUrl, settings.appId),
};
return this.settingsService.update(identity.brandId, body);
}
@Get()
@@ -182,213 +57,29 @@ export class AdminMiniAppReleaseController {
}
@Post(":id/upload")
async upload(
upload(
@Req() request: FastifyRequest,
@Param("id") taskId: string,
@Body() body: UploadMiniAppReleaseDto,
): Promise<unknown> {
const identity = await this.identity(request);
const { task, brand } = await this.releases.uploadContext(identity.brandId, taskId);
if (task.status !== "built" && task.status !== "failed")
throw new BadRequestException("当前小程序发布任务不能重复上传");
const staleBuilding = isStaleBuilding(task);
if (task.buildStatus === "building" && !staleBuilding)
throw new ConflictException("小程序构建正在进行中,请稍后");
const settings = this.jsonObject(brand.miniAppSettings);
const appid = (() => {
try {
return weappAppId(settings.appId);
} catch (error) {
throw new BadRequestException(error instanceof Error ? error.message : "未配置微信 AppID");
}
})();
const privateKey = settings.credential
? decryptMiniAppCredential(settings.credential)
: this.requiredEnv("WECHAT_UPLOAD_PRIVATE_KEY");
const normalizedPrivateKey = normalizePrivateKey(privateKey);
const keyInspection = inspectPrivateKey(normalizedPrivateKey);
if (!keyInspection.valid)
throw new BadRequestException(
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序上传配置”里重新粘贴完整私钥。`,
);
const templateKey = miniAppTemplateKey(brand.templateKey);
if (!templateKey) throw new BadRequestException("当前品牌模板没有可上传的小程序包");
let buildConfig: { apiBaseUrl: string; appId: string };
try {
buildConfig = {
apiBaseUrl: miniappApiBaseUrl(settings.apiBaseUrl),
appId: weappAppId(settings.appId),
};
} catch (error) {
throw new BadRequestException(
error instanceof Error ? error.message : "小程序构建参数未配置",
);
}
const projectPath = miniappProjectPath(templateKey);
const buildLogs: BuildLog[] = [
{
at: new Date().toISOString(),
message: `开始构建 ${templateKey} 微信小程序`,
stream: "stdout",
},
{
at: new Date().toISOString(),
message: `请求地址 ${buildConfig.apiBaseUrl},AppID ${buildConfig.appId}`,
stream: "stdout",
},
];
if (staleBuilding)
buildLogs.push({
at: new Date().toISOString(),
message: `上一次构建已超过 ${Math.round(buildingStaleMs() / 60000)} 分钟没有进展,按中断处理并重新构建`,
stream: "stderr",
});
if (task.status === "failed") {
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "built",
buildLogs,
buildStatus: "building",
});
} else {
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
buildLogs,
buildStatus: "building",
error: null,
});
}
const result = await this.buildWeApp(templateKey, buildConfig, (message, stream) => {
buildLogs.push({ at: new Date().toISOString(), message, stream });
void this.releases
.updateBuild(identity.brandId, identity.subject, taskId, {
buildLogs,
buildStatus: "building",
})
.catch(() => undefined);
});
if (result.exitCode !== 0) {
buildLogs.push({
at: new Date().toISOString(),
message: `构建失败,退出码 ${result.exitCode}`,
stream: "stderr",
});
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
error: `小程序构建失败,请查看构建日志`,
buildLogs,
buildStatus: "failed",
});
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.updateBuild(identity.brandId, identity.subject, taskId, {
error: "小程序构建产物缺少 app.json",
buildLogs,
buildStatus: "failed",
});
throw new BadRequestException(`小程序构建产物缺少 app.json:${projectPath}`);
}
buildLogs.push({
at: new Date().toISOString(),
message: "构建完成,开始上传微信",
stream: "stdout",
});
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
buildLogs,
buildStatus: "success",
});
try {
const uploadResult = await runMiniAppUpload({
projectPath,
appid,
privateKey: normalizedPrivateKey,
version: body.version ?? String(task.version),
desc: body.desc ?? `brand content v${task.version}`,
robot: body.robot ?? 1,
});
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "uploaded",
buildLogs,
buildStatus: "success",
weappUploadId:
typeof uploadResult.strUint64Version === "string"
? uploadResult.strUint64Version
: String(task.version),
});
} catch (error) {
const message = error instanceof Error ? error.message : "微信代码上传失败";
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "failed",
buildLogs,
buildStatus: "failed",
error: message,
});
throw new BadGatewayException(message);
}
return this.identity(request).then(({ brandId, subject }) =>
this.uploads.run(brandId, subject, taskId, body),
);
}
@Patch(":id/status")
async updateStatus(
updateStatus(
@Req() request: FastifyRequest,
@Param("id") taskId: string,
@Body() body: UpdateMiniAppReleaseStatusDto,
): Promise<unknown> {
const identity = await this.identity(request);
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, body);
return this.identity(request).then(({ brandId, subject }) =>
this.releases.updateStatus(brandId, subject, taskId, body),
);
}
private async identity(request: FastifyRequest): Promise<{ subject: string; brandId: string }> {
private async identity(request: FastifyRequest): Promise<AdminIdentity> {
const { subject, brandId } = await this.access.requireBrand(request);
return { subject, brandId };
}
private requiredEnv(name: string): string {
const value = process.env[name];
if (!value) throw new BadRequestException(`${name} 未配置`);
return value;
}
private buildWeApp(
templateKey: string,
buildConfig: { apiBaseUrl: string; appId: 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: REPOSITORY_ROOT,
env: {
...process.env,
TEMPLATE_KEY: templateKey,
TARO_ENV: "weapp",
API_BASE_URL: buildConfig.apiBaseUrl,
WEAPP_APP_ID: buildConfig.appId,
},
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> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
}
@@ -0,0 +1,107 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
import { miniappArtifactRoot } from "./miniapp-artifact.js";
import { miniappApiBaseUrl, validateApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
import { encryptMiniAppCredential } from "./miniapp-credential-crypto.js";
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
import type { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
@Injectable()
export class AdminMiniAppSettingsService {
constructor(private readonly releases: AdminMiniAppReleaseService) {}
async get(brandId: string): Promise<unknown> {
const settings = this.jsonObject(await this.releases.settings(brandId));
return this.present(settings);
}
async update(brandId: string, body: UpdateMiniAppSettingsDto & { privateKey?: string }) {
if (body.privateKey !== undefined) this.validatePrivateKey(body.privateKey);
const current = this.jsonObject(await this.releases.settings(brandId));
const settings = {
...current,
appId: body.appId ?? current.appId ?? "",
apiBaseUrl:
body.apiBaseUrl === undefined ? (current.apiBaseUrl ?? "") : this.apiBaseUrl(body),
build: {
...this.jsonObject(current.build),
...this.jsonObject(body.build),
} as Prisma.InputJsonObject,
...(body.privateKey === undefined
? {}
: { credential: encryptMiniAppCredential(normalizePrivateKey(body.privateKey)) }),
templateKey: current.templateKey ?? null,
} satisfies Prisma.InputJsonObject;
await this.releases.saveSettings(brandId, settings);
return this.present(settings);
}
private validatePrivateKey(privateKey: string) {
if (!privateKey.trim().startsWith("-----BEGIN"))
throw new BadRequestException("上传私钥格式无效:应为 -----BEGIN 开头的 PEM 内容");
const inspection = inspectPrivateKey(privateKey);
if (!inspection.valid)
throw new BadRequestException(
`上传私钥无法解析(${inspection.reason ?? "PEM 格式错误"})。请粘贴微信开发者工具生成的完整私钥,注意保留换行。`,
);
}
private apiBaseUrl(body: UpdateMiniAppSettingsDto) {
const trimmed = body.apiBaseUrl?.trim();
if (!trimmed) throw new BadRequestException("小程序请求地址不能为空");
try {
return validateApiBaseUrl(trimmed);
} catch (error) {
throw new BadRequestException(error instanceof Error ? error.message : "小程序请求地址无效");
}
}
private present(settings: Record<string, unknown>) {
return {
appId: "",
artifactPath: miniappArtifactRoot(),
build: {},
...settings,
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
privateKey: undefined,
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
hasStoredCredentials: Boolean(settings.credential),
...this.buildConfigSummary(settings.apiBaseUrl, settings.appId),
};
}
private buildConfigSummary(
storedApiBaseUrl: unknown,
storedAppId: unknown,
): {
requestDomain: string | null;
buildError: string | null;
} {
try {
const base = miniappApiBaseUrl(storedApiBaseUrl);
weappAppId(storedAppId);
return { requestDomain: new URL(base).host, buildError: null };
} catch (error) {
return {
requestDomain: null,
buildError: error instanceof Error ? error.message : "小程序构建参数未配置",
};
}
}
/** 表单回显:品牌未显式配置时展示环境推导出的默认地址,便于管理员在其基础上修改。 */
private effectiveApiBaseUrl(storedApiBaseUrl: unknown) {
try {
return miniappApiBaseUrl(storedApiBaseUrl);
} catch {
return typeof storedApiBaseUrl === "string" ? storedApiBaseUrl : "";
}
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
}
@@ -0,0 +1,172 @@
import {
BadGatewayException,
BadRequestException,
ConflictException,
Injectable,
} from "@nestjs/common";
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import { getTemplatePackageManifest, templatePackageRegistry } from "@personal-brand/config";
import { AdminMiniAppBuildService } from "./admin-miniapp-build.service.js";
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
import { miniappProjectPath } from "./miniapp-artifact.js";
import { miniappApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
import { buildingStaleMs, isStaleBuilding } from "./miniapp-build-status.js";
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
import { runMiniAppUpload } from "./miniapp-upload.js";
interface BuildLog {
at: string;
message: string;
stream: "stdout" | "stderr";
}
function miniAppTemplateKey(industryTemplateKey: string): string | null {
return (
getTemplatePackageManifest(industryTemplateKey)?.packageKey ??
templatePackageRegistry.find((item) =>
item.supportedIndustryTemplates.includes(industryTemplateKey),
)?.packageKey ??
null
);
}
function log(message: string, stream: "stdout" | "stderr"): BuildLog {
return { at: new Date().toISOString(), message, stream };
}
@Injectable()
export class AdminMiniAppUploadService {
constructor(
private readonly releases: AdminMiniAppReleaseService,
private readonly builds: AdminMiniAppBuildService,
) {}
async run(
brandId: string,
actorId: string,
taskId: string,
input: { version?: string; desc?: string; robot?: number },
): Promise<unknown> {
const { task, brand } = await this.releases.uploadContext(brandId, taskId);
if (task.status !== "built" && task.status !== "failed")
throw new BadRequestException("当前小程序发布任务不能重复上传");
const staleBuilding = isStaleBuilding(task);
if (task.buildStatus === "building" && !staleBuilding)
throw new ConflictException("小程序构建正在进行中,请稍后");
const settings = this.jsonObject(brand.miniAppSettings);
const appId = weappAppId(settings.appId);
const privateKey = settings.credential
? decryptMiniAppCredential(settings.credential)
: this.requiredEnv("WECHAT_UPLOAD_PRIVATE_KEY");
const normalizedPrivateKey = normalizePrivateKey(privateKey);
const keyInspection = inspectPrivateKey(normalizedPrivateKey);
if (!keyInspection.valid)
throw new BadRequestException(
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序上传配置”里重新粘贴完整私钥。`,
);
const templateKey = miniAppTemplateKey(brand.templateKey);
if (!templateKey) throw new BadRequestException("当前品牌模板没有可上传的小程序包");
const buildConfig = { apiBaseUrl: miniappApiBaseUrl(settings.apiBaseUrl), appId };
const projectPath = miniappProjectPath(templateKey);
const buildLogs = [
log(`开始构建 ${templateKey} 微信小程序`, "stdout"),
log(`请求地址 ${buildConfig.apiBaseUrl},AppID ${buildConfig.appId}`, "stdout"),
];
if (staleBuilding)
buildLogs.push(
log(
`上一次构建已超过 ${Math.round(buildingStaleMs() / 60000)} 分钟没有进展,按中断处理并重新构建`,
"stderr",
),
);
if (task.status === "failed") {
await this.releases.updateStatus(brandId, actorId, taskId, {
status: "built",
buildLogs,
buildStatus: "building",
});
} else {
await this.releases.updateBuild(brandId, actorId, taskId, {
buildLogs,
buildStatus: "building",
error: null,
});
}
const result = await this.builds.run(templateKey, buildConfig, (message, stream) => {
buildLogs.push(log(message, stream));
void this.releases
.updateBuild(brandId, actorId, taskId, { buildLogs, buildStatus: "building" })
.catch(() => undefined);
});
if (result.exitCode !== 0) {
buildLogs.push(log(`构建失败,退出码 ${result.exitCode}`, "stderr"));
await this.releases.updateBuild(brandId, actorId, taskId, {
error: "小程序构建失败,请查看构建日志",
buildLogs,
buildStatus: "failed",
});
throw new BadRequestException("小程序构建失败,请查看构建日志");
}
if (!existsSync(projectPath) || !existsSync(resolve(projectPath, "app.json"))) {
buildLogs.push(log(`构建完成但缺少产物:${projectPath}/app.json`, "stderr"));
await this.releases.updateBuild(brandId, actorId, taskId, {
error: "小程序构建产物缺少 app.json",
buildLogs,
buildStatus: "failed",
});
throw new BadRequestException(`小程序构建产物缺少 app.json:${projectPath}`);
}
buildLogs.push(log("构建完成,开始上传微信", "stdout"));
await this.releases.updateBuild(brandId, actorId, taskId, {
buildLogs,
buildStatus: "success",
});
try {
const uploadResult = await runMiniAppUpload({
projectPath,
appid: appId,
privateKey: normalizedPrivateKey,
version: input.version ?? String(task.version),
desc: input.desc ?? `brand content v${task.version}`,
robot: input.robot ?? 1,
});
return this.releases.updateStatus(brandId, actorId, taskId, {
status: "uploaded",
buildLogs,
buildStatus: "success",
weappUploadId:
typeof uploadResult.strUint64Version === "string"
? uploadResult.strUint64Version
: String(task.version),
});
} catch (error) {
const message = error instanceof Error ? error.message : "微信代码上传失败";
await this.releases.updateStatus(brandId, actorId, taskId, {
status: "failed",
buildLogs,
buildStatus: "failed",
error: message,
});
throw new BadGatewayException(message);
}
}
private requiredEnv(name: string): string {
const value = process.env[name];
if (!value) throw new BadRequestException(`${name} 未配置`);
return value;
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
}