Compare commits

...
8 Commits
Author SHA1 Message Date
que01 6df4e1d72b docs: 补充模板契约发布快照刷新流程
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
2026-10-21 09:02:16 +08:00
que01 cb046a4c27 fix: 支持显式放行遗留字段删除的重发分类 2026-10-21 09:00:05 +08:00
que01 3738be884b chore: 更新模板完成证据源码哈希 2026-10-20 22:25:16 +08:00
que01 193858c727 fix: 增加模板契约发布快照重发工具 2026-10-20 22:14:55 +08:00
que01 ea81c754ed test: 增加发布包运行时预检 2026-10-20 21:24:21 +08:00
que01 16fd827634 fix: 收口发布包完整性与模板契约迁移 2026-10-20 17:59:11 +08:00
que01 38e9d59864 chore: 更新模板完成证据源码哈希 2026-10-20 17:37:34 +08:00
que01 fb072d844b fix: 补齐发布包补丁文件 2026-10-20 17:35:04 +08:00
11 changed files with 1276 additions and 35 deletions

No files matched your search

@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
"generatedAt": "2026-10-20T09:00:52.740+00:00",
"generatedAt": "2026-10-20T13:23:08.179Z",
"templates": {
"acheng-campus-food": {
"real-manifest-interaction": {
@@ -256,5 +256,5 @@
}
}
},
"sourceTreeHash": "775950266c3ec796f5af6eafabedae91a1fa6c1d4c71b29ca8d5b589b4846473"
"sourceTreeHash": "7db7647772c54d29bcff2211b59bc3a1c261988b543046ba3b078d5945d3a599"
}
+2
View File
@@ -381,6 +381,8 @@ try {
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"], release);
await backupDatabase(path.join(root, "shared/backups", manifest.version + ".dump"));
await pruneBackups(path.join(root, "shared/backups"));
// 旧数据的模板包声明必须先收敛,migration 才能安全地删除兼容字段。
run(process.execPath, ["deploy/prepare-template-contract.mjs", ".", "--apply"], release);
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "migrate", "deploy"], release);
const seedDirectory = path.join(process.env.LOCAL_MEDIA_ROOT, "seed");
await copyMissingFiles(path.join(release, "seed-media"), seedDirectory);
+479
View File
@@ -0,0 +1,479 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { copyFile, mkdir, readFile } from "node:fs/promises";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { spawnSync } from "node:child_process";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
const CONTRACT_MIGRATION = "20261018120000_enforce_single_template_contract";
const source = path.resolve(process.argv[2] ?? ".");
const apply = process.argv.includes("--apply");
const catalogPath = path.join(source, "template-catalog.json");
const apiRequire = createRequire(new URL("../apps/api/package.json", import.meta.url));
const { PrismaClient } = apiRequire("@prisma/client");
function object(value) {
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
}
function nonEmpty(value) {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function sha256(content) {
return createHash("sha256").update(content).digest("hex");
}
function supportsIndustry(version, industry) {
const manifest = object(version.manifestSnapshot) ?? object(version.manifest) ?? {};
const fixture = object(object(manifest.previewFixture)?.[industry]);
return (
version.status === "published" &&
manifest.packageKey === version.packageKey &&
manifest.visualTemplateKey === version.packageKey &&
manifest.version === version.version &&
manifest.runtimeContract === "1.0" &&
Array.isArray(manifest.supportedIndustryTemplates) &&
manifest.supportedIndustryTemplates.includes(industry) &&
fixture !== null
);
}
function versionShape(version) {
return {
id: version.id,
packageKey: version.packageKey,
version: version.version,
status: version.status,
contentChecksum: version.contentChecksum,
manifestSnapshot: version.manifestSnapshot ?? version.manifest,
};
}
/**
* 只规划旧数据到单一模板契约的转换。运行时不得复用此逻辑做兜底。
*/
export function buildTemplateContractPlan({ brands, versions, catalog }) {
const catalogPackages = catalog.packages ?? [];
const normalizedVersions = versions.map(versionShape);
const imports = new Map();
const installations = [];
for (const brand of brands) {
if (!Array.isArray(brand.installations) || brand.installations.length > 1)
throw new Error(`品牌 ${brand.slug} 存在多条模板安装记录,必须人工处理`);
const installation = brand.installations?.[0] ?? null;
const declarations = [
["installation.visualTemplateKey", nonEmpty(installation?.visualTemplateKey)],
["brand.config.visualTemplateKey", nonEmpty(brand.brandVisualTemplateKey)],
[
"installation.configSnapshot.visualTemplateKey",
nonEmpty(installation?.snapshotVisualTemplateKey),
],
["installation.configSnapshot.packageKey", nonEmpty(installation?.snapshotPackageKey)],
].filter(([, value]) => value);
const declaredKeys = [...new Set(declarations.map(([, value]) => value))];
if (declaredKeys.length > 1)
throw new Error(`品牌 ${brand.slug} 的模板包声明冲突:${declaredKeys.join("、")}`);
let selected;
const linkedId = nonEmpty(installation?.templatePackageVersionId);
if (linkedId) {
selected = normalizedVersions.find((version) => version.id === linkedId);
if (!selected || !supportsIndustry(selected, brand.templateKey))
throw new Error(`品牌 ${brand.slug} 已关联的模板包版本不符合契约`);
if (declaredKeys[0] && declaredKeys[0] !== selected.packageKey)
throw new Error(`品牌 ${brand.slug} 的模板包声明与已关联版本冲突`);
} else {
const packageKey = declaredKeys[0];
if (!packageKey) throw new Error(`品牌 ${brand.slug} 没有可审计的旧模板包声明`);
const candidates = normalizedVersions.filter(
(version) =>
version.packageKey === packageKey && supportsIndustry(version, brand.templateKey),
);
if (candidates.length > 1)
throw new Error(`品牌 ${brand.slug} 匹配到多个已发布模板包版本,必须人工处理`);
if (candidates.length === 1) {
selected = candidates[0];
} else {
const bundled = catalogPackages.filter(
(entry) =>
entry.packageKey === packageKey &&
supportsIndustry(
{
packageKey: entry.packageKey,
version: entry.version,
status: "published",
manifestSnapshot: entry.manifest,
},
brand.templateKey,
),
);
if (bundled.length !== 1)
throw new Error(
`品牌 ${brand.slug} 在发布包中匹配到 ${bundled.length} 个可用模板包,必须人工处理`,
);
selected = bundled[0];
imports.set(`${selected.packageKey}@${selected.version}`, selected);
}
}
installations.push({
brandId: brand.brandId,
slug: brand.slug,
installationId: installation?.id ?? null,
templateKey: brand.templateKey,
packageKey: selected.packageKey,
version: selected.version,
packageVersionId: selected.id ?? null,
catalogImport: !selected.id,
contentChecksum: selected.contentChecksum,
configSnapshot: selected.manifestSnapshot ?? selected.manifest,
});
}
return {
catalogImports: [...imports.values()],
installations,
};
}
async function loadInputs(prisma) {
const columns = await prisma.$queryRawUnsafe(`
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema = current_schema()
AND table_name IN ('BrandTemplateInstallation', 'TemplatePackageVersion')
AND column_name IN ('visualTemplateKey', 'templatePackageVersionId')
`);
const installationVisual = columns.some(
(column) =>
column.table_name === "BrandTemplateInstallation" &&
column.column_name === "visualTemplateKey",
);
const versionVisual = columns.some(
(column) =>
column.table_name === "TemplatePackageVersion" && column.column_name === "visualTemplateKey",
);
if (!installationVisual && !versionVisual) return { alreadyApplied: true };
const tables = await prisma.$queryRawUnsafe(`
SELECT to_regclass('"TemplatePackage"')::text AS package_table,
to_regclass('"TemplatePackageVersion"')::text AS version_table,
to_regclass('"TemplatePackageAuditLog"')::text AS audit_table
`);
if (!tables[0]?.package_table || !tables[0]?.version_table || !tables[0]?.audit_table)
throw new Error("模板包目录表尚未创建,请先让 Prisma 应用目录类 migration");
const brands = await prisma.$queryRawUnsafe(`
SELECT
brand.id AS "brandId",
brand.slug,
brand."templateKey",
brand.config->>'visualTemplateKey' AS "brandVisualTemplateKey",
installation.id AS "installationId",
installation."templatePackageVersionId",
installation."visualTemplateKey" AS "installationVisualTemplateKey",
installation."configSnapshot"->>'visualTemplateKey' AS "snapshotVisualTemplateKey",
installation."configSnapshot"->>'packageKey' AS "snapshotPackageKey"
FROM "BrandProfile" brand
LEFT JOIN "BrandTemplateInstallation" installation ON installation."brandId" = brand.id
ORDER BY brand.slug, installation.id
`);
const grouped = new Map();
for (const row of brands) {
const entry = grouped.get(row.brandId) ?? {
brandId: row.brandId,
slug: row.slug,
templateKey: row.templateKey,
brandVisualTemplateKey: row.brandVisualTemplateKey,
installations: [],
};
if (row.installationId) {
entry.installations.push({
id: row.installationId,
templatePackageVersionId: row.templatePackageVersionId,
visualTemplateKey: row.installationVisualTemplateKey,
snapshotVisualTemplateKey: row.snapshotVisualTemplateKey,
snapshotPackageKey: row.snapshotPackageKey,
});
}
grouped.set(row.brandId, entry);
}
const versions = await prisma.$queryRawUnsafe(`
SELECT id, "packageKey", version, status, "contentChecksum", "manifestSnapshot"
FROM "TemplatePackageVersion"
ORDER BY "packageKey", version
`);
const catalog = JSON.parse(await readFile(catalogPath, "utf8"));
if (catalog.formatVersion !== "1" || !Array.isArray(catalog.packages))
throw new Error("发布包模板目录格式无效");
return { alreadyApplied: false, brands: [...grouped.values()], versions, catalog };
}
async function ensureArtifact(root, entry) {
const sourceArchive = path.join(source, entry.archivePath);
const content = await readFile(sourceArchive);
if (sha256(content) !== entry.archiveChecksum)
throw new Error(`发布包模板归档校验失败:${entry.packageKey}@${entry.version}`);
const target = path.join(
root,
"shared/template-artifacts",
entry.packageKey,
entry.version,
entry.archiveChecksum + ".tar.gz",
);
await mkdir(path.dirname(target), { recursive: true });
try {
const existing = await readFile(target);
if (sha256(existing) === entry.archiveChecksum) return target;
} catch {}
await copyFile(sourceArchive, target);
return target;
}
async function runApply(prisma, plan, deployRoot, actorId) {
const imported = new Map();
await prisma.$transaction(async (tx) => {
for (const entry of plan.catalogImports) {
const artifactPath = await ensureArtifact(deployRoot, entry);
const existingRows = await tx.$queryRawUnsafe(
`SELECT id, status, "contentChecksum", "manifestSnapshot"
FROM "TemplatePackageVersion"
WHERE "packageKey" = $1 AND version = $2`,
entry.packageKey,
entry.version,
);
let version = existingRows[0];
if (version) {
if (version.contentChecksum !== entry.contentChecksum)
throw new Error(`已存在不同内容的模板包版本:${entry.packageKey}@${entry.version}`);
if (version.status === "imported") {
await tx.$executeRawUnsafe(
`UPDATE "TemplatePackageVersion"
SET status = 'published', "updatedAt" = CURRENT_TIMESTAMP
WHERE id = $1`,
version.id,
);
await tx.$executeRawUnsafe(
`INSERT INTO "TemplatePackageAuditLog"
("id", "templatePackageVersionId", "actorId", action, "fromStatus", "toStatus", metadata)
VALUES ($1, $2, $3, 'published', 'imported', 'published', $4::jsonb)`,
randomUUID(),
version.id,
actorId,
JSON.stringify({ source: "legacy-template-contract-migration" }),
);
} else if (version.status !== "published") {
throw new Error(
`模板包版本 ${entry.packageKey}@${entry.version} 状态为 ${version.status},不能用于旧数据迁移`,
);
}
} else {
await tx.$executeRawUnsafe(
`INSERT INTO "TemplatePackage" (id, "packageKey", "createdAt", "updatedAt")
VALUES ($1, $2, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
ON CONFLICT ("packageKey") DO NOTHING`,
randomUUID(),
entry.packageKey,
);
const packageRows = await tx.$queryRawUnsafe(
`SELECT id FROM "TemplatePackage" WHERE "packageKey" = $1`,
entry.packageKey,
);
const templatePackageId = packageRows[0]?.id;
if (!templatePackageId) throw new Error(`无法创建模板包:${entry.packageKey}`);
const versionId = randomUUID();
await tx.$executeRawUnsafe(
`INSERT INTO "TemplatePackageVersion" (
id, "templatePackageId", "packageKey", version, "displayName", "visualTemplateKey",
status, "manifestSnapshot", "validationReport", "contentChecksum", "archiveChecksum",
"artifactPath", "importedById", "importedAt", "createdAt", "updatedAt"
) VALUES (
$1, $2, $3, $4, $5, $3, 'imported', $6::jsonb, $7::jsonb, $8, $9, $10, $11,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
)`,
versionId,
templatePackageId,
entry.packageKey,
entry.version,
entry.displayName,
JSON.stringify(entry.manifest),
JSON.stringify(entry.validationReport),
entry.contentChecksum,
entry.archiveChecksum,
artifactPath,
actorId,
);
await tx.$executeRawUnsafe(
`INSERT INTO "TemplatePackageAuditLog"
("id", "templatePackageVersionId", "actorId", action, "toStatus", metadata)
VALUES ($1, $2, $3, 'imported', 'imported', $4::jsonb)`,
randomUUID(),
versionId,
actorId,
JSON.stringify({
source: "legacy-template-contract-migration",
contentChecksum: entry.contentChecksum,
archiveChecksum: entry.archiveChecksum,
}),
);
await tx.$executeRawUnsafe(
`UPDATE "TemplatePackageVersion"
SET status = 'published', "updatedAt" = CURRENT_TIMESTAMP
WHERE id = $1`,
versionId,
);
await tx.$executeRawUnsafe(
`INSERT INTO "TemplatePackageAuditLog"
("id", "templatePackageVersionId", "actorId", action, "fromStatus", "toStatus", metadata)
VALUES ($1, $2, $3, 'published', 'imported', 'published', $4::jsonb)`,
randomUUID(),
versionId,
actorId,
JSON.stringify({ source: "legacy-template-contract-migration" }),
);
version = {
id: versionId,
status: "published",
contentChecksum: entry.contentChecksum,
};
}
imported.set(`${entry.packageKey}@${entry.version}`, version.id);
}
for (const installation of plan.installations) {
const packageVersionId =
installation.packageVersionId ??
imported.get(`${installation.packageKey}@${installation.version}`);
if (!packageVersionId)
throw new Error(`模板包版本未导入:${installation.packageKey}@${installation.version}`);
if (installation.installationId) {
await tx.$executeRawUnsafe(
`UPDATE "BrandTemplateInstallation"
SET "templateKey" = $2,
"templateVersion" = $3,
"templatePackageVersionId" = $4,
"contentChecksum" = $5,
"configSnapshot" = $6::jsonb,
"visualTemplateKey" = $7,
"updatedAt" = CURRENT_TIMESTAMP
WHERE id = $1`,
installation.installationId,
installation.templateKey,
installation.version,
packageVersionId,
installation.contentChecksum,
JSON.stringify(installation.configSnapshot),
installation.packageKey,
);
} else {
await tx.$executeRawUnsafe(
`INSERT INTO "BrandTemplateInstallation" (
id, "brandId", "templateKey", "templateVersion", "templatePackageVersionId",
"contentChecksum", "configSnapshot", "previousSnapshots", "visualTemplateKey",
"installedAt", "updatedAt"
) VALUES (
$1, $2, $3, $4, $5, $6, $7::jsonb, '[]'::jsonb, $8,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
)`,
randomUUID(),
installation.brandId,
installation.templateKey,
installation.version,
packageVersionId,
installation.contentChecksum,
JSON.stringify(installation.configSnapshot),
installation.packageKey,
);
}
}
});
}
async function resolveFailedMigration(root) {
const result = spawnSync(
"pnpm",
[
"--filter",
"@personal-brand/api",
"exec",
"prisma",
"migrate",
"resolve",
"--rolled-back",
CONTRACT_MIGRATION,
],
{ cwd: root, stdio: "inherit", env: process.env },
);
if (result.status !== 0) throw new Error("无法将失败的模板契约 migration 标记为 rolled-back");
}
async function main() {
const deployRoot = process.env.DEPLOY_ROOT;
if (!deployRoot || !path.isAbsolute(deployRoot))
throw new Error("DEPLOY_ROOT must be an absolute path");
const prisma = new PrismaClient();
try {
const inputs = await loadInputs(prisma);
if (inputs.alreadyApplied) {
console.log("template contract migration already applied; no legacy data to prepare");
return 0;
}
const plan = buildTemplateContractPlan(inputs);
console.log(
JSON.stringify(
{
apply,
catalogImports: plan.catalogImports.map((entry) => ({
packageKey: entry.packageKey,
version: entry.version,
contentChecksum: entry.contentChecksum,
})),
installations: plan.installations.map((entry) => ({
slug: entry.slug,
templateKey: entry.templateKey,
packageKey: entry.packageKey,
version: entry.version,
action: entry.installationId ? "update" : "create",
})),
},
null,
2,
),
);
if (!apply) return 0;
const actorUsername = process.env.TEMPLATE_CATALOG_ACTOR ?? "admin";
const actors = await prisma.$queryRawUnsafe(
`SELECT id FROM "AdminUser" WHERE username = $1 AND "isEnabled" = true`,
actorUsername,
);
if (!actors[0]) throw new Error(`找不到启用的模板迁移操作人:${actorUsername}`);
await runApply(prisma, plan, deployRoot, actors[0].id);
const failed = await prisma.$queryRawUnsafe(
`SELECT 1 FROM _prisma_migrations
WHERE migration_name = $1 AND finished_at IS NULL AND rolled_back_at IS NULL`,
CONTRACT_MIGRATION,
);
if (failed.length) await resolveFailedMigration(source);
console.log("legacy template contract data prepared");
return 0;
} finally {
await prisma.$disconnect();
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main()
.then((code) => {
process.exitCode = code;
})
.catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}
+99
View File
@@ -0,0 +1,99 @@
import assert from "node:assert/strict";
import test from "node:test";
import { buildTemplateContractPlan } from "./prepare-template-contract.mjs";
function manifest(packageKey, industry, version = "1.0.0") {
return {
packageKey,
version,
visualTemplateKey: packageKey,
runtimeContract: "1.0",
supportedIndustryTemplates: [industry],
previewFixture: { [industry]: { schemaVersion: "1" } },
};
}
function catalogEntry(packageKey, industry, version = "1.0.0") {
return {
packageKey,
version,
displayName: packageKey,
contentChecksum: "a".repeat(64),
validationReport: { errors: [] },
manifest: manifest(packageKey, industry, version),
archiveChecksum: "b".repeat(64),
archivePath: `template-artifacts/${packageKey}/${version}/${"b".repeat(64)}.tar.gz`,
};
}
test("template contract plan resolves legacy installations and imports missing packages", () => {
const existing = catalogEntry("atelier-solopreneur", "personal", "1.3.2");
const defaultBrand = catalogEntry("acheng-campus-food", "food", "1.0.3");
const plan = buildTemplateContractPlan({
catalog: { formatVersion: "1", packages: [existing, defaultBrand] },
versions: [],
brands: [
{
brandId: "brand-1",
slug: "atelier-studio",
templateKey: "personal",
brandVisualTemplateKey: "atelier-solopreneur",
installations: [
{
id: "installation-1",
templatePackageVersionId: null,
visualTemplateKey: null,
snapshotVisualTemplateKey: null,
snapshotPackageKey: null,
},
],
},
{
brandId: "brand-2",
slug: "default-brand",
templateKey: "food",
brandVisualTemplateKey: "acheng-campus-food",
installations: [],
},
],
});
assert.deepEqual(
plan.catalogImports.map((entry) => `${entry.packageKey}@${entry.version}`),
["atelier-solopreneur@1.3.2", "acheng-campus-food@1.0.3"],
);
assert.equal(plan.installations.length, 2);
assert.equal(plan.installations[0].installationId, "installation-1");
assert.equal(plan.installations[0].packageVersionId, null);
assert.equal(plan.installations[0].catalogImport, true);
assert.equal(plan.installations[1].installationId, null);
assert.equal(plan.installations[1].slug, "default-brand");
});
test("template contract plan rejects conflicting legacy package declarations", () => {
assert.throws(
() =>
buildTemplateContractPlan({
catalog: { formatVersion: "1", packages: [] },
versions: [],
brands: [
{
brandId: "brand-1",
slug: "conflicting-brand",
templateKey: "food",
brandVisualTemplateKey: "acheng-campus-food",
installations: [
{
id: "installation-1",
templatePackageVersionId: null,
visualTemplateKey: "linjing-editorial",
snapshotVisualTemplateKey: null,
snapshotPackageKey: null,
},
],
},
],
}),
/模板包声明冲突/,
);
});
@@ -0,0 +1,195 @@
#!/usr/bin/env node
import { isDeepStrictEqual } from "node:util";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";
const CONTRACT_KEYS = new Set([
"templateDefinition",
"visualTemplateDefinition",
"visualTemplateManifest",
"templatePackageManifest",
"installation",
"templateKey",
]);
const VOLATILE_KEYS = new Set(["generatedAt"]);
/** null 与缺失键都表示“没有值”,比较前统一剔除,避免旧快照缺列被误判为内容变更。 */
function normalizeNullish(value) {
if (Array.isArray(value)) return value.map(normalizeNullish);
if (value && typeof value === "object") {
const result = {};
for (const [key, item] of Object.entries(value)) {
if (item === null || item === undefined) continue;
result[key] = normalizeNullish(item);
}
return result;
}
return value;
}
function isPlainObject(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
/** 返回递归差异路径,用于判断内容差异是否全部属于显式允许的遗留字段删除。 */
export function diffPaths(published, current, prefix = "") {
if (isPlainObject(published) && isPlainObject(current)) {
const keys = new Set([...Object.keys(published), ...Object.keys(current)]);
return [...keys].flatMap((key) =>
diffPaths(published[key], current[key], prefix ? prefix + "." + key : key),
);
}
return isDeepStrictEqual(published, current) ? [] : [{ path: prefix }];
}
/**
* 只允许自动重发“模板契约字段变化、品牌内容未变”的发布快照。
* 一旦草稿内容与已发布快照不同,必须由管理员显式审查后发布,避免误发草稿。
* allowedRemovedKeys 只能放行“旧值存在、新值缺失”的遗留字段删除,不能放行赋值变化。
*/
export function classifyContractRefresh(published, current, options = {}) {
if (!published || !current) throw new Error("发布快照不能为空");
const allowedRemovedKeys = new Set(options.allowedRemovedKeys ?? []);
const normalizedPublished = normalizeNullish(published);
const normalizedCurrent = normalizeNullish(current);
const keys = new Set([...Object.keys(normalizedPublished), ...Object.keys(normalizedCurrent)]);
const changedKeys = [...keys]
.filter((key) => !VOLATILE_KEYS.has(key))
.filter((key) => !isDeepStrictEqual(normalizedPublished[key], normalizedCurrent[key]));
const blockingKeys = [];
const allowedChanges = [];
for (const key of changedKeys) {
if (CONTRACT_KEYS.has(key)) continue;
const changes = diffPaths(normalizedPublished[key], normalizedCurrent[key], key);
const blocking = changes.filter(
(change) =>
!(allowedRemovedKeys.has(change.path) && isRemovedAtPath(normalizedCurrent, change.path)),
);
if (blocking.length) blockingKeys.push(key);
else allowedChanges.push(...changes.map((change) => change.path));
}
const status = blockingKeys.length
? "content-diverged"
: changedKeys.length
? "contract-stale"
: "current";
return { status, changedKeys, blockingKeys, allowedChanges };
}
function isRemovedAtPath(root, dotPath) {
let node = root;
const parts = dotPath.split(".");
for (const part of parts.slice(0, -1)) {
if (!isPlainObject(node) || !Object.hasOwn(node, part)) return false;
node = node[part];
}
return isPlainObject(node) && !Object.hasOwn(node, parts.at(-1));
}
async function loadServices() {
const apiRequire = createRequire(new URL("../apps/api/package.json", import.meta.url));
const { PrismaService } = await import("../apps/api/dist/prisma.service.js");
const { BrandReleaseService } = await import("../apps/api/dist/brand-release.service.js");
const { BrandReleaseApiService } = await import("../apps/api/dist/brand-release-api.service.js");
// 触发运行时依赖解析,避免发布脚本在错误的工作目录下才失败。
apiRequire("@prisma/client");
const prisma = new PrismaService();
const snapshots = new BrandReleaseService(prisma);
return {
prisma,
snapshots,
releases: new BrandReleaseApiService(prisma, snapshots),
};
}
function parseArgs(argv) {
const options = { apply: false, allowedRemovedKeys: [] };
for (const arg of argv) {
if (arg === "--apply") options.apply = true;
else if (arg.startsWith("--allow-removed-key=")) {
const key = arg.slice("--allow-removed-key=".length);
if (!key) throw new Error("--allow-removed-key 需要字段路径");
options.allowedRemovedKeys.push(key);
} else throw new Error(`未知参数:${arg}`);
}
return options;
}
async function main() {
const options = parseArgs(process.argv.slice(2));
const actorUsername = process.env.TEMPLATE_CATALOG_ACTOR ?? "admin";
const note =
process.env.TEMPLATE_CONTRACT_REPUBLISH_NOTE ?? "模板契约迁移:刷新已发布页面方案兼容性";
const { prisma, snapshots, releases } = await loadServices();
try {
const actor = await prisma.adminUser.findFirst({
where: { username: actorUsername, isEnabled: true },
select: { id: true },
});
if (!actor) throw new Error(`找不到启用的模板迁移操作人:${actorUsername}`);
const brands = await prisma.brandProfile.findMany({
select: { id: true, slug: true },
orderBy: { slug: "asc" },
});
const results = [];
for (const brand of brands) {
const release = await prisma.brandRelease.findFirst({
where: { brandId: brand.id, status: "published" },
orderBy: { version: "desc" },
select: { version: true, snapshot: true },
});
if (!release) {
results.push({ slug: brand.slug, status: "unpublished" });
continue;
}
const current = await snapshots.buildSnapshot(brand.id);
const classification = classifyContractRefresh(release.snapshot, current, options);
const result = {
slug: brand.slug,
releaseVersion: release.version,
...classification,
};
results.push(result);
if (!options.apply || classification.status !== "contract-stale") continue;
const readiness = await releases.readiness(brand.id);
if (!readiness.ready) {
result.status = "not-ready";
result.blockingKeys = readiness.checks
.filter((check) => !check.passed)
.map((check) => check.key);
continue;
}
const published = await releases.publish(brand.id, actor.id, note);
result.status = "republished";
result.newReleaseVersion = published.version;
}
console.log(
JSON.stringify(
{
apply: options.apply,
actor: actorUsername,
allowedRemovedKeys: options.allowedRemovedKeys,
results,
},
null,
2,
),
);
if (
options.apply &&
results.some((item) => ["content-diverged", "not-ready"].includes(item.status))
)
process.exitCode = 1;
} finally {
await prisma.$disconnect();
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}
@@ -0,0 +1,123 @@
import assert from "node:assert/strict";
import test from "node:test";
import { classifyContractRefresh } from "./republish-stale-template-contracts.mjs";
function snapshot(overrides = {}) {
return {
generatedAt: "2026-10-20T00:00:00.000Z",
templateKey: "doors",
templateDefinition: { key: "doors" },
visualTemplateDefinition: { supportedIndustryTemplates: ["personal", "doors"] },
visualTemplateManifest: { pages: [] },
templatePackageManifest: { supportedIndustryTemplates: ["personal", "doors"] },
installation: { templateVersion: "1.0.6" },
brand: { name: "林境门作" },
offerings: [{ name: "入户门" }],
...overrides,
};
}
const staleContract = () =>
snapshot({
generatedAt: "2026-10-20T01:00:00.000Z",
visualTemplateDefinition: { supportedIndustryTemplates: ["doors"] },
templatePackageManifest: { supportedIndustryTemplates: ["doors"] },
installation: { templateVersion: "1.0.7" },
});
test("detects a contract-only stale publication", () => {
assert.deepEqual(classifyContractRefresh(snapshot(), staleContract()), {
status: "contract-stale",
changedKeys: ["visualTemplateDefinition", "templatePackageManifest", "installation"],
blockingKeys: [],
allowedChanges: [],
});
});
test("ignores generated timestamps when the publication is current", () => {
assert.deepEqual(
classifyContractRefresh(snapshot(), snapshot({ generatedAt: "2026-10-21T00:00:00.000Z" })),
{ status: "current", changedKeys: [], blockingKeys: [], allowedChanges: [] },
);
});
test("blocks automatic publication when draft content has diverged", () => {
const current = snapshot({
installation: { templateVersion: "1.0.7" },
brand: { name: "尚未发布的品牌名" },
});
assert.deepEqual(classifyContractRefresh(snapshot(), current), {
status: "content-diverged",
changedKeys: ["installation", "brand"],
blockingKeys: ["brand"],
allowedChanges: [],
});
});
test("treats a missing key and an explicit null as the same value", () => {
const current = snapshot({ brand: { name: "林境门作", miniAppSettings: null } });
assert.equal(classifyContractRefresh(snapshot(), current).status, "current");
});
test("allows an explicitly permitted legacy field removal", () => {
const published = snapshot({
brand: { name: "林境门作", config: { visualTemplateKey: "doors" } },
});
const current = snapshot({ brand: { name: "林境门作", config: {} } });
assert.deepEqual(
classifyContractRefresh(published, current, {
allowedRemovedKeys: ["brand.config.visualTemplateKey"],
}),
{
status: "contract-stale",
changedKeys: ["brand"],
blockingKeys: [],
allowedChanges: ["brand.config.visualTemplateKey"],
},
);
});
test("does not allow an unlisted legacy field removal", () => {
const published = snapshot({
brand: { name: "林境门作", config: { visualTemplateKey: "doors" } },
});
const current = snapshot({ brand: { name: "林境门作", config: {} } });
assert.deepEqual(classifyContractRefresh(published, current), {
status: "content-diverged",
changedKeys: ["brand"],
blockingKeys: ["brand"],
allowedChanges: [],
});
});
test("does not allow a permitted legacy field to change value", () => {
const published = snapshot({
brand: { name: "林境门作", config: { visualTemplateKey: "doors" } },
});
const current = snapshot({ brand: { name: "林境门作", config: { visualTemplateKey: "other" } } });
assert.deepEqual(
classifyContractRefresh(published, current, {
allowedRemovedKeys: ["brand.config.visualTemplateKey"],
}),
{
status: "content-diverged",
changedKeys: ["brand"],
blockingKeys: ["brand"],
allowedChanges: [],
},
);
});
test("blocks when a permitted removal is combined with other content changes", () => {
const published = snapshot({
brand: { name: "林境门作", config: { visualTemplateKey: "doors" } },
});
const current = snapshot({
brand: { name: "林境门作", config: {}, miniAppSettings: { appId: "wx-test" } },
});
const result = classifyContractRefresh(published, current, {
allowedRemovedKeys: ["brand.config.visualTemplateKey"],
});
assert.equal(result.status, "content-diverged");
assert.deepEqual(result.blockingKeys, ["brand"]);
});
+34 -1
View File
@@ -159,7 +159,40 @@ pnpm deploy:verify
脚本要求账号已完成初始密码修改,品牌发布检查全部通过,公开工作区已发布且至少有一项业务。凭据只从环境变量读取,不能写入仓库。
### 5. 小程序代码上传
### 5. 模板契约迁移后的发布快照刷新
`BrandRelease` 是公开工作区的唯一数据源,发布后内容不可变。模板包升级或兼容性声明修正不会自动改写历史发布,必须显式刷新快照,否则公开工作区会继续返回旧契约(例如旧的 `supportedIndustryTemplates`)。
先在生产 release 目录执行 dry-run:
```bash
node deploy/republish-stale-template-contracts.mjs
```
脚本逐品牌比较当前发布快照与数据库重建快照:
- `current`:无需处理;
- `contract-stale`:仅模板契约字段变化,可重发;
- `content-diverged`:品牌内容(`brand`、`offerings`、`forms`、`trustContents`、`capabilities` 等)与已发布快照不同,**禁止自动重发**,必须在 Admin 审查草稿后手动发布;
- `not-ready`:发布检查未通过,先修复阻断项。
确认输出后加 `--apply` 执行。历史遗留字段删除必须显式放行,不能默认忽略:
```bash
node deploy/republish-stale-template-contracts.mjs --apply \
--allow-removed-key=brand.config.visualTemplateKey
```
`--allow-removed-key` 只允许“旧值存在、新值缺失”的删除;该字段被改成其他值或与其他内容差异同时出现时仍会拦截。`--apply` 退出码为 1 表示至少一个品牌被拦截,应按上面的分类处理,不要重复盲目执行。
重发后验证公开契约:
```bash
curl -fsS "$API_BASE_URL/public/workspace?brandSlug=$BRAND_SLUG" |
jq '{publication, visualTemplate}'
```
### 6. 小程序代码上传
后台“配置与发布 → 小程序发布”会调用对应模板的小程序构建,并把产物上传到微信。构建产物根目录由 `MINIAPP_ARTIFACT_ROOT` 控制,相对路径按仓库根目录解析(不是 API 进程的工作目录),默认 `apps/taro/dist`;单个模板的产物固定为 `<root>/<template-package-key>/weapp`,缺少 `app.json` 即判定构建失败并保留构建日志。生产环境仍按 ADR 0023,优先在 CI 或专用发布 Worker 中构建,API 只负责上传。
+80
View File
@@ -26,6 +26,26 @@ export async function checkPackage(directory) {
.sort();
if (JSON.stringify(actual) !== JSON.stringify(expected))
throw new Error("Release file list mismatch");
const packagePath = path.join(directory, "package.json");
let releasePackage;
try {
releasePackage = JSON.parse(await readFile(packagePath, "utf8"));
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
const patchedDependencies = releasePackage?.pnpm?.patchedDependencies ?? {};
for (const [dependency, patchPath] of Object.entries(patchedDependencies)) {
if (
typeof patchPath !== "string" ||
path.isAbsolute(patchPath) ||
patchPath.split("/").includes("..")
)
throw new Error("Invalid patched dependency path: " + dependency);
if (!actual.includes(patchPath))
throw new Error(`Release is missing patched dependency ${dependency}: ${patchPath}`);
}
for (const file of manifest.files) {
if (file.path.startsWith("/") || file.path.split("/").includes(".."))
throw new Error("Unsafe release path");
@@ -34,6 +54,66 @@ export async function checkPackage(directory) {
if (content.byteLength !== file.bytes || digest !== file.sha256)
throw new Error("Release checksum mismatch: " + file.path);
}
const workspacePackages = new Map();
for (const relative of actual.filter(
(file) => file === "package.json" || file.endsWith("/package.json"),
)) {
const workspacePackage = JSON.parse(await readFile(path.join(directory, relative), "utf8"));
if (typeof workspacePackage.name !== "string" || !workspacePackage.name)
throw new Error("Workspace package has no name: " + relative);
workspacePackages.set(workspacePackage.name, {
directory: path.posix.dirname(relative),
manifest: workspacePackage,
});
}
for (const [name, workspacePackage] of workspacePackages) {
for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
for (const [dependency, range] of Object.entries(workspacePackage.manifest[section] ?? {})) {
if (typeof range !== "string" || !range.startsWith("workspace:")) continue;
const target = workspacePackages.get(dependency);
if (!target) {
throw new Error(
`Release is missing workspace dependency ${dependency} required by ${name}`,
);
}
if (target.directory === ".") {
throw new Error(`Workspace dependency ${dependency} cannot be the release root package`);
}
}
}
}
if (actual.includes("template-catalog.json")) {
const catalog = JSON.parse(
await readFile(path.join(directory, "template-catalog.json"), "utf8"),
);
if (catalog.formatVersion !== "1" || !Array.isArray(catalog.packages))
throw new Error("Invalid template catalog");
const keys = new Set();
for (const entry of catalog.packages) {
if (
typeof entry.packageKey !== "string" ||
typeof entry.version !== "string" ||
typeof entry.archiveChecksum !== "string" ||
typeof entry.archivePath !== "string"
)
throw new Error("Invalid template catalog entry");
if (keys.has(entry.packageKey))
throw new Error("Duplicate template package in catalog: " + entry.packageKey);
keys.add(entry.packageKey);
if (
path.isAbsolute(entry.archivePath) ||
entry.archivePath.split("/").includes("..") ||
!actual.includes(entry.archivePath)
)
throw new Error("Template archive is missing from release: " + entry.packageKey);
const digest = createHash("sha256")
.update(await readFile(path.join(directory, entry.archivePath)))
.digest("hex");
if (digest !== entry.archiveChecksum)
throw new Error("Template archive checksum mismatch: " + entry.packageKey);
}
}
return manifest;
}
+115 -8
View File
@@ -6,22 +6,27 @@ import path from "node:path";
import test from "node:test";
import { checkPackage } from "./check-package.mjs";
async function createPackage() {
async function createPackage(extraFiles = {}) {
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-release-"));
await mkdir(path.join(directory, "apps"), { recursive: true });
const content = Buffer.from("release fixture");
await writeFile(path.join(directory, "apps/api.js"), content);
const files = new Map([["apps/api.js", content]]);
for (const [relative, value] of Object.entries(extraFiles)) {
const fileContent = Buffer.isBuffer(value) ? value : Buffer.from(value);
await mkdir(path.dirname(path.join(directory, relative)), { recursive: true });
await writeFile(path.join(directory, relative), fileContent);
files.set(relative, fileContent);
}
await writeFile(
path.join(directory, "manifest.json"),
JSON.stringify({
version: "fixture-1",
files: [
{
path: "apps/api.js",
bytes: content.byteLength,
sha256: createHash("sha256").update(content).digest("hex"),
},
],
files: [...files].map(([filePath, fileContent]) => ({
path: filePath,
bytes: fileContent.byteLength,
sha256: createHash("sha256").update(fileContent).digest("hex"),
})),
}),
);
return directory;
@@ -56,3 +61,105 @@ test("release package checker rejects files missing from the manifest", async ()
await rm(directory, { recursive: true, force: true });
}
});
test("release package checker rejects patched dependencies missing from the package", async () => {
const directory = await createPackage({
"package.json": JSON.stringify({
name: "fixture-release",
pnpm: {
patchedDependencies: {
"example-package@1.0.0": "patches/example-package.patch",
},
},
}),
});
try {
await assert.rejects(checkPackage(directory), /missing patched dependency/);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("release package checker accepts a complete workspace dependency closure", async () => {
const directory = await createPackage({
"package.json": JSON.stringify({ name: "fixture-release" }),
"packages/api/package.json": JSON.stringify({
name: "@fixture/api",
dependencies: { "@fixture/contract": "workspace:^" },
}),
"packages/contract/package.json": JSON.stringify({
name: "@fixture/contract",
}),
});
try {
await checkPackage(directory);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("release package checker rejects a missing workspace dependency", async () => {
const directory = await createPackage({
"package.json": JSON.stringify({ name: "fixture-release" }),
"packages/api/package.json": JSON.stringify({
name: "@fixture/api",
dependencies: { "@fixture/contract": "workspace:^" },
}),
});
try {
await assert.rejects(
checkPackage(directory),
/missing workspace dependency @fixture\/contract/,
);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("release package checker accepts a valid template catalog", async () => {
const archive = Buffer.from("template archive");
const archiveChecksum = createHash("sha256").update(archive).digest("hex");
const archivePath = `template-artifacts/example/1.0.0/${archiveChecksum}.tar.gz`;
const directory = await createPackage({
[archivePath]: archive,
"template-catalog.json": JSON.stringify({
formatVersion: "1",
packages: [
{
packageKey: "example",
version: "1.0.0",
archiveChecksum,
archivePath,
},
],
}),
});
try {
await checkPackage(directory);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("release package checker rejects a template archive with a mismatched checksum", async () => {
const archivePath = "template-artifacts/example/1.0.0/archive.tar.gz";
const directory = await createPackage({
[archivePath]: "template archive",
"template-catalog.json": JSON.stringify({
formatVersion: "1",
packages: [
{
packageKey: "example",
version: "1.0.0",
archiveChecksum: "0".repeat(64),
archivePath,
},
],
}),
});
try {
await assert.rejects(checkPackage(directory), /template archive checksum mismatch/i);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
+90 -24
View File
@@ -1,11 +1,12 @@
import { createHash } from "node:crypto";
import { existsSync } from "node:fs";
import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
import { createRequire } from "node:module";
import { checkPackage } from "./check-package.mjs";
import { verifyRuntimePreflight } from "./runtime-preflight.mjs";
const require = createRequire(import.meta.url);
const { findLeaks, loadConfig } = require("../../apps/taro/config/mask-taro.cjs");
@@ -71,9 +72,13 @@ async function copyWorkspace(workspace) {
const target = path.join(output, workspace);
await mkdir(target, { recursive: true });
await cp(path.join(source, "package.json"), path.join(target, "package.json"));
await cp(path.join(source, "src"), path.join(target, "src"), { recursive: true });
await cp(path.join(source, "dist"), path.join(target, "dist"), { recursive: true });
await cp(path.join(source, "tsconfig.json"), path.join(target, "tsconfig.json"));
for (const directory of ["src", "dist"]) {
if (!existsSync(path.join(source, directory))) continue;
await cp(path.join(source, directory), path.join(target, directory), { recursive: true });
}
if (existsSync(path.join(source, "tsconfig.json"))) {
await cp(path.join(source, "tsconfig.json"), path.join(target, "tsconfig.json"));
}
if (workspace === "apps/api") {
await cp(path.join(source, "prisma/schema.prisma"), path.join(target, "prisma/schema.prisma"));
await cp(path.join(source, "prisma/migrations"), path.join(target, "prisma/migrations"), {
@@ -92,18 +97,85 @@ async function copyTaroWorkspace() {
await cp(path.join(source, "tsconfig.json"), path.join(target, "tsconfig.json"));
}
async function copyTemplatePackage(directoryName) {
const source = path.join(root, "packages", directoryName);
const target = path.join(output, "packages", directoryName);
await mkdir(target, { recursive: true });
await cp(path.join(source, "package.json"), path.join(target, "package.json"));
await cp(path.join(source, "template.json"), path.join(target, "template.json"));
await cp(path.join(source, "miniapp"), path.join(target, "miniapp"), { recursive: true });
await cp(path.join(source, "taro"), path.join(target, "taro"), { recursive: true });
await cp(path.join(source, "tsconfig.json"), path.join(target, "tsconfig.json"));
function sha256File(file) {
return readFile(file).then((content) => createHash("sha256").update(content).digest("hex"));
}
async function discoverTemplatePackages() {
const packages = [];
for (const entry of await readdir(path.join(root, "packages"), { withFileTypes: true })) {
const templateDirectory = path.join(root, "packages", entry.name);
if (
entry.isDirectory() &&
entry.name.startsWith("template-") &&
existsSync(path.join(templateDirectory, "template.json")) &&
existsSync(path.join(templateDirectory, "taro/index.tsx"))
) {
packages.push({
directoryName: entry.name,
manifest: JSON.parse(await readFile(path.join(templateDirectory, "template.json"), "utf8")),
});
}
}
return packages.sort((left, right) =>
left.manifest.packageKey.localeCompare(right.manifest.packageKey),
);
}
async function buildTemplateCatalog() {
const packedRoot = path.join(root, "dist/template-packages");
await rm(packedRoot, { recursive: true, force: true });
const packages = [];
for (const template of await discoverTemplatePackages()) {
const { packageKey, version } = template.manifest;
if (typeof packageKey !== "string" || typeof version !== "string")
throw new Error("Template manifest must declare packageKey and version");
run("node", ["scripts/template-pack.cjs", "--template", packageKey, "--out", packedRoot]);
const packedDirectory = path.join(packedRoot, `${packageKey}-${version}`);
const checksums = JSON.parse(
await readFile(path.join(packedDirectory, "checksums.json"), "utf8"),
);
const archiveSource = packedDirectory + ".tar.gz";
const archiveChecksum = await sha256File(archiveSource);
const archivePath = path.posix.join(
"template-artifacts",
packageKey,
version,
archiveChecksum + ".tar.gz",
);
const archiveTarget = path.join(output, archivePath);
await mkdir(path.dirname(archiveTarget), { recursive: true });
await cp(archiveSource, archiveTarget);
const target = path.join(output, "packages", template.directoryName);
await cp(packedDirectory, target, { recursive: true });
packages.push({
packageKey,
version,
displayName: template.manifest.displayName,
supportedIndustryTemplates: template.manifest.supportedIndustryTemplates,
manifest: template.manifest,
validationReport: {
formatVersion: "1",
errors: [],
fileCount: checksums.files.length,
extractedBytes: checksums.files.reduce((total, file) => total + file.bytes, 0),
files: checksums.files,
},
contentChecksum: checksums.contentChecksum,
archiveChecksum,
archivePath,
});
}
await writeFile(
path.join(output, "template-catalog.json"),
JSON.stringify({ formatVersion: "1", packages }, null, 2) + "\n",
);
return packages;
}
async function main() {
if (Number(process.versions.node.split(".")[0]) !== 24)
throw new Error("Node.js 24 is required to build the release");
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,100}$/.test(version))
throw new Error("Invalid release version");
const adminDist = path.join(root, "apps/admin/dist");
@@ -119,9 +191,11 @@ async function main() {
]) {
await cp(path.join(root, file), path.join(output, file));
}
await cp(path.join(root, "patches"), path.join(output, "patches"), { recursive: true });
for (const workspace of [
"apps/api",
"packages/config",
"packages/template-contract",
"packages/types",
"packages/validation",
]) {
@@ -129,17 +203,8 @@ async function main() {
}
await copyTaroWorkspace();
await cp(adminDist, path.join(output, "apps/admin/dist"), { recursive: true });
for (const entry of await readdir(path.join(root, "packages"), { withFileTypes: true })) {
const templateDirectory = path.join(root, "packages", entry.name);
if (
entry.isDirectory() &&
entry.name.startsWith("template-") &&
existsSync(path.join(templateDirectory, "template.json")) &&
existsSync(path.join(templateDirectory, "taro/index.tsx"))
) {
await copyTemplatePackage(entry.name);
}
}
const templateCatalog = await buildTemplateCatalog();
if (!templateCatalog.length) throw new Error("Release contains no template package");
await cp(path.join(root, "apps/api/prisma/assets"), path.join(output, "seed-media"), {
recursive: true,
});
@@ -183,6 +248,7 @@ async function main() {
}
await writeFile(path.join(output, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
await checkPackage(output);
await verifyRuntimePreflight(output);
run("tar", ["-czf", archive, "-C", output, "."]);
const checksum = createHash("sha256")
.update(await readFile(archive))
+57
View File
@@ -0,0 +1,57 @@
import { cp, mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
/**
* 在临时目录中验证发布包的运行时依赖闭包。
* 冻结安装只能证明锁文件一致,不能证明打包时没有遗漏 workspace package。
*/
export async function verifyRuntimePreflight(releaseDirectory) {
const temporary = await mkdtemp(path.join(os.tmpdir(), "personal-brand-runtime-"));
const apiDirectory = path.join(temporary, "apps/api");
try {
await cp(releaseDirectory, temporary, { recursive: true });
run(
"pnpm",
[
"--filter",
"@personal-brand/api...",
"--filter",
"@personal-brand/taro...",
"--filter",
"@personal-brand/template-acheng-campus-food",
"--filter",
"@personal-brand/template-linjing-editorial",
"--filter",
"@personal-brand/template-atelier-solopreneur",
"install",
"--frozen-lockfile",
"--prefer-offline",
"--ignore-scripts",
],
temporary,
);
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"], temporary);
run(
process.execPath,
["--input-type=module", "-e", "await import('./dist/main.js')"],
apiDirectory,
{ NODE_ENV: "test" },
);
} finally {
await rm(temporary, { recursive: true, force: true });
}
}
function run(command, args, cwd, extraEnvironment = {}) {
const result = spawnSync(command, args, {
cwd,
stdio: "inherit",
env: { ...process.env, ...extraEnvironment },
});
if (result.status !== 0)
throw new Error(
`${command} failed during release runtime preflight with exit ${result.status}`,
);
}