import { createHash } from "node:crypto"; import { cp, mkdir, readFile, readdir, 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"; const require = createRequire(import.meta.url); const { findLeaks, loadConfig } = require("../../apps/taro/config/mask-taro.cjs"); const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); const timestamp = new Date().toISOString().replace(/\D/g, "").slice(0, 14); const git = spawnSync("git", ["rev-parse", "--short=12", "HEAD"], { cwd: root, encoding: "utf8" }); if (git.status !== 0) throw new Error("Cannot determine source revision"); const revision = git.stdout.trim(); const version = process.env.RELEASE_VERSION ?? timestamp + "-" + revision; const output = path.join(root, "dist/releases", version); const archive = path.join(root, "dist/releases", "personal-brand-" + version + ".tar.gz"); function run(command, args) { const result = spawnSync(command, args, { cwd: root, stdio: "inherit" }); if (result.status !== 0) process.exit(result.status ?? 1); } /** 发布产物对外可下载,出现框架指纹即视为发布配置错误。 */ function assertNoStackFingerprint(directory) { const config = loadConfig(); if (!config.enabled) return; const leaks = findLeaks(path.join(root, directory), config); if (!leaks.length) return; throw new Error( `${directory} 仍含技术栈指纹,请通过包内构建脚本产出:\n` + leaks .slice(0, 10) .map((leak) => " - " + leak) .join("\n"), ); } async function listFiles(directory, prefix = "") { const files = []; for (const entry of await readdir(directory, { withFileTypes: true })) { const relative = path.posix.join(prefix, entry.name); if (entry.isDirectory()) files.push(...(await listFiles(path.join(directory, entry.name), relative))); else if (entry.isFile()) files.push(relative); else throw new Error("Unsupported release file: " + relative); } return files.sort(); } async function verifyStaticEntry(dist, entry, prefix) { const html = await readFile(path.join(dist, entry), "utf8"); for (const match of html.matchAll(/(?:src|href)=["']([^"']+)["']/g)) { const reference = match[1]; if (!/\.(?:js|css)(?:[?#]|$)/.test(reference)) continue; const url = new URL(reference, "https://release.invalid" + prefix); if (url.origin !== "https://release.invalid" || !url.pathname.startsWith(prefix)) { throw new Error("Invalid static base path in " + entry + ": " + reference); } const relative = decodeURIComponent(url.pathname.slice(prefix.length)); const base = entry === "index.html" ? dist : path.join(dist, "template-preview"); await readFile(path.join(base, relative)); } } async function copyWorkspace(workspace) { const source = path.join(root, 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")); 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"), { recursive: true, }); } } async function main() { 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"); await verifyStaticEntry(adminDist, "index.html", "/admin/"); await verifyStaticEntry(adminDist, "template-preview/index.html", "/template-preview/"); await mkdir(path.dirname(output), { recursive: true }); await mkdir(output, { recursive: false }); for (const file of [ "package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "tsconfig.base.json", ]) { await cp(path.join(root, file), path.join(output, file)); } for (const workspace of [ "apps/api", "packages/config", "packages/types", "packages/validation", ]) { await copyWorkspace(workspace); } await cp(adminDist, path.join(output, "apps/admin/dist"), { recursive: true }); await cp(path.join(root, "apps/api/prisma/assets"), path.join(output, "seed-media"), { recursive: true, }); await cp(path.join(root, "deploy"), path.join(output, "deploy"), { recursive: true }); for (const file of ["check-package.mjs", "verify-public-release.mjs"]) { await mkdir(path.join(output, "scripts/deploy"), { recursive: true }); await cp(path.join(root, "scripts/deploy", file), path.join(output, "scripts/deploy", file)); } const validationPath = path.join(output, "packages/validation/package.json"); const validation = JSON.parse(await readFile(validationPath, "utf8")); validation.exports["."].import = "./dist/index.js"; validation.exports["."].types = "./dist/index.d.ts"; await writeFile(validationPath, JSON.stringify(validation, null, 2) + "\n"); const schemaPath = path.join(output, "apps/api/prisma/schema.prisma"); const schema = await readFile(schemaPath, "utf8"); await writeFile( schemaPath, schema.replace(/binaryTargets\s*=\s*\[[^\]]*\]/, 'binaryTargets = ["native"]'), ); const status = spawnSync("git", ["status", "--porcelain"], { cwd: root, encoding: "utf8" }); if (status.status !== 0) throw new Error("Cannot determine working tree state"); const manifest = { version, revision, dirty: Boolean(status.stdout.trim()), createdAt: new Date().toISOString(), nodeMajor: 24, packageManager: "pnpm@9.15.0", files: [], }; for (const file of await listFiles(output)) { if (/(?:^|\/)\.env(?:\.|$)/.test(file) && !file.endsWith(".example")) { throw new Error("Refusing to package environment file: " + file); } const content = await readFile(path.join(output, file)); manifest.files.push({ path: file, bytes: content.byteLength, sha256: createHash("sha256").update(content).digest("hex"), }); } await writeFile(path.join(output, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n"); await checkPackage(output); run("tar", ["-czf", archive, "-C", output, "."]); const checksum = createHash("sha256") .update(await readFile(archive)) .digest("hex"); await writeFile(archive + ".sha256", checksum + " " + path.basename(archive) + "\n"); console.log("release: " + version); console.log("files: " + manifest.files.length); console.log("archive: " + path.relative(root, archive)); console.log("checksum: " + path.relative(root, archive + ".sha256")); } run("pnpm", ["build:admin:preview"]); assertNoStackFingerprint("apps/admin/dist"); run("pnpm", ["--filter", "@personal-brand/config", "build"]); run("pnpm", ["--filter", "@personal-brand/types", "build"]); run("pnpm", ["--filter", "@personal-brand/validation", "build"]); run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"]); run("pnpm", ["--filter", "@personal-brand/api", "build"]); await main();