install.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. var __create = Object.create;
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __getProtoOf = Object.getPrototypeOf;
  6. var __hasOwnProp = Object.prototype.hasOwnProperty;
  7. var __copyProps = (to, from, except, desc) => {
  8. if (from && typeof from === "object" || typeof from === "function") {
  9. for (let key of __getOwnPropNames(from))
  10. if (!__hasOwnProp.call(to, key) && key !== except)
  11. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  12. }
  13. return to;
  14. };
  15. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  16. // If the importer is in node compatibility mode or this is not an ESM
  17. // file that has been converted to a CommonJS file using a Babel-
  18. // compatible transform (i.e. "__esModule" has not been set), then set
  19. // "default" to the CommonJS "module.exports" for node compatibility.
  20. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  21. mod
  22. ));
  23. // npm/lib/node-platform.ts
  24. var import_os = __toESM(require("os"));
  25. var import_path = __toESM(require("path"));
  26. var knownPackages = {
  27. "darwin arm64 LE": "@cloudflare/workerd-darwin-arm64",
  28. "darwin x64 LE": "@cloudflare/workerd-darwin-64",
  29. "linux arm64 LE": "@cloudflare/workerd-linux-arm64",
  30. "linux x64 LE": "@cloudflare/workerd-linux-64",
  31. "win32 x64 LE": "@cloudflare/workerd-windows-64"
  32. };
  33. var maybeExeExtension = process.platform === "win32" ? ".exe" : "";
  34. function pkgAndSubpathForCurrentPlatform() {
  35. let pkg;
  36. let subpath;
  37. let platformKey = `${process.platform} ${import_os.default.arch()} ${import_os.default.endianness()}`;
  38. if (platformKey in knownPackages) {
  39. pkg = knownPackages[platformKey];
  40. subpath = `bin/workerd${maybeExeExtension}`;
  41. } else {
  42. throw new Error(`Unsupported platform: ${platformKey}`);
  43. }
  44. return { pkg, subpath };
  45. }
  46. function downloadedBinPath(pkg, subpath) {
  47. const libDir = import_path.default.dirname(require.resolve("workerd"));
  48. return import_path.default.join(libDir, `downloaded-${pkg.replace("/", "-")}-${import_path.default.basename(subpath)}${maybeExeExtension}`);
  49. }
  50. // npm/lib/node-install.ts
  51. var import_fs = __toESM(require("fs"));
  52. var import_os2 = __toESM(require("os"));
  53. var import_path2 = __toESM(require("path"));
  54. var import_zlib = __toESM(require("zlib"));
  55. var import_https = __toESM(require("https"));
  56. var import_child_process = __toESM(require("child_process"));
  57. var toPath = import_path2.default.join(__dirname, "bin", "workerd");
  58. var isToPathJS = true;
  59. function validateBinaryVersion(...command) {
  60. command.push("--version");
  61. let stdout;
  62. try {
  63. stdout = import_child_process.default.execFileSync(command.shift(), command, {
  64. // Without this, this install script strangely crashes with the error
  65. // "EACCES: permission denied, write" but only on Ubuntu Linux when node is
  66. // installed from the Snap Store. This is not a problem when you download
  67. // the official version of node. The problem appears to be that stderr
  68. // (i.e. file descriptor 2) isn't writable?
  69. //
  70. // More info:
  71. // - https://snapcraft.io/ (what the Snap Store is)
  72. // - https://nodejs.org/dist/ (download the official version of node)
  73. // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035
  74. //
  75. stdio: [
  76. /* stdin */
  77. "pipe",
  78. /* stdout */
  79. "pipe",
  80. /* stderr */
  81. "inherit"
  82. ]
  83. }).toString().trim();
  84. } catch (e) {
  85. let msg = `[workerd] Failed to validate workerd binary
  86. Local development will not work. This usually means you're on an unsupported
  87. operating system, or missing some shared libraries.`;
  88. if (process.platform === "linux") {
  89. msg += " On Debian-based systems,\nmake sure you've installed the `libc++1` package.";
  90. }
  91. console.error(msg);
  92. return;
  93. }
  94. if (stdout !== `workerd ${"2023-08-14"}`) {
  95. throw new Error(
  96. `Expected ${JSON.stringify(
  97. "2023-08-14"
  98. )} but got ${JSON.stringify(stdout)}`
  99. );
  100. }
  101. }
  102. function isYarn() {
  103. const { npm_config_user_agent } = process.env;
  104. if (npm_config_user_agent) {
  105. return /\byarn\//.test(npm_config_user_agent);
  106. }
  107. return false;
  108. }
  109. function fetch(url) {
  110. return new Promise((resolve, reject) => {
  111. import_https.default.get(url, (res) => {
  112. if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location)
  113. return fetch(res.headers.location).then(resolve, reject);
  114. if (res.statusCode !== 200)
  115. return reject(new Error(`Server responded with ${res.statusCode}`));
  116. let chunks = [];
  117. res.on("data", (chunk) => chunks.push(chunk));
  118. res.on("end", () => resolve(Buffer.concat(chunks)));
  119. }).on("error", reject);
  120. });
  121. }
  122. function extractFileFromTarGzip(buffer, subpath) {
  123. try {
  124. buffer = import_zlib.default.unzipSync(buffer);
  125. } catch (err) {
  126. throw new Error(
  127. `Invalid gzip data in archive: ${err && err.message || err}`
  128. );
  129. }
  130. let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, "");
  131. let offset = 0;
  132. subpath = `package/${subpath}`;
  133. while (offset < buffer.length) {
  134. let name = str(offset, 100);
  135. let size = parseInt(str(offset + 124, 12), 8);
  136. offset += 512;
  137. if (!isNaN(size)) {
  138. if (name === subpath)
  139. return buffer.subarray(offset, offset + size);
  140. offset += size + 511 & ~511;
  141. }
  142. }
  143. throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`);
  144. }
  145. function installUsingNPM(pkg, subpath, binPath) {
  146. const env = { ...process.env, npm_config_global: void 0 };
  147. const libDir = import_path2.default.dirname(require.resolve("workerd"));
  148. const installDir = import_path2.default.join(libDir, "npm-install");
  149. import_fs.default.mkdirSync(installDir);
  150. try {
  151. import_fs.default.writeFileSync(import_path2.default.join(installDir, "package.json"), "{}");
  152. import_child_process.default.execSync(
  153. `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${"1.20230814.1"}`,
  154. { cwd: installDir, stdio: "pipe", env }
  155. );
  156. const installedBinPath = import_path2.default.join(
  157. installDir,
  158. "node_modules",
  159. pkg,
  160. subpath
  161. );
  162. import_fs.default.renameSync(installedBinPath, binPath);
  163. } finally {
  164. try {
  165. removeRecursive(installDir);
  166. } catch {
  167. }
  168. }
  169. }
  170. function removeRecursive(dir) {
  171. for (const entry of import_fs.default.readdirSync(dir)) {
  172. const entryPath = import_path2.default.join(dir, entry);
  173. let stats;
  174. try {
  175. stats = import_fs.default.lstatSync(entryPath);
  176. } catch {
  177. continue;
  178. }
  179. if (stats.isDirectory())
  180. removeRecursive(entryPath);
  181. else
  182. import_fs.default.unlinkSync(entryPath);
  183. }
  184. import_fs.default.rmdirSync(dir);
  185. }
  186. function maybeOptimizePackage(binPath) {
  187. if (import_os2.default.platform() !== "win32" && !isYarn()) {
  188. const tempPath = import_path2.default.join(__dirname, "bin-workerd");
  189. try {
  190. import_fs.default.linkSync(binPath, tempPath);
  191. import_fs.default.renameSync(tempPath, toPath);
  192. isToPathJS = false;
  193. import_fs.default.unlinkSync(tempPath);
  194. } catch {
  195. }
  196. }
  197. }
  198. async function downloadDirectlyFromNPM(pkg, subpath, binPath) {
  199. const unscopedPkg = pkg.substring(pkg.indexOf("/") + 1);
  200. const url = `https://registry.npmjs.org/${pkg}/-/${unscopedPkg}-${"1.20230814.1"}.tgz`;
  201. console.error(`[workerd] Trying to download ${JSON.stringify(url)}`);
  202. try {
  203. import_fs.default.writeFileSync(
  204. binPath,
  205. extractFileFromTarGzip(await fetch(url), subpath)
  206. );
  207. import_fs.default.chmodSync(binPath, 493);
  208. } catch (e) {
  209. console.error(
  210. `[workerd] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`
  211. );
  212. throw e;
  213. }
  214. }
  215. async function checkAndPreparePackage() {
  216. const { pkg, subpath } = pkgAndSubpathForCurrentPlatform();
  217. let binPath;
  218. try {
  219. binPath = require.resolve(`${pkg}/${subpath}`);
  220. } catch (e) {
  221. console.error(`[workerd] Failed to find package "${pkg}" on the file system
  222. This can happen if you use the "--no-optional" flag. The "optionalDependencies"
  223. package.json feature is used by workerd to install the correct binary executable
  224. for your current platform. This install script will now attempt to work around
  225. this. If that fails, you need to remove the "--no-optional" flag to use workerd.
  226. `);
  227. binPath = downloadedBinPath(pkg, subpath);
  228. try {
  229. console.error(`[workerd] Trying to install package "${pkg}" using npm`);
  230. installUsingNPM(pkg, subpath, binPath);
  231. } catch (e2) {
  232. console.error(
  233. `[workerd] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`
  234. );
  235. try {
  236. await downloadDirectlyFromNPM(pkg, subpath, binPath);
  237. } catch (e3) {
  238. throw new Error(`Failed to install package "${pkg}"`);
  239. }
  240. }
  241. }
  242. maybeOptimizePackage(binPath);
  243. }
  244. checkAndPreparePackage().then(() => {
  245. if (isToPathJS) {
  246. validateBinaryVersion(process.execPath, toPath);
  247. } else {
  248. validateBinaryVersion(toPath);
  249. }
  250. });