1use anyhow::{anyhow, bail, Context, Result};
2use async_compression::futures::bufread::GzipDecoder;
3use async_tar::Archive;
4use futures::lock::Mutex;
5use futures::{future::Shared, FutureExt};
6use gpui::{executor::Background, Task};
7use serde::Deserialize;
8use smol::{fs, io::BufReader, process::Command};
9use std::process::Output;
10use std::{
11 env::consts,
12 path::{Path, PathBuf},
13 sync::{Arc, OnceLock},
14};
15use util::{http::HttpClient, ResultExt};
16
17const VERSION: &str = "v18.15.0";
18
19static RUNTIME_INSTANCE: OnceLock<Arc<NodeRuntime>> = OnceLock::new();
20
21#[derive(Debug, Deserialize)]
22#[serde(rename_all = "kebab-case")]
23pub struct NpmInfo {
24 #[serde(default)]
25 dist_tags: NpmInfoDistTags,
26 versions: Vec<String>,
27}
28
29#[derive(Debug, Deserialize, Default)]
30pub struct NpmInfoDistTags {
31 latest: Option<String>,
32}
33
34pub struct NodeRuntime {
35 http: Arc<dyn HttpClient>,
36 background: Arc<Background>,
37 installation_path: Mutex<Option<Shared<Task<Result<PathBuf, Arc<anyhow::Error>>>>>>,
38}
39
40impl NodeRuntime {
41 pub fn instance(http: Arc<dyn HttpClient>, background: Arc<Background>) -> Arc<NodeRuntime> {
42 RUNTIME_INSTANCE
43 .get_or_init(|| {
44 Arc::new(NodeRuntime {
45 http,
46 background,
47 installation_path: Mutex::new(None),
48 })
49 })
50 .clone()
51 }
52
53 pub async fn binary_path(&self) -> Result<PathBuf> {
54 let installation_path = self.install_if_needed().await?;
55 Ok(installation_path.join("bin/node"))
56 }
57
58 pub async fn run_npm_subcommand(
59 &self,
60 directory: Option<&Path>,
61 subcommand: &str,
62 args: &[&str],
63 ) -> Result<Output> {
64 let attempt = |installation_path: PathBuf| async move {
65 let node_binary = installation_path.join("bin/node");
66 let npm_file = installation_path.join("bin/npm");
67
68 if smol::fs::metadata(&node_binary).await.is_err() {
69 return Err(anyhow!("missing node binary file"));
70 }
71
72 if smol::fs::metadata(&npm_file).await.is_err() {
73 return Err(anyhow!("missing npm file"));
74 }
75
76 let mut command = Command::new(node_binary);
77 command.arg(npm_file).arg(subcommand).args(args);
78
79 if let Some(directory) = directory {
80 command.current_dir(directory);
81 }
82
83 command.output().await.map_err(|e| anyhow!("{e}"))
84 };
85
86 let installation_path = self.install_if_needed().await?;
87 let mut output = attempt(installation_path).await;
88 if output.is_err() {
89 let installation_path = self.reinstall().await?;
90 output = attempt(installation_path).await;
91 if output.is_err() {
92 return Err(anyhow!(
93 "failed to launch npm subcommand {subcommand} subcommand"
94 ));
95 }
96 }
97
98 if let Ok(output) = &output {
99 if !output.status.success() {
100 return Err(anyhow!(
101 "failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
102 String::from_utf8_lossy(&output.stdout),
103 String::from_utf8_lossy(&output.stderr)
104 ));
105 }
106 }
107
108 output.map_err(|e| anyhow!("{e}"))
109 }
110
111 pub async fn npm_package_latest_version(&self, name: &str) -> Result<String> {
112 let output = self
113 .run_npm_subcommand(
114 None,
115 "info",
116 &[
117 name,
118 "--json",
119 "-fetch-retry-mintimeout",
120 "2000",
121 "-fetch-retry-maxtimeout",
122 "5000",
123 "-fetch-timeout",
124 "5000",
125 ],
126 )
127 .await?;
128
129 let mut info: NpmInfo = serde_json::from_slice(&output.stdout)?;
130 info.dist_tags
131 .latest
132 .or_else(|| info.versions.pop())
133 .ok_or_else(|| anyhow!("no version found for npm package {}", name))
134 }
135
136 pub async fn npm_install_packages(
137 &self,
138 directory: &Path,
139 packages: impl IntoIterator<Item = (&str, &str)>,
140 ) -> Result<()> {
141 let packages: Vec<_> = packages
142 .into_iter()
143 .map(|(name, version)| format!("{name}@{version}"))
144 .collect();
145
146 let mut arguments: Vec<_> = packages.iter().map(|p| p.as_str()).collect();
147 arguments.extend_from_slice(&[
148 "-fetch-retry-mintimeout",
149 "2000",
150 "-fetch-retry-maxtimeout",
151 "5000",
152 "-fetch-timeout",
153 "5000",
154 ]);
155
156 self.run_npm_subcommand(Some(directory), "install", &arguments)
157 .await?;
158 Ok(())
159 }
160
161 async fn reinstall(&self) -> Result<PathBuf> {
162 log::info!("beginnning to reinstall Node runtime");
163 let mut installation_path = self.installation_path.lock().await;
164
165 if let Some(task) = installation_path.as_ref().cloned() {
166 if let Ok(installation_path) = task.await {
167 smol::fs::remove_dir_all(&installation_path)
168 .await
169 .context("node dir removal")
170 .log_err();
171 }
172 }
173
174 let http = self.http.clone();
175 let task = self
176 .background
177 .spawn(async move { Self::install(http).await.map_err(Arc::new) })
178 .shared();
179
180 *installation_path = Some(task.clone());
181 task.await.map_err(|e| anyhow!("{}", e))
182 }
183
184 async fn install_if_needed(&self) -> Result<PathBuf> {
185 let task = self
186 .installation_path
187 .lock()
188 .await
189 .get_or_insert_with(|| {
190 let http = self.http.clone();
191 self.background
192 .spawn(async move { Self::install(http).await.map_err(Arc::new) })
193 .shared()
194 })
195 .clone();
196
197 task.await.map_err(|e| anyhow!("{}", e))
198 }
199
200 async fn install(http: Arc<dyn HttpClient>) -> Result<PathBuf> {
201 log::info!("installing Node runtime");
202 let arch = match consts::ARCH {
203 "x86_64" => "x64",
204 "aarch64" => "arm64",
205 other => bail!("Running on unsupported platform: {other}"),
206 };
207
208 let folder_name = format!("node-{VERSION}-darwin-{arch}");
209 let node_containing_dir = util::paths::SUPPORT_DIR.join("node");
210 let node_dir = node_containing_dir.join(folder_name);
211 let node_binary = node_dir.join("bin/node");
212
213 if fs::metadata(&node_binary).await.is_err() {
214 _ = fs::remove_dir_all(&node_containing_dir).await;
215 fs::create_dir(&node_containing_dir)
216 .await
217 .context("error creating node containing dir")?;
218
219 let file_name = format!("node-{VERSION}-darwin-{arch}.tar.gz");
220 let url = format!("https://nodejs.org/dist/{VERSION}/{file_name}");
221 let mut response = http
222 .get(&url, Default::default(), true)
223 .await
224 .context("error downloading Node binary tarball")?;
225
226 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
227 let archive = Archive::new(decompressed_bytes);
228 archive.unpack(&node_containing_dir).await?;
229 }
230
231 anyhow::Ok(node_dir)
232 }
233}