packaged-sourcemap-cleanup.mjs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import {
  2. existsSync,
  3. mkdirSync,
  4. mkdtempSync,
  5. readdirSync,
  6. readFileSync,
  7. rmSync,
  8. statSync,
  9. unlinkSync,
  10. writeFileSync,
  11. } from "node:fs";
  12. import { tmpdir } from "node:os";
  13. import { extname, resolve } from "node:path";
  14. const SOURCEMAP_REFERENCE_EXTENSIONS = new Set([".js", ".cjs", ".mjs", ".css"]);
  15. // 只清理位于行首的 sourceMappingURL 注释。压缩后的 bundle 可能在模板字符串里内嵌
  16. // 这段文本(例如内嵌 TypeScript 编译器的 emitter 源码),行中匹配会把该行剩余内容整段
  17. // 吞掉,直接产出语法损坏的产物;真实的 sourcemap 注释总是由构建工具单独成行输出。
  18. const SOURCE_MAPPING_URL_LINE_RE = /(?:^|\r?\n)[ \t]*\/\/[#@][ \t]*sourceMappingURL=[^\r\n]*/g;
  19. const SOURCE_MAPPING_URL_BLOCK_RE =
  20. /(?:^|\r?\n)[ \t]*\/\*[#@][ \t]*sourceMappingURL=[\s\S]*?\*\/[ \t]*/g;
  21. export function stripSourceMappingUrlComments(source) {
  22. return source.replace(SOURCE_MAPPING_URL_LINE_RE, "").replace(SOURCE_MAPPING_URL_BLOCK_RE, "");
  23. }
  24. function walkFiles(rootDir, visitor) {
  25. if (!existsSync(rootDir)) {
  26. return;
  27. }
  28. for (const entry of readdirSync(rootDir)) {
  29. const entryPath = resolve(rootDir, entry);
  30. const stat = statSync(entryPath);
  31. if (stat.isDirectory()) {
  32. walkFiles(entryPath, visitor);
  33. continue;
  34. }
  35. if (stat.isFile()) {
  36. visitor(entryPath);
  37. }
  38. }
  39. }
  40. export function stripSourceMappingUrlCommentsInDirectory(rootDir) {
  41. const summary = { filesChanged: 0, referencesRemoved: 0 };
  42. walkFiles(rootDir, (filePath) => {
  43. if (!SOURCEMAP_REFERENCE_EXTENSIONS.has(extname(filePath))) {
  44. return;
  45. }
  46. const source = readFileSync(filePath, "utf8");
  47. const lineReferenceCount = source.match(SOURCE_MAPPING_URL_LINE_RE)?.length ?? 0;
  48. const blockReferenceCount = source.match(SOURCE_MAPPING_URL_BLOCK_RE)?.length ?? 0;
  49. const referencesRemoved = lineReferenceCount + blockReferenceCount;
  50. if (referencesRemoved === 0) {
  51. return;
  52. }
  53. writeFileSync(filePath, stripSourceMappingUrlComments(source));
  54. summary.filesChanged += 1;
  55. summary.referencesRemoved += referencesRemoved;
  56. });
  57. return summary;
  58. }
  59. export function removeSourceMapFilesInDirectory(rootDir) {
  60. const summary = { filesRemoved: 0 };
  61. walkFiles(rootDir, (filePath) => {
  62. if (extname(filePath) !== ".map") {
  63. return;
  64. }
  65. unlinkSync(filePath);
  66. summary.filesRemoved += 1;
  67. });
  68. return summary;
  69. }
  70. export async function cleanupPackagedSourcemaps({
  71. appAsarPath,
  72. resourcesDir,
  73. runAsarCommand,
  74. runTimedSync,
  75. runTimedAsync,
  76. resolveUnpackDirs,
  77. replaceAppAsarFromStaging,
  78. pruneStagingDirectory = null,
  79. logger = console,
  80. }) {
  81. if (existsSync(appAsarPath)) {
  82. mkdirSync(tmpdir(), { recursive: true });
  83. const stagingDir = mkdtempSync(resolve(tmpdir(), "zcode-app-asar-sourcemap-"));
  84. try {
  85. runTimedSync("afterPack:sourcemap-cleanup:asar-extract", () =>
  86. runAsarCommand(["extract", appAsarPath, stagingDir]),
  87. );
  88. const stripSummary = stripSourceMappingUrlCommentsInDirectory(stagingDir);
  89. const mapSummary = removeSourceMapFilesInDirectory(stagingDir);
  90. const pruneSummary = pruneStagingDirectory ? await pruneStagingDirectory(stagingDir) : null;
  91. if (
  92. stripSummary.referencesRemoved > 0 ||
  93. mapSummary.filesRemoved > 0 ||
  94. (pruneSummary?.packagesRemoved ?? 0) > 0
  95. ) {
  96. if (pruneSummary?.packagesRemoved > 0) {
  97. logger.log(
  98. `[afterPack] removed incompatible platform packages count=${pruneSummary.packagesRemoved}: ${pruneSummary.removedNames.join(", ")}`,
  99. );
  100. }
  101. logger.log(
  102. `[afterPack] stripped sourceMappingURL references=${stripSummary.referencesRemoved} files=${stripSummary.filesChanged} maps=${mapSummary.filesRemoved}`,
  103. );
  104. await runTimedAsync("afterPack:sourcemap-cleanup:asar-pack", () =>
  105. replaceAppAsarFromStaging({
  106. sourceDir: stagingDir,
  107. appAsarPath,
  108. // 重写前取 unpack 布局快照,避免这次重写丢掉 electron-builder 或
  109. // afterPack 注入阶段已经确定的 unpack 结果。
  110. unpackDirs: resolveUnpackDirs ? resolveUnpackDirs(appAsarPath) : [],
  111. }),
  112. );
  113. } else {
  114. logger.log("[afterPack] app.asar sourcemap cleanup found no references");
  115. }
  116. } finally {
  117. rmSync(stagingDir, { force: true, recursive: true });
  118. }
  119. }
  120. const stripSummary = stripSourceMappingUrlCommentsInDirectory(resourcesDir);
  121. const mapSummary = removeSourceMapFilesInDirectory(resourcesDir);
  122. logger.log(
  123. `[afterPack] resources sourcemap cleanup references=${stripSummary.referencesRemoved} files=${stripSummary.filesChanged} maps=${mapSummary.filesRemoved}`,
  124. );
  125. }