| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- import { createReadStream } from "node:fs"
- import { readdir, readFile } from "node:fs/promises"
- import { createHash } from "node:crypto"
- import { join } from "node:path"
- export type RuntimeRelease = { protocol: number; revision: string }
- export async function runtimeRelease(): Promise<RuntimeRelease> {
- const release = JSON.parse(await readFile(new URL("../runtime-release.json", import.meta.url), "utf8"))
- if (release.protocol !== 1 || !/^[a-f0-9]{40}$/.test(release.revision)) throw new Error("运行组件版本清单无效。")
- return release
- }
- export async function runtimeFiles(root: string) {
- const result: Record<string, string> = {}
- const visit = async (relative: string) => {
- for (const entry of await readdir(join(root, relative), { withFileTypes: true })) {
- const name = relative ? `${relative}/${entry.name}` : entry.name
- if (name === "desktop-runtime.json") continue
- if (entry.isDirectory()) {
- await visit(name)
- continue
- }
- if (!entry.isFile()) throw new Error(`运行组件包含非普通文件:${name}`)
- const hash = createHash("sha256")
- for await (const chunk of createReadStream(join(root, name))) hash.update(chunk)
- result[name] = hash.digest("hex")
- }
- }
- await visit("")
- return Object.fromEntries(Object.entries(result).sort(([a], [b]) => a.localeCompare(b)))
- }
- export async function validateRuntimeBundle(root: string, release?: RuntimeRelease) {
- const manifest = JSON.parse(await readFile(join(root, "desktop-runtime.json"), "utf8"))
- if (manifest.protocol !== 1 || manifest.platform !== process.platform || manifest.arch !== process.arch)
- throw new Error("本地运行组件与打包平台或协议不匹配。")
- const binary = process.platform === "win32" ? "agentpaas.exe" : "agentpaas"
- const files = await runtimeFiles(root)
- if (!manifest.files || !files[binary] || JSON.stringify(files) !== JSON.stringify(manifest.files))
- throw new Error("本地运行组件文件校验失败,请重新准备运行组件。")
- if (release) {
- const info = JSON.parse(await readFile(join(root, "build-info.json"), "utf8"))
- if (
- info.git_revision !== release.revision ||
- info.dirty !== false ||
- info.desktop_protocol !== release.protocol ||
- info.platform !== manifest.platform ||
- info.arch !== manifest.arch
- )
- throw new Error(`本地运行组件版本不匹配或源码未提交,请使用 ${release.revision} 重新构建。`)
- }
- return manifest
- }
|