fix: 打通小程序代码上传链路
小程序上传此前连续失败,根因分散在状态机、产物路径、模块导入、私钥解析和进程隔离上,逐项修复: - 构建进度改用 updateBuild 只写 buildStatus/buildLogs,不再用 updateStatus 记录进度,避免状态机拒绝自我迁移而返回 409 - 产物目录锚定仓库根目录,不再随 API 进程工作目录变成 apps/api/apps/taro/dist - miniprogram-ci 为 CommonJS 包,动态导入后从 default 归一化取 Project/upload,替换原有的类型断言 - 上传私钥统一还原成合法 PEM;输入框曾把换行吞成单行,导致 OpenSSL 解码失败,现保存时校验、上传时自动修复存量数据 - 上传改在独立子进程执行,miniprogram-ci 崩溃或超时不再终止 API 进程,失败返回 502 并保留微信原始错误 - 构建超过 MINIAPP_BUILD_STALE_MS 无进度即视为中断,允许重新上传,避免任务永久卡在 building - 构建前校验请求地址与 AppID,请求地址支持在品牌配置中维护,环境变量仅作回落,避免再打出指向 localhost 的包 - 小程序 /media/ 按请求地址的 origin 解析,不再依赖网关剥离 /api 前缀 新增对应单测与集成断言,并更新部署说明。
This commit is contained in:
1 parent
f52577ff9e
commit
44fe7a0142
27 files changed
+986
-62
No files matched your search
@@ -31,6 +31,12 @@ export async function createApp(): Promise<NestFastifyApplication> {
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV !== "test") {
|
||||
process.on("unhandledRejection", (reason) => {
|
||||
console.error("[api] unhandled rejection", reason);
|
||||
});
|
||||
process.on("uncaughtException", (error) => {
|
||||
console.error("[api] uncaught exception", error);
|
||||
});
|
||||
const app = await createApp();
|
||||
await app.listen({ port: Number(process.env.API_PORT ?? 3001), host: "0.0.0.0" });
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
BadGatewayException,
|
||||
Body,
|
||||
ConflictException,
|
||||
Controller,
|
||||
@@ -19,15 +20,18 @@ import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.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";
|
||||
|
||||
const MINIAPP_ARTIFACT_ROOT = process.env.MINIAPP_ARTIFACT_ROOT ?? "apps/taro/dist";
|
||||
|
||||
function miniAppTemplateKey(industryTemplateKey: string): string | null {
|
||||
return (
|
||||
getTemplatePackageManifest(industryTemplateKey)?.packageKey ??
|
||||
@@ -38,22 +42,6 @@ function miniAppTemplateKey(industryTemplateKey: string): string | null {
|
||||
);
|
||||
}
|
||||
|
||||
interface MiniprogramCi {
|
||||
Project: new (options: {
|
||||
projectPath: string;
|
||||
type: "miniProgram";
|
||||
appid: string;
|
||||
privateKey: string;
|
||||
}) => unknown;
|
||||
upload: (options: {
|
||||
project: unknown;
|
||||
version: string;
|
||||
desc: string;
|
||||
robot: number;
|
||||
setting: { es6: boolean; minified: boolean };
|
||||
}) => Promise<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
interface BuildLog {
|
||||
at: string;
|
||||
message: string;
|
||||
@@ -92,17 +80,48 @@ export class AdminMiniAppReleaseController {
|
||||
select: { miniAppSettings: true },
|
||||
});
|
||||
const settings = this.jsonObject(brand?.miniAppSettings);
|
||||
const buildConfig = this.buildConfigSummary(settings.apiBaseUrl, settings.appId);
|
||||
return {
|
||||
appId: "",
|
||||
artifactPath: MINIAPP_ARTIFACT_ROOT,
|
||||
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 : "";
|
||||
}
|
||||
}
|
||||
|
||||
@Patch("settings")
|
||||
async updateSettings(
|
||||
@Req() request: FastifyRequest,
|
||||
@@ -110,20 +129,40 @@ export class AdminMiniAppReleaseController {
|
||||
): Promise<unknown> {
|
||||
const identity = await this.identity(request);
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
if (body.privateKey !== undefined && !body.privateKey.startsWith("-----BEGIN"))
|
||||
throw new BadRequestException("上传私钥格式无效");
|
||||
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 brand = await this.prisma.brandProfile.findUniqueOrThrow({
|
||||
where: { id: identity.brandId },
|
||||
select: { miniAppSettings: true },
|
||||
});
|
||||
const current = this.jsonObject(brand.miniAppSettings);
|
||||
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(body.privateKey);
|
||||
: 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),
|
||||
@@ -137,10 +176,12 @@ export class AdminMiniAppReleaseController {
|
||||
});
|
||||
return {
|
||||
appId: settings.appId,
|
||||
artifactPath: MINIAPP_ARTIFACT_ROOT,
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -169,40 +210,79 @@ export class AdminMiniAppReleaseController {
|
||||
if (!task) throw new BadRequestException("小程序发布任务不存在");
|
||||
if (task.status !== "built" && task.status !== "failed")
|
||||
throw new BadRequestException("当前小程序发布任务不能重复上传");
|
||||
if (task.buildStatus === "building")
|
||||
const staleBuilding = isStaleBuilding(task);
|
||||
if (task.buildStatus === "building" && !staleBuilding)
|
||||
throw new ConflictException("小程序构建正在进行中,请稍后");
|
||||
const brand = await this.prisma.brandProfile.findUniqueOrThrow({
|
||||
where: { id: identity.brandId },
|
||||
select: { miniAppSettings: true, templateKey: true },
|
||||
});
|
||||
const settings = this.jsonObject(brand.miniAppSettings);
|
||||
const appid =
|
||||
typeof settings.appId === "string" && settings.appId
|
||||
? settings.appId
|
||||
: this.requiredEnv("WECHAT_APP_ID");
|
||||
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("当前品牌模板没有可上传的小程序包");
|
||||
const projectPath = resolve(MINIAPP_ARTIFACT_ROOT, templateKey, "weapp");
|
||||
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",
|
||||
},
|
||||
];
|
||||
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
||||
status: task.status,
|
||||
buildLogs,
|
||||
buildStatus: "building",
|
||||
});
|
||||
const result = await this.buildWeApp(templateKey, (message, stream) => {
|
||||
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
|
||||
.updateStatus(identity.brandId, identity.subject, taskId, {
|
||||
status: task.status,
|
||||
.updateBuild(identity.brandId, identity.subject, taskId, {
|
||||
buildLogs,
|
||||
buildStatus: "building",
|
||||
})
|
||||
@@ -214,8 +294,7 @@ export class AdminMiniAppReleaseController {
|
||||
message: `构建失败,退出码 ${result.exitCode}`,
|
||||
stream: "stderr",
|
||||
});
|
||||
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
||||
status: task.status,
|
||||
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
|
||||
error: `小程序构建失败,请查看构建日志`,
|
||||
buildLogs,
|
||||
buildStatus: "failed",
|
||||
@@ -228,38 +307,30 @@ export class AdminMiniAppReleaseController {
|
||||
message: `构建完成但缺少产物:${projectPath}/app.json`,
|
||||
stream: "stderr",
|
||||
});
|
||||
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
||||
status: task.status,
|
||||
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
|
||||
error: "小程序构建产物缺少 app.json",
|
||||
buildLogs,
|
||||
buildStatus: "failed",
|
||||
});
|
||||
throw new BadRequestException("小程序构建产物缺少 app.json");
|
||||
throw new BadRequestException(`小程序构建产物缺少 app.json:${projectPath}`);
|
||||
}
|
||||
buildLogs.push({
|
||||
at: new Date().toISOString(),
|
||||
message: "构建完成,开始上传微信",
|
||||
stream: "stdout",
|
||||
});
|
||||
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
||||
status: task.status,
|
||||
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
|
||||
buildLogs,
|
||||
buildStatus: "success",
|
||||
});
|
||||
const ci = (await import("miniprogram-ci")) as unknown as MiniprogramCi;
|
||||
const project = new ci.Project({
|
||||
projectPath,
|
||||
type: "miniProgram",
|
||||
appid,
|
||||
privateKey,
|
||||
});
|
||||
try {
|
||||
const uploadResult = await ci.upload({
|
||||
project,
|
||||
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,
|
||||
setting: { es6: false, minified: true },
|
||||
});
|
||||
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
||||
status: "uploaded",
|
||||
@@ -271,13 +342,14 @@ export class AdminMiniAppReleaseController {
|
||||
: 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: error instanceof Error ? error.message : "微信代码上传失败",
|
||||
error: message,
|
||||
});
|
||||
throw error;
|
||||
throw new BadGatewayException(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,12 +376,19 @@ export class AdminMiniAppReleaseController {
|
||||
|
||||
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: resolve(process.cwd(), "../.."),
|
||||
env: { ...process.env, TEMPLATE_KEY: templateKey, TARO_ENV: "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") => {
|
||||
|
||||
@@ -107,6 +107,48 @@ export class AdminMiniAppReleaseService {
|
||||
);
|
||||
}
|
||||
|
||||
async updateBuild(
|
||||
brandId: string,
|
||||
actorId: string,
|
||||
taskId: string,
|
||||
input: {
|
||||
buildStatus?: "idle" | "building" | "success" | "failed";
|
||||
error?: string | null;
|
||||
buildLogs?: unknown;
|
||||
},
|
||||
): Promise<unknown> {
|
||||
return this.prisma.$transaction(
|
||||
async (tx) => {
|
||||
const task = await tx.miniAppReleaseTask.findFirst({ where: { id: taskId, brandId } });
|
||||
if (!task) throw new NotFoundException("小程序发布任务不存在");
|
||||
const buildStatusChanged =
|
||||
input.buildStatus !== undefined && input.buildStatus !== task.buildStatus;
|
||||
return tx.miniAppReleaseTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
...(input.error !== undefined ? { error: input.error } : {}),
|
||||
...(input.buildLogs !== undefined
|
||||
? { buildLogs: input.buildLogs as Prisma.InputJsonValue }
|
||||
: {}),
|
||||
...(input.buildStatus ? { buildStatus: input.buildStatus } : {}),
|
||||
...(buildStatusChanged
|
||||
? {
|
||||
audit: this.audit(task.audit, {
|
||||
action: "build-updated",
|
||||
actorId,
|
||||
from: task.buildStatus,
|
||||
to: input.buildStatus,
|
||||
at: new Date().toISOString(),
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
|
||||
);
|
||||
}
|
||||
|
||||
private audit(value: Prisma.JsonValue | null, entry: Record<string, unknown>) {
|
||||
return [...(Array.isArray(value) ? value : []), entry] as Prisma.InputJsonValue[];
|
||||
}
|
||||
|
||||
@@ -6,6 +6,11 @@ export class UpdateMiniAppSettingsDto {
|
||||
@MaxLength(100)
|
||||
appId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
apiBaseUrl?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export const REPOSITORY_ROOT = fileURLToPath(new URL("../../../../..", import.meta.url));
|
||||
|
||||
export function miniappArtifactRoot(configured = process.env.MINIAPP_ARTIFACT_ROOT): string {
|
||||
return configured
|
||||
? resolve(REPOSITORY_ROOT, configured)
|
||||
: resolve(REPOSITORY_ROOT, "apps/taro/dist");
|
||||
}
|
||||
|
||||
export function miniappProjectPath(templatePackageKey: string): string {
|
||||
return resolve(miniappArtifactRoot(), templatePackageKey, "weapp");
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
|
||||
|
||||
function normalizeBaseUrl(value: string): string {
|
||||
return value.trim().replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求地址优先取品牌在后台维护的值,其次才是环境变量。
|
||||
* 小程序包内的 `API_BASE_URL` 是编译期常量,改地址需要重新构建上传,
|
||||
* 但地址本身属于可在后台修改的配置,不再写死在服务端环境变量里。
|
||||
*/
|
||||
export function miniappApiBaseUrl(
|
||||
storedApiBaseUrl?: unknown,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): string {
|
||||
const stored =
|
||||
typeof storedApiBaseUrl === "string" && storedApiBaseUrl.trim()
|
||||
? storedApiBaseUrl.trim()
|
||||
: undefined;
|
||||
if (stored) return validate(normalizeBaseUrl(stored));
|
||||
const explicit = env.MINIAPP_API_BASE_URL?.trim();
|
||||
if (explicit) return validate(normalizeBaseUrl(explicit));
|
||||
const publicBase = env.PUBLIC_BASE_URL?.trim();
|
||||
if (publicBase)
|
||||
return validate(
|
||||
normalizeBaseUrl(`${normalizeBaseUrl(publicBase)}${env.MINIAPP_API_PATH ?? "/api"}`),
|
||||
);
|
||||
throw new Error(
|
||||
"未配置小程序请求地址:请在“配置与发布 → 小程序上传配置”里填写“小程序请求地址”,例如 https://wechat.app.que01.top/api",
|
||||
);
|
||||
}
|
||||
|
||||
/** 保存前校验后台填写的请求地址,错误信息直接给到管理员。 */
|
||||
export function validateApiBaseUrl(value: string): string {
|
||||
return validate(normalizeBaseUrl(value));
|
||||
}
|
||||
|
||||
function validate(value: string): string {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
throw new Error(`小程序请求地址不是合法 URL:${value}`);
|
||||
}
|
||||
if (url.protocol !== "https:" && !LOCAL_HOSTS.has(url.hostname))
|
||||
throw new Error(`小程序请求地址必须使用 https(当前 ${value}),否则真机无法访问`);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function weappAppId(storedAppId: unknown, env: NodeJS.ProcessEnv = process.env): string {
|
||||
const candidate =
|
||||
typeof storedAppId === "string" && storedAppId.trim()
|
||||
? storedAppId.trim()
|
||||
: (env.WEAPP_APP_ID?.trim() ?? "");
|
||||
if (!candidate || candidate === "undefined" || candidate === "touristappid")
|
||||
throw new Error("未配置微信 AppID:请在“小程序上传配置”里填写或设置 WEAPP_APP_ID");
|
||||
return candidate;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
const DEFAULT_STALE_MS = 15 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* 构建进程可能被系统杀掉或随 API 一起退出,此时任务会永久停在 `building`。
|
||||
* 超过该时长没有任何进度写入,就认为这次构建已经中断,允许重新发起。
|
||||
*/
|
||||
export function buildingStaleMs(configured = process.env.MINIAPP_BUILD_STALE_MS): number {
|
||||
const parsed = Number(configured);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_STALE_MS;
|
||||
}
|
||||
|
||||
export function isStaleBuilding(
|
||||
task: { buildStatus?: string | null; updatedAt: Date | string },
|
||||
now = Date.now(),
|
||||
): boolean {
|
||||
if (task.buildStatus !== "building") return false;
|
||||
const updatedAt = new Date(task.updatedAt).getTime();
|
||||
if (Number.isNaN(updatedAt)) return false;
|
||||
return now - updatedAt >= buildingStaleMs();
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export interface MiniprogramCi {
|
||||
Project: new (options: {
|
||||
projectPath: string;
|
||||
type: "miniProgram";
|
||||
appid: string;
|
||||
privateKey: string;
|
||||
}) => unknown;
|
||||
upload: (options: {
|
||||
project: unknown;
|
||||
version: string;
|
||||
desc: string;
|
||||
robot: number;
|
||||
setting: { es6: boolean; minified: boolean };
|
||||
}) => Promise<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* `miniprogram-ci` 是 CommonJS 包,ESM 动态导入后导出挂在 `default` 上,
|
||||
* 直接取命名导出会得到 undefined。这里统一归一化两种模块形态。
|
||||
*/
|
||||
export function resolveMiniprogramCi(imported: unknown): MiniprogramCi {
|
||||
const namespace = imported as { default?: unknown } | null;
|
||||
const resolved = (namespace?.default ?? imported) as Partial<MiniprogramCi> | null;
|
||||
if (typeof resolved?.Project !== "function" || typeof resolved?.upload !== "function")
|
||||
throw new Error("miniprogram-ci 模块缺少 Project/upload 导出");
|
||||
return resolved as MiniprogramCi;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { createPrivateKey } from "node:crypto";
|
||||
|
||||
const PEM_HEADER = /^-----BEGIN ([A-Z0-9 ]+)-----/;
|
||||
const PEM_BLOCK = /-----BEGIN ([A-Z0-9 ]+)-----([\s\S]*?)-----END \1-----/;
|
||||
|
||||
function rewrapBody(header: string, body: string): string {
|
||||
const compact = body.replace(/\s+/g, "");
|
||||
const lines = compact.match(/.{1,64}/g) ?? [];
|
||||
return `-----BEGIN ${header}-----\n${lines.join("\n")}\n-----END ${header}-----`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台输入框、聊天工具和 JSON 字符串都会破坏 PEM 的换行。
|
||||
* 这里把字面量 `\n`、被折成单行的 base64 主体统一还原成合法 PEM。
|
||||
*/
|
||||
export function normalizePrivateKey(raw: string): string {
|
||||
const unescaped = raw
|
||||
.replace(/\r\n/g, "\n")
|
||||
.replace(/\\r\\n|\\n|\\r/g, "\n")
|
||||
.trim();
|
||||
const block = unescaped.match(PEM_BLOCK);
|
||||
if (block?.[1] !== undefined && block[2] !== undefined)
|
||||
return `${rewrapBody(block[1], block[2])}\n`;
|
||||
const header = unescaped.match(PEM_HEADER);
|
||||
if (header?.[1] === undefined) return `${unescaped}\n`;
|
||||
const body = unescaped.replace(PEM_HEADER, "").replace(/-----END [A-Z0-9 ]+-----/, "");
|
||||
return `${rewrapBody(header[1], body)}\n`;
|
||||
}
|
||||
|
||||
export interface PrivateKeyInspection {
|
||||
valid: boolean;
|
||||
kind?: string;
|
||||
bits?: number;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export function inspectPrivateKey(raw: string): PrivateKeyInspection {
|
||||
try {
|
||||
const key = createPrivateKey(normalizePrivateKey(raw));
|
||||
return {
|
||||
valid: true,
|
||||
...(key.asymmetricKeyType ? { kind: key.asymmetricKeyType } : {}),
|
||||
...(key.asymmetricKeyDetails?.modulusLength
|
||||
? { bits: key.asymmetricKeyDetails.modulusLength }
|
||||
: {}),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
valid: false,
|
||||
reason: error instanceof Error ? error.message : "私钥解析失败",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { resolveMiniprogramCi } from "./miniapp-ci.js";
|
||||
import { UPLOAD_RESULT_PREFIX, type MiniAppUploadRequest } from "./miniapp-upload-protocol.js";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
interface UploadOptions extends MiniAppUploadRequest {
|
||||
setting: { es6: boolean; minified: boolean };
|
||||
}
|
||||
|
||||
export async function uploadMiniAppCode(options: UploadOptions): Promise<Record<string, unknown>> {
|
||||
const ci = resolveMiniprogramCi(await import("miniprogram-ci"));
|
||||
const project = new ci.Project({
|
||||
projectPath: options.projectPath,
|
||||
type: "miniProgram",
|
||||
appid: options.appid,
|
||||
privateKey: options.privateKey,
|
||||
});
|
||||
return ci.upload({
|
||||
project,
|
||||
version: options.version,
|
||||
desc: options.desc,
|
||||
robot: options.robot,
|
||||
setting: options.setting,
|
||||
});
|
||||
}
|
||||
|
||||
async function readStdin(): Promise<string> {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of process.stdin) chunks.push(chunk as Buffer);
|
||||
return Buffer.concat(chunks).toString("utf8");
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const request = JSON.parse(await readStdin()) as MiniAppUploadRequest;
|
||||
try {
|
||||
const result = await uploadMiniAppCode({
|
||||
...request,
|
||||
setting: { es6: false, minified: true },
|
||||
});
|
||||
process.stdout.write(`${UPLOAD_RESULT_PREFIX}${JSON.stringify({ ok: true, result })}\n`);
|
||||
} catch (error) {
|
||||
process.stdout.write(
|
||||
`${UPLOAD_RESULT_PREFIX}${JSON.stringify({
|
||||
ok: false,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
})}\n`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
function isDirectExecution(): boolean {
|
||||
const entry = process.argv[1];
|
||||
if (!entry) return false;
|
||||
try {
|
||||
return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (isDirectExecution()) {
|
||||
await main();
|
||||
process.exit(process.exitCode ?? 0);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
export const UPLOAD_RESULT_PREFIX = "__MINIAPP_UPLOAD_RESULT__";
|
||||
|
||||
export interface MiniAppUploadRequest {
|
||||
projectPath: string;
|
||||
appid: string;
|
||||
privateKey: string;
|
||||
version: string;
|
||||
desc: string;
|
||||
robot: number;
|
||||
}
|
||||
|
||||
export interface MiniAppUploadOutcome {
|
||||
ok: boolean;
|
||||
result?: Record<string, unknown>;
|
||||
message?: string;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
UPLOAD_RESULT_PREFIX,
|
||||
type MiniAppUploadOutcome,
|
||||
type MiniAppUploadRequest,
|
||||
} from "./miniapp-upload-protocol.js";
|
||||
|
||||
const RUNNER_PATH = fileURLToPath(new URL("./miniapp-upload-cli.js", import.meta.url));
|
||||
const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
|
||||
function parseOutcome(stdout: string): MiniAppUploadOutcome | null {
|
||||
const line = stdout
|
||||
.split("\n")
|
||||
.filter((item) => item.startsWith(UPLOAD_RESULT_PREFIX))
|
||||
.pop();
|
||||
if (!line) return null;
|
||||
try {
|
||||
return JSON.parse(line.slice(UPLOAD_RESULT_PREFIX.length)) as MiniAppUploadOutcome;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* miniprogram-ci 会 fork 子进程,失败时可能抛出无人接管的 rejection 并终止宿主进程。
|
||||
* 因此上传必须在独立进程里执行,任何崩溃都不能影响 API 服务本身。
|
||||
*/
|
||||
export function runMiniAppUpload(
|
||||
request: MiniAppUploadRequest,
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
): Promise<Record<string, unknown>> {
|
||||
return new Promise((resolvePromise, rejectPromise) => {
|
||||
const child = spawn(process.execPath, [RUNNER_PATH], {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let settled = false;
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
child.kill("SIGKILL");
|
||||
rejectPromise(new Error("微信代码上传超时,请稍后重试"));
|
||||
}, timeoutMs);
|
||||
const finish = (action: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
action();
|
||||
};
|
||||
|
||||
child.stdout.on("data", (chunk: Buffer) => {
|
||||
stdout += chunk.toString();
|
||||
});
|
||||
child.stderr.on("data", (chunk: Buffer) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
child.on("error", () => finish(() => rejectPromise(new Error("微信上传进程启动失败"))));
|
||||
child.on("close", (code) =>
|
||||
finish(() => {
|
||||
const outcome = parseOutcome(stdout);
|
||||
if (outcome?.ok && outcome.result) return resolvePromise(outcome.result);
|
||||
const detail = outcome?.message ?? stderr.trim().split("\n").pop() ?? "";
|
||||
rejectPromise(
|
||||
new Error(
|
||||
detail
|
||||
? `微信代码上传失败:${detail}`
|
||||
: `微信代码上传失败(上传进程退出码 ${code ?? 1})`,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
child.stdin.on("error", () => undefined);
|
||||
child.stdin.end(JSON.stringify(request));
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user