runtime-bundle.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { createReadStream } from "node:fs"
  2. import { readdir, readFile } from "node:fs/promises"
  3. import { createHash } from "node:crypto"
  4. import { join } from "node:path"
  5. export async function runtimeFiles(root: string) {
  6. const result: Record<string, string> = {}
  7. const visit = async (relative: string) => {
  8. for (const entry of await readdir(join(root, relative), { withFileTypes: true })) {
  9. const name = relative ? `${relative}/${entry.name}` : entry.name
  10. if (name === "desktop-runtime.json") continue
  11. if (entry.isDirectory()) {
  12. await visit(name)
  13. continue
  14. }
  15. if (!entry.isFile()) throw new Error(`运行组件包含非普通文件:${name}`)
  16. const hash = createHash("sha256")
  17. for await (const chunk of createReadStream(join(root, name))) hash.update(chunk)
  18. result[name] = hash.digest("hex")
  19. }
  20. }
  21. await visit("")
  22. return Object.fromEntries(Object.entries(result).sort(([a], [b]) => a.localeCompare(b)))
  23. }
  24. export async function validateRuntimeBundle(root: string) {
  25. const manifest = JSON.parse(await readFile(join(root, "desktop-runtime.json"), "utf8"))
  26. if (manifest.protocol !== 1 || manifest.platform !== process.platform || manifest.arch !== process.arch)
  27. throw new Error("本地运行组件与打包平台或协议不匹配。")
  28. const binary = process.platform === "win32" ? "agentpaas.exe" : "agentpaas"
  29. const files = await runtimeFiles(root)
  30. if (!manifest.files || !files[binary] || JSON.stringify(files) !== JSON.stringify(manifest.files))
  31. throw new Error("本地运行组件文件校验失败,请重新准备运行组件。")
  32. return manifest
  33. }