sea-node-download.mjs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import { spawnSync } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { existsSync, createWriteStream } from "node:fs";
  4. import { mkdir, readFile, rename, rm } from "node:fs/promises";
  5. import { dirname, resolve } from "node:path";
  6. import { Readable } from "node:stream";
  7. import { pipeline } from "node:stream/promises";
  8. import { nodeReleaseArtifact, targetParts } from "./sea-targets.mjs";
  9. const commandText = (command, args) => [command, ...args].join(" ");
  10. const run = (command, args, options = {}) => {
  11. const result = spawnSync(command, args, {
  12. encoding: "utf8",
  13. stdio: "inherit",
  14. ...options,
  15. });
  16. if (result.error) {
  17. throw new Error(`${commandText(command, args)} failed: ${result.error.message}`, {
  18. cause: result.error,
  19. });
  20. }
  21. if (result.status !== 0) {
  22. throw new Error(`${commandText(command, args)} failed`);
  23. }
  24. };
  25. const sha256File = async (file) => {
  26. const hash = createHash("sha256");
  27. hash.update(await readFile(file));
  28. return hash.digest("hex");
  29. };
  30. const formatBytes = (bytes) => `${(bytes / 1024 / 1024).toFixed(1)} MiB`;
  31. export const downloadFile = async (url, destination) => {
  32. console.log(`[sea] downloading ${url}`);
  33. const response = await fetch(url, {
  34. redirect: "follow",
  35. });
  36. if (!response.ok || !response.body) {
  37. throw new Error(`Failed to download ${url}: HTTP ${response.status}`);
  38. }
  39. await mkdir(dirname(destination), {
  40. recursive: true,
  41. });
  42. const tempDestination = `${destination}.download`;
  43. await rm(tempDestination, {
  44. force: true,
  45. });
  46. const contentLength = Number(response.headers.get("content-length") ?? 0);
  47. let received = 0;
  48. let lastProgressAt = Date.now();
  49. const body = Readable.fromWeb(response.body);
  50. body.on("data", (chunk) => {
  51. received += chunk.length;
  52. const now = Date.now();
  53. if (now - lastProgressAt < 5_000) return;
  54. lastProgressAt = now;
  55. const total = contentLength > 0 ? ` / ${formatBytes(contentLength)}` : "";
  56. console.log(`[sea] downloaded ${formatBytes(received)}${total}`);
  57. });
  58. try {
  59. await pipeline(body, createWriteStream(tempDestination));
  60. await rename(tempDestination, destination);
  61. } catch (error) {
  62. await rm(tempDestination, {
  63. force: true,
  64. });
  65. throw error;
  66. }
  67. };
  68. const shasumsPath = (nodeCache, nodeVersion) =>
  69. resolve(nodeCache, `v${nodeVersion}`, "SHASUMS256.txt");
  70. const ensureShasums = async ({ nodeCache, nodeVersion }) => {
  71. const destination = shasumsPath(nodeCache, nodeVersion);
  72. if (!existsSync(destination)) {
  73. await downloadFile(`https://nodejs.org/dist/v${nodeVersion}/SHASUMS256.txt`, destination);
  74. }
  75. return readFile(destination, "utf8");
  76. };
  77. const expectedSha256 = (shasums, artifact) => {
  78. for (const line of shasums.split(/\r?\n/)) {
  79. const [hash, name] = line.trim().split(/\s+/);
  80. if (name === artifact) return hash;
  81. }
  82. throw new Error(`Could not find ${artifact} in Node.js SHASUMS256.txt`);
  83. };
  84. const ensureDownloadedArtifact = async ({ artifact, destination, nodeCache, nodeVersion }) => {
  85. const shasums = await ensureShasums({ nodeCache, nodeVersion });
  86. const expected = expectedSha256(shasums, artifact);
  87. if (existsSync(destination)) {
  88. const actual = await sha256File(destination);
  89. if (actual === expected) return;
  90. console.log(`[sea] cached ${artifact} checksum mismatch; downloading again`);
  91. await rm(destination, {
  92. force: true,
  93. });
  94. }
  95. await downloadFile(
  96. new URL(artifact, `https://nodejs.org/dist/v${nodeVersion}/`).href,
  97. destination,
  98. );
  99. const actual = await sha256File(destination);
  100. if (actual !== expected) {
  101. throw new Error(`Checksum mismatch for ${artifact}: expected ${expected}, received ${actual}`);
  102. }
  103. };
  104. const releaseArchiveRoot = (target, nodeVersion) => {
  105. const { arch, releasePlatform } = targetParts(target);
  106. return `node-v${nodeVersion}-${releasePlatform}-${arch}`;
  107. };
  108. const ensureExtractedNode = async ({ archivePath, extractRoot, nodeVersion, target }) => {
  109. const nodePath = resolve(extractRoot, releaseArchiveRoot(target, nodeVersion), "bin", "node");
  110. if (existsSync(nodePath)) return nodePath;
  111. await rm(extractRoot, {
  112. force: true,
  113. recursive: true,
  114. });
  115. await mkdir(extractRoot, {
  116. recursive: true,
  117. });
  118. try {
  119. run("tar", ["-xf", archivePath, "-C", extractRoot]);
  120. } catch (error) {
  121. throw new Error(
  122. `Could not extract ${archivePath}. Install tar/xz support or pass --node-binary ${target}=/abs/path/node.`,
  123. {
  124. cause: error,
  125. },
  126. );
  127. }
  128. if (!existsSync(nodePath)) {
  129. throw new Error(`Extracted Node.js archive did not contain ${nodePath}`);
  130. }
  131. return nodePath;
  132. };
  133. export const resolveDownloadedNodeBinary = async ({ nodeCache, nodeVersion, target }) => {
  134. const artifact = nodeReleaseArtifact(target, nodeVersion);
  135. const artifactPath = resolve(nodeCache, `v${nodeVersion}`, artifact);
  136. await ensureDownloadedArtifact({
  137. artifact,
  138. destination: artifactPath,
  139. nodeCache,
  140. nodeVersion,
  141. });
  142. const { releasePlatform } = targetParts(target);
  143. if (releasePlatform === "win") return artifactPath;
  144. return ensureExtractedNode({
  145. archivePath: artifactPath,
  146. extractRoot: resolve(nodeCache, `v${nodeVersion}`, target),
  147. nodeVersion,
  148. target,
  149. });
  150. };