devElectronAppBundle.mjs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import { access, cp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
  2. import { dirname, join } from "node:path";
  3. export const DEV_ELECTRON_PROTOCOL_SCHEME = "zcode";
  4. export const DEV_ELECTRON_APP_NAME = "ZCode Dev";
  5. export const DEV_ELECTRON_APP_BUNDLE_ID = "dev.zcode.app.development";
  6. // 副本布局版本,见 prepareDevElectronAppBundle 中的指纹说明。
  7. export const DEV_ELECTRON_BUNDLE_FORMAT = 2;
  8. function escapeXml(value) {
  9. return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll('"', "&quot;");
  10. }
  11. function replacePlistString(plist, key, value) {
  12. const pattern = new RegExp(`(<key>${key}</key>\\s*<string>)[^<]*(</string>)`, "u");
  13. if (!pattern.test(plist)) {
  14. throw new Error(`Dev Electron Info.plist is missing ${key}`);
  15. }
  16. return plist.replace(
  17. pattern,
  18. (_match, prefix, suffix) => `${prefix}${escapeXml(value)}${suffix}`,
  19. );
  20. }
  21. function appendProtocolDeclaration(plist) {
  22. if (plist.includes(`<string>${DEV_ELECTRON_PROTOCOL_SCHEME}</string>`)) {
  23. return plist;
  24. }
  25. const closingDictIndex = plist.lastIndexOf("</dict>");
  26. if (closingDictIndex < 0) {
  27. throw new Error("Dev Electron Info.plist is missing its root dict");
  28. }
  29. const protocolDeclaration = `\n\t<key>CFBundleURLTypes</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>CFBundleURLName</key>\n\t\t\t<string>${DEV_ELECTRON_APP_NAME}</string>\n\t\t\t<key>CFBundleURLSchemes</key>\n\t\t\t<array>\n\t\t\t\t<string>${DEV_ELECTRON_PROTOCOL_SCHEME}</string>\n\t\t\t</array>\n\t\t</dict>\n\t</array>\n`;
  30. return `${plist.slice(0, closingDictIndex)}${protocolDeclaration}${plist.slice(closingDictIndex)}`;
  31. }
  32. /**
  33. * 为 macOS 本地 Dev runtime 写入产品身份和 zcode URL scheme。
  34. * raw Electron 的 Info.plist 没有 CFBundleURLTypes,系统只能把 zcode 交给
  35. * com.github.Electron;这里仅修改启动副本,避免污染 node_modules 中的 Electron。
  36. */
  37. export function patchDevElectronInfoPlist(plist) {
  38. let patched = replacePlistString(plist, "CFBundleDisplayName", DEV_ELECTRON_APP_NAME);
  39. patched = replacePlistString(patched, "CFBundleIdentifier", DEV_ELECTRON_APP_BUNDLE_ID);
  40. patched = replacePlistString(patched, "CFBundleName", DEV_ELECTRON_APP_NAME);
  41. return appendProtocolDeclaration(patched);
  42. }
  43. export function resolveDevElectronAppBundlePath({ runtimeRoot, electronVersion, arch }) {
  44. return join(runtimeRoot, `${electronVersion}-${arch}`, `${DEV_ELECTRON_APP_NAME}.app`);
  45. }
  46. export async function prepareDevElectronAppBundle({
  47. electronAppPath,
  48. runtimeRoot,
  49. electronVersion,
  50. arch,
  51. }) {
  52. const appPath = resolveDevElectronAppBundlePath({ runtimeRoot, electronVersion, arch });
  53. const infoPlistPath = join(appPath, "Contents", "Info.plist");
  54. const sourceExecutablePath = join(electronAppPath, "Contents", "MacOS", "Electron");
  55. const existingExecutablePath = join(appPath, "Contents", "MacOS", "Electron");
  56. // 源二进制的身份指纹,写在 .app 外面:放进 Contents 会污染 bundle 结构。
  57. const sourceStampPath = join(dirname(appPath), ".zcode-dev-electron-source.json");
  58. // 这里原本把两个 Electron 可执行文件(各 ~100MB+)整份读进内存做 equals,
  59. // 每次 dev 启动都要付一次全量读盘。源二进制由 npm 包解压产出,记录它的 size+mtime
  60. // 即可判定是否需要重拷,语义等价而开销是常数级。
  61. //
  62. // 不直接比较「源与副本」的 mtime:cp 即使开 preserveTimestamps 也会把 mtime
  63. // 四舍五入到毫秒,源的亚毫秒精度必然丢失,两边永远不相等 —— 那等于没有缓存。
  64. //
  65. // format 字段记录副本的布局版本:布局修复(例如符号链接策略变更)时递增,
  66. // 让已存在的旧副本在源二进制没变的情况下也能被判定为需要重拷。
  67. const sourceStats = await stat(sourceExecutablePath).catch(() => undefined);
  68. const sourceStamp = sourceStats
  69. ? JSON.stringify({
  70. format: DEV_ELECTRON_BUNDLE_FORMAT,
  71. size: sourceStats.size,
  72. mtimeMs: sourceStats.mtimeMs,
  73. })
  74. : undefined;
  75. let needsCopy = true;
  76. try {
  77. const existingInfoPlist = await readFile(infoPlistPath, "utf8");
  78. await access(existingExecutablePath);
  79. const existingStamp = await readFile(sourceStampPath, "utf8");
  80. needsCopy =
  81. !existingInfoPlist.includes(`<string>${DEV_ELECTRON_APP_BUNDLE_ID}</string>`) ||
  82. !existingInfoPlist.includes(`<string>${DEV_ELECTRON_PROTOCOL_SCHEME}</string>`) ||
  83. sourceStamp === undefined ||
  84. existingStamp !== sourceStamp;
  85. } catch {
  86. // 目录不存在、来源不是本工具生成的 bundle,下面走一次完整复制。
  87. }
  88. if (needsCopy) {
  89. // 只删除本次生成的 ignored runtime 目录,绝不触碰 node_modules 或用户数据。
  90. await rm(appPath, { recursive: true, force: true });
  91. await rm(sourceStampPath, { force: true });
  92. await mkdir(dirname(appPath), { recursive: true });
  93. // verbatimSymlinks 必须开:Electron Framework.framework 内部靠相对符号链接
  94. // (Resources -> Versions/Current/Resources、Current -> A)组织。fs.cp 默认会把
  95. // 相对链接改写成指向 node_modules 的绝对路径,主进程仍能读到,但 GPU / network
  96. // 等 macOS 沙箱子进程只允许读本 bundle 目录,顺链接出去会被拦,表现为
  97. // "icudtl.dat not found in bundle" 然后 "GPU process isn't usable. Goodbye."。
  98. await cp(electronAppPath, appPath, { recursive: true, verbatimSymlinks: true });
  99. const patchedInfoPlist = patchDevElectronInfoPlist(await readFile(infoPlistPath, "utf8"));
  100. await writeFile(infoPlistPath, patchedInfoPlist, "utf8");
  101. // 指纹最后写:中途失败时下次仍会判定为需要重拷,不会留下半成品缓存。
  102. if (sourceStamp !== undefined) await writeFile(sourceStampPath, sourceStamp, "utf8");
  103. }
  104. return {
  105. appPath,
  106. executablePath: join(appPath, "Contents", "MacOS", "Electron"),
  107. };
  108. }