sea-workspace-package-assets.mjs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { createHash } from "node:crypto";
  2. import { mkdir, readFile, writeFile } from "node:fs/promises";
  3. import { dirname, resolve } from "node:path";
  4. function compiledEntry(value) {
  5. if (typeof value === "string") {
  6. if (!value.startsWith("./src/")) return value;
  7. const path = value.replace(/^\.\/src\//, "./dist/");
  8. if (/\.d\.[cm]?ts$/.test(path)) return path;
  9. return path
  10. .replace(/\.tsx?$/, ".js")
  11. .replace(/\.mts$/, ".mjs")
  12. .replace(/\.cts$/, ".cjs");
  13. }
  14. if (Array.isArray(value)) return value.map(compiledEntry);
  15. if (value && typeof value === "object") {
  16. return Object.fromEntries(
  17. Object.entries(value).map(([key, entry]) => [key, compiledEntry(entry)]),
  18. );
  19. }
  20. return value;
  21. }
  22. export async function stageSeaPackageAssets({
  23. packageFiles,
  24. workspacePackage,
  25. stagingDirectory,
  26. assetPrefix,
  27. }) {
  28. const files = [];
  29. const assets = {};
  30. for (const file of packageFiles) {
  31. let sourcePath = file.sourcePath;
  32. let bytes = await readFile(sourcePath);
  33. if (workspacePackage && file.assetPath.endsWith("/package.json")) {
  34. const manifest = JSON.parse(bytes.toString("utf8"));
  35. // 根 workspace 为开发环境导出 src/*.ts;SEA 仅携带 dist,必须在暂存副本改写入口。
  36. // 不修改源码 manifest,否则会影响桌面 esbuild 的源码解析路径。
  37. for (const field of ["exports", "main", "module", "types", "imports"]) {
  38. if (field in manifest) manifest[field] = compiledEntry(manifest[field]);
  39. }
  40. bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
  41. sourcePath = resolve(stagingDirectory, file.assetPath);
  42. await mkdir(dirname(sourcePath), { recursive: true });
  43. await writeFile(sourcePath, bytes);
  44. }
  45. assets[`${assetPrefix}${file.assetPath}`] = sourcePath;
  46. files.push({
  47. mode: /\.(?:dll|dylib|node|so)$/i.test(file.assetPath) ? 0o755 : 0o644,
  48. path: file.assetPath,
  49. sha256: createHash("sha256").update(bytes).digest("hex"),
  50. });
  51. }
  52. return { files, assets };
  53. }