node_runtime.rs

  1use anyhow::{Context as _, Result, anyhow, bail};
  2use async_compression::futures::bufread::GzipDecoder;
  3use async_tar::Archive;
  4use futures::{AsyncReadExt, FutureExt as _, channel::oneshot, future::Shared};
  5use http_client::{Host, HttpClient, Url};
  6use log::Level;
  7use semver::Version;
  8use serde::Deserialize;
  9use smol::io::BufReader;
 10use smol::{fs, lock::Mutex};
 11use std::collections::HashMap;
 12use std::fmt::Display;
 13use std::{
 14    env::{self, consts},
 15    ffi::OsString,
 16    io,
 17    net::{IpAddr, Ipv4Addr},
 18    path::{Path, PathBuf},
 19    process::Output,
 20    sync::Arc,
 21};
 22use util::ResultExt;
 23use util::archive::extract_zip;
 24
 25const NODE_CA_CERTS_ENV_VAR: &str = "NODE_EXTRA_CA_CERTS";
 26
 27#[derive(Clone, Debug, Default, Eq, PartialEq)]
 28pub struct NodeBinaryOptions {
 29    pub allow_path_lookup: bool,
 30    pub allow_binary_download: bool,
 31    pub use_paths: Option<(PathBuf, PathBuf)>,
 32}
 33
 34/// Use this when you need to launch npm as a long-lived process (for example, an agent server),
 35/// so the invocation and environment stay consistent with the Node runtime's proxy and CA setup.
 36#[derive(Clone, Debug)]
 37pub struct NpmCommand {
 38    pub path: PathBuf,
 39    pub args: Vec<String>,
 40    pub env: HashMap<String, String>,
 41}
 42
 43pub enum VersionStrategy<'a> {
 44    /// Install if current version doesn't match pinned version
 45    Pin(&'a Version),
 46    /// Install if current version is older than latest version
 47    Latest(&'a Version),
 48}
 49
 50#[derive(Clone)]
 51pub struct NodeRuntime(Arc<Mutex<NodeRuntimeState>>);
 52
 53struct NodeRuntimeState {
 54    http: Arc<dyn HttpClient>,
 55    instance: Option<Box<dyn NodeRuntimeTrait>>,
 56    last_options: Option<NodeBinaryOptions>,
 57    options: watch::Receiver<Option<NodeBinaryOptions>>,
 58    shell_env_loaded: Shared<oneshot::Receiver<()>>,
 59}
 60
 61impl NodeRuntime {
 62    pub fn new(
 63        http: Arc<dyn HttpClient>,
 64        shell_env_loaded: Option<oneshot::Receiver<()>>,
 65        options: watch::Receiver<Option<NodeBinaryOptions>>,
 66    ) -> Self {
 67        NodeRuntime(Arc::new(Mutex::new(NodeRuntimeState {
 68            http,
 69            instance: None,
 70            last_options: None,
 71            options,
 72            shell_env_loaded: shell_env_loaded.unwrap_or(oneshot::channel().1).shared(),
 73        })))
 74    }
 75
 76    pub fn unavailable() -> Self {
 77        NodeRuntime(Arc::new(Mutex::new(NodeRuntimeState {
 78            http: Arc::new(http_client::BlockedHttpClient),
 79            instance: None,
 80            last_options: None,
 81            options: watch::channel(Some(NodeBinaryOptions::default())).1,
 82            shell_env_loaded: oneshot::channel().1.shared(),
 83        })))
 84    }
 85
 86    async fn instance(&self) -> Box<dyn NodeRuntimeTrait> {
 87        let mut state = self.0.lock().await;
 88
 89        let options = loop {
 90            if let Some(options) = state.options.borrow().as_ref() {
 91                break options.clone();
 92            }
 93            match state.options.changed().await {
 94                Ok(()) => {}
 95                // failure case not cached
 96                Err(err) => {
 97                    return Box::new(UnavailableNodeRuntime {
 98                        error_message: err.to_string().into(),
 99                    }) as Box<dyn NodeRuntimeTrait>;
100                }
101            }
102        };
103
104        if state.last_options.as_ref() != Some(&options) {
105            state.instance.take();
106        }
107        if let Some(instance) = state.instance.as_ref() {
108            return instance.boxed_clone();
109        }
110
111        if let Some((node, npm)) = options.use_paths.as_ref() {
112            let instance = match SystemNodeRuntime::new(node.clone(), npm.clone()).await {
113                Ok(instance) => {
114                    log::info!("using Node.js from `node.path` in settings: {:?}", instance);
115                    Box::new(instance)
116                }
117                Err(err) => {
118                    // failure case not cached, since it's cheap to check again
119                    return Box::new(UnavailableNodeRuntime {
120                        error_message: format!(
121                            "failure checking Node.js from `node.path` in settings ({}): {:?}",
122                            node.display(),
123                            err
124                        )
125                        .into(),
126                    });
127                }
128            };
129            state.instance = Some(instance.boxed_clone());
130            state.last_options = Some(options);
131            return instance;
132        }
133
134        let system_node_error = if options.allow_path_lookup {
135            state.shell_env_loaded.clone().await.ok();
136            match SystemNodeRuntime::detect().await {
137                Ok(instance) => {
138                    log::info!("using Node.js found on PATH: {:?}", instance);
139                    state.instance = Some(instance.boxed_clone());
140                    state.last_options = Some(options);
141                    return Box::new(instance) as Box<dyn NodeRuntimeTrait>;
142                }
143                Err(err) => Some(err),
144            }
145        } else {
146            None
147        };
148
149        let instance = if options.allow_binary_download {
150            let (log_level, why_using_managed) = match system_node_error {
151                Some(err @ DetectError::Other(_)) => (Level::Warn, err.to_string()),
152                Some(err @ DetectError::NotInPath(_)) => (Level::Info, err.to_string()),
153                None => (
154                    Level::Info,
155                    "`node.ignore_system_version` is `true` in settings".to_string(),
156                ),
157            };
158            match ManagedNodeRuntime::install_if_needed(&state.http).await {
159                Ok(instance) => {
160                    log::log!(
161                        log_level,
162                        "using Zed managed Node.js at {} since {}",
163                        instance.installation_path.display(),
164                        why_using_managed
165                    );
166                    Box::new(instance) as Box<dyn NodeRuntimeTrait>
167                }
168                Err(err) => {
169                    // failure case is cached, since downloading + installing may be expensive. The
170                    // downside of this is that it may fail due to an intermittent network issue.
171                    //
172                    // TODO: Have `install_if_needed` indicate which failure cases are retryable
173                    // and/or have shared tracking of when internet is available.
174                    Box::new(UnavailableNodeRuntime {
175                        error_message: format!(
176                            "failure while downloading and/or installing Zed managed Node.js, \
177                            restart Zed to retry: {}",
178                            err
179                        )
180                        .into(),
181                    }) as Box<dyn NodeRuntimeTrait>
182                }
183            }
184        } else if let Some(system_node_error) = system_node_error {
185            // failure case not cached, since it's cheap to check again
186            //
187            // TODO: When support is added for setting `options.allow_binary_download`, update this
188            // error message.
189            return Box::new(UnavailableNodeRuntime {
190                error_message: format!(
191                    "failure while checking system Node.js from PATH: {}",
192                    system_node_error
193                )
194                .into(),
195            });
196        } else {
197            // failure case is cached because it will always happen with these options
198            //
199            // TODO: When support is added for setting `options.allow_binary_download`, update this
200            // error message.
201            Box::new(UnavailableNodeRuntime {
202                error_message: "`node` settings do not allow any way to use Node.js"
203                    .to_string()
204                    .into(),
205            })
206        };
207
208        state.instance = Some(instance.boxed_clone());
209        state.last_options = Some(options);
210        instance
211    }
212
213    pub async fn binary_path(&self) -> Result<PathBuf> {
214        self.instance().await.binary_path()
215    }
216
217    pub async fn run_npm_subcommand(
218        &self,
219        directory: Option<&Path>,
220        subcommand: &str,
221        args: &[&str],
222    ) -> Result<Output> {
223        let http = self.0.lock().await.http.clone();
224        self.instance()
225            .await
226            .run_npm_subcommand(directory, http.proxy(), subcommand, args)
227            .await
228    }
229
230    pub async fn npm_package_installed_version(
231        &self,
232        local_package_directory: &Path,
233        name: &str,
234    ) -> Result<Option<Version>> {
235        self.instance()
236            .await
237            .npm_package_installed_version(local_package_directory, name)
238            .await
239    }
240
241    pub async fn npm_command(&self, subcommand: &str, args: &[&str]) -> Result<NpmCommand> {
242        let http = self.0.lock().await.http.clone();
243        self.instance()
244            .await
245            .npm_command(http.proxy(), subcommand, args)
246            .await
247    }
248
249    pub async fn npm_package_latest_version(&self, name: &str) -> Result<Version> {
250        let http = self.0.lock().await.http.clone();
251        let output = self
252            .instance()
253            .await
254            .run_npm_subcommand(
255                None,
256                http.proxy(),
257                "info",
258                &[
259                    name,
260                    "--json",
261                    "--fetch-retry-mintimeout",
262                    "2000",
263                    "--fetch-retry-maxtimeout",
264                    "5000",
265                    "--fetch-timeout",
266                    "5000",
267                ],
268            )
269            .await?;
270
271        let mut info: NpmInfo = serde_json::from_slice(&output.stdout)?;
272        info.dist_tags
273            .latest
274            .or_else(|| info.versions.pop())
275            .with_context(|| format!("no version found for npm package {name}"))
276    }
277
278    pub async fn npm_install_packages(
279        &self,
280        directory: &Path,
281        packages: &[(&str, &str)],
282    ) -> Result<()> {
283        if packages.is_empty() {
284            return Ok(());
285        }
286
287        let packages: Vec<_> = packages
288            .iter()
289            .map(|(name, version)| format!("{name}@{version}"))
290            .collect();
291
292        let arguments: Vec<_> = packages
293            .iter()
294            .map(|p| p.as_str())
295            .chain([
296                "--save-exact",
297                "--fetch-retry-mintimeout",
298                "2000",
299                "--fetch-retry-maxtimeout",
300                "5000",
301                "--fetch-timeout",
302                "5000",
303            ])
304            .collect();
305
306        // This is also wrong because the directory is wrong.
307        self.run_npm_subcommand(Some(directory), "install", &arguments)
308            .await?;
309        Ok(())
310    }
311
312    pub async fn should_install_npm_package(
313        &self,
314        package_name: &str,
315        local_executable_path: &Path,
316        local_package_directory: &Path,
317        version_strategy: VersionStrategy<'_>,
318    ) -> bool {
319        // In the case of the local system not having the package installed,
320        // or in the instances where we fail to parse package.json data,
321        // we attempt to install the package.
322        if fs::metadata(local_executable_path).await.is_err() {
323            return true;
324        }
325
326        let Some(installed_version) = self
327            .npm_package_installed_version(local_package_directory, package_name)
328            .await
329            .log_err()
330            .flatten()
331        else {
332            return true;
333        };
334
335        match version_strategy {
336            VersionStrategy::Pin(pinned_version) => &installed_version != pinned_version,
337            VersionStrategy::Latest(latest_version) => &installed_version < latest_version,
338        }
339    }
340}
341
342enum ArchiveType {
343    TarGz,
344    Zip,
345}
346
347#[derive(Debug, Deserialize)]
348#[serde(rename_all = "kebab-case")]
349pub struct NpmInfo {
350    #[serde(default)]
351    dist_tags: NpmInfoDistTags,
352    versions: Vec<Version>,
353}
354
355#[derive(Debug, Deserialize, Default)]
356pub struct NpmInfoDistTags {
357    latest: Option<Version>,
358}
359
360#[async_trait::async_trait]
361trait NodeRuntimeTrait: Send + Sync {
362    fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait>;
363    fn binary_path(&self) -> Result<PathBuf>;
364
365    async fn run_npm_subcommand(
366        &self,
367        directory: Option<&Path>,
368        proxy: Option<&Url>,
369        subcommand: &str,
370        args: &[&str],
371    ) -> Result<Output>;
372
373    async fn npm_command(
374        &self,
375        proxy: Option<&Url>,
376        subcommand: &str,
377        args: &[&str],
378    ) -> Result<NpmCommand>;
379
380    async fn npm_package_installed_version(
381        &self,
382        local_package_directory: &Path,
383        name: &str,
384    ) -> Result<Option<Version>>;
385}
386
387#[derive(Clone)]
388struct ManagedNodeRuntime {
389    installation_path: PathBuf,
390}
391
392impl ManagedNodeRuntime {
393    const VERSION: &str = "v24.11.0";
394
395    #[cfg(not(windows))]
396    const NODE_PATH: &str = "bin/node";
397    #[cfg(windows)]
398    const NODE_PATH: &str = "node.exe";
399
400    #[cfg(not(windows))]
401    const NPM_PATH: &str = "bin/npm";
402    #[cfg(windows)]
403    const NPM_PATH: &str = "node_modules/npm/bin/npm-cli.js";
404
405    async fn install_if_needed(http: &Arc<dyn HttpClient>) -> Result<Self> {
406        log::info!("Node runtime install_if_needed");
407
408        let os = match consts::OS {
409            "macos" => "darwin",
410            "linux" => "linux",
411            "windows" => "win",
412            other => bail!("Running on unsupported os: {other}"),
413        };
414
415        let arch = match consts::ARCH {
416            "x86_64" => "x64",
417            "aarch64" => "arm64",
418            other => bail!("Running on unsupported architecture: {other}"),
419        };
420
421        let version = Self::VERSION;
422        let folder_name = format!("node-{version}-{os}-{arch}");
423        let node_containing_dir = paths::data_dir().join("node");
424        let node_dir = node_containing_dir.join(folder_name);
425        let node_binary = node_dir.join(Self::NODE_PATH);
426        let npm_file = node_dir.join(Self::NPM_PATH);
427        let node_ca_certs = env::var(NODE_CA_CERTS_ENV_VAR).unwrap_or_else(|_| String::new());
428
429        let valid = if fs::metadata(&node_binary).await.is_ok() {
430            let result = util::command::new_smol_command(&node_binary)
431                .env(NODE_CA_CERTS_ENV_VAR, node_ca_certs)
432                .arg(npm_file)
433                .arg("--version")
434                .args(["--cache".into(), node_dir.join("cache")])
435                .args(["--userconfig".into(), node_dir.join("blank_user_npmrc")])
436                .args(["--globalconfig".into(), node_dir.join("blank_global_npmrc")])
437                .output()
438                .await;
439            match result {
440                Ok(output) => {
441                    if output.status.success() {
442                        true
443                    } else {
444                        log::warn!(
445                            "Zed managed Node.js binary at {} failed check with output: {:?}",
446                            node_binary.display(),
447                            output
448                        );
449                        false
450                    }
451                }
452                Err(err) => {
453                    log::warn!(
454                        "Zed managed Node.js binary at {} failed check, so re-downloading it. \
455                        Error: {}",
456                        node_binary.display(),
457                        err
458                    );
459                    false
460                }
461            }
462        } else {
463            false
464        };
465
466        if !valid {
467            _ = fs::remove_dir_all(&node_containing_dir).await;
468            fs::create_dir(&node_containing_dir)
469                .await
470                .context("error creating node containing dir")?;
471
472            let archive_type = match consts::OS {
473                "macos" | "linux" => ArchiveType::TarGz,
474                "windows" => ArchiveType::Zip,
475                other => bail!("Running on unsupported os: {other}"),
476            };
477
478            let version = Self::VERSION;
479            let file_name = format!(
480                "node-{version}-{os}-{arch}.{extension}",
481                extension = match archive_type {
482                    ArchiveType::TarGz => "tar.gz",
483                    ArchiveType::Zip => "zip",
484                }
485            );
486
487            let url = format!("https://nodejs.org/dist/{version}/{file_name}");
488            log::info!("Downloading Node.js binary from {url}");
489            let mut response = http
490                .get(&url, Default::default(), true)
491                .await
492                .context("error downloading Node binary tarball")?;
493            log::info!("Download of Node.js complete, extracting...");
494
495            let body = response.body_mut();
496            match archive_type {
497                ArchiveType::TarGz => {
498                    let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
499                    let archive = Archive::new(decompressed_bytes);
500                    archive.unpack(&node_containing_dir).await?;
501                }
502                ArchiveType::Zip => extract_zip(&node_containing_dir, body).await?,
503            }
504            log::info!("Extracted Node.js to {}", node_containing_dir.display())
505        }
506
507        // Note: Not in the `if !valid {}` so we can populate these for existing installations
508        _ = fs::create_dir(node_dir.join("cache")).await;
509        _ = fs::write(node_dir.join("blank_user_npmrc"), []).await;
510        _ = fs::write(node_dir.join("blank_global_npmrc"), []).await;
511
512        anyhow::Ok(ManagedNodeRuntime {
513            installation_path: node_dir,
514        })
515    }
516}
517
518fn path_with_node_binary_prepended(node_binary: &Path) -> Option<OsString> {
519    let existing_path = env::var_os("PATH");
520    let node_bin_dir = node_binary.parent().map(|dir| dir.as_os_str());
521    match (existing_path, node_bin_dir) {
522        (Some(existing_path), Some(node_bin_dir)) => {
523            if let Ok(joined) = env::join_paths(
524                [PathBuf::from(node_bin_dir)]
525                    .into_iter()
526                    .chain(env::split_paths(&existing_path)),
527            ) {
528                Some(joined)
529            } else {
530                Some(existing_path)
531            }
532        }
533        (Some(existing_path), None) => Some(existing_path),
534        (None, Some(node_bin_dir)) => Some(node_bin_dir.to_owned()),
535        _ => None,
536    }
537}
538
539#[async_trait::async_trait]
540impl NodeRuntimeTrait for ManagedNodeRuntime {
541    fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
542        Box::new(self.clone())
543    }
544
545    fn binary_path(&self) -> Result<PathBuf> {
546        Ok(self.installation_path.join(Self::NODE_PATH))
547    }
548
549    async fn run_npm_subcommand(
550        &self,
551        directory: Option<&Path>,
552        proxy: Option<&Url>,
553        subcommand: &str,
554        args: &[&str],
555    ) -> Result<Output> {
556        let attempt = || async {
557            let npm_command = self.npm_command(proxy, subcommand, args).await?;
558            let mut command = util::command::new_smol_command(npm_command.path);
559            command.args(npm_command.args);
560            command.envs(npm_command.env);
561            configure_npm_command(&mut command, directory);
562            command.output().await.map_err(|e| anyhow!("{e}"))
563        };
564
565        let mut output = attempt().await;
566        if output.is_err() {
567            output = attempt().await;
568            anyhow::ensure!(
569                output.is_ok(),
570                "failed to launch npm subcommand {subcommand} subcommand\nerr: {:?}",
571                output.err()
572            );
573        }
574
575        if let Ok(output) = &output {
576            anyhow::ensure!(
577                output.status.success(),
578                "failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
579                String::from_utf8_lossy(&output.stdout),
580                String::from_utf8_lossy(&output.stderr)
581            );
582        }
583
584        output.map_err(|e| anyhow!("{e}"))
585    }
586
587    async fn npm_command(
588        &self,
589        proxy: Option<&Url>,
590        subcommand: &str,
591        args: &[&str],
592    ) -> Result<NpmCommand> {
593        let node_binary = self.installation_path.join(Self::NODE_PATH);
594        let npm_file = self.installation_path.join(Self::NPM_PATH);
595
596        anyhow::ensure!(
597            smol::fs::metadata(&node_binary).await.is_ok(),
598            "missing node binary file"
599        );
600        anyhow::ensure!(
601            smol::fs::metadata(&npm_file).await.is_ok(),
602            "missing npm file"
603        );
604
605        let command_args = build_npm_command_args(
606            Some(&npm_file),
607            &self.installation_path.join("cache"),
608            Some(&self.installation_path.join("blank_user_npmrc")),
609            Some(&self.installation_path.join("blank_global_npmrc")),
610            proxy,
611            subcommand,
612            args,
613        );
614        let command_env = npm_command_env(Some(&node_binary));
615
616        Ok(NpmCommand {
617            path: node_binary,
618            args: command_args,
619            env: command_env,
620        })
621    }
622
623    async fn npm_package_installed_version(
624        &self,
625        local_package_directory: &Path,
626        name: &str,
627    ) -> Result<Option<Version>> {
628        read_package_installed_version(local_package_directory.join("node_modules"), name).await
629    }
630}
631
632#[derive(Debug, Clone)]
633pub struct SystemNodeRuntime {
634    node: PathBuf,
635    npm: PathBuf,
636    global_node_modules: PathBuf,
637    scratch_dir: PathBuf,
638}
639
640impl SystemNodeRuntime {
641    const MIN_VERSION: semver::Version = Version::new(22, 0, 0);
642    async fn new(node: PathBuf, npm: PathBuf) -> Result<Self> {
643        let output = util::command::new_smol_command(&node)
644            .arg("--version")
645            .output()
646            .await
647            .with_context(|| format!("running node from {:?}", node))?;
648        if !output.status.success() {
649            anyhow::bail!(
650                "failed to run node --version. stdout: {}, stderr: {}",
651                String::from_utf8_lossy(&output.stdout),
652                String::from_utf8_lossy(&output.stderr),
653            );
654        }
655        let version_str = String::from_utf8_lossy(&output.stdout);
656        let version = semver::Version::parse(version_str.trim().trim_start_matches('v'))?;
657        if version < Self::MIN_VERSION {
658            anyhow::bail!(
659                "node at {} is too old. want: {}, got: {}",
660                node.to_string_lossy(),
661                Self::MIN_VERSION,
662                version
663            )
664        }
665
666        let scratch_dir = paths::data_dir().join("node");
667        fs::create_dir(&scratch_dir).await.ok();
668        fs::create_dir(scratch_dir.join("cache")).await.ok();
669
670        let mut this = Self {
671            node,
672            npm,
673            global_node_modules: PathBuf::default(),
674            scratch_dir,
675        };
676        let output = this.run_npm_subcommand(None, None, "root", &["-g"]).await?;
677        this.global_node_modules =
678            PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
679
680        Ok(this)
681    }
682
683    async fn detect() -> std::result::Result<Self, DetectError> {
684        let node = which::which("node").map_err(DetectError::NotInPath)?;
685        let npm = which::which("npm").map_err(DetectError::NotInPath)?;
686        Self::new(node, npm).await.map_err(DetectError::Other)
687    }
688}
689
690enum DetectError {
691    NotInPath(which::Error),
692    Other(anyhow::Error),
693}
694
695impl Display for DetectError {
696    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
697        match self {
698            DetectError::NotInPath(err) => {
699                write!(f, "system Node.js wasn't found on PATH: {}", err)
700            }
701            DetectError::Other(err) => {
702                write!(f, "checking system Node.js failed with error: {}", err)
703            }
704        }
705    }
706}
707
708#[async_trait::async_trait]
709impl NodeRuntimeTrait for SystemNodeRuntime {
710    fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
711        Box::new(self.clone())
712    }
713
714    fn binary_path(&self) -> Result<PathBuf> {
715        Ok(self.node.clone())
716    }
717
718    async fn run_npm_subcommand(
719        &self,
720        directory: Option<&Path>,
721        proxy: Option<&Url>,
722        subcommand: &str,
723        args: &[&str],
724    ) -> anyhow::Result<Output> {
725        let npm_command = self.npm_command(proxy, subcommand, args).await?;
726        let mut command = util::command::new_smol_command(npm_command.path);
727        command.args(npm_command.args);
728        command.envs(npm_command.env);
729        configure_npm_command(&mut command, directory);
730        let output = command.output().await?;
731        anyhow::ensure!(
732            output.status.success(),
733            "failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
734            String::from_utf8_lossy(&output.stdout),
735            String::from_utf8_lossy(&output.stderr)
736        );
737        Ok(output)
738    }
739
740    async fn npm_command(
741        &self,
742        proxy: Option<&Url>,
743        subcommand: &str,
744        args: &[&str],
745    ) -> Result<NpmCommand> {
746        let command_args = build_npm_command_args(
747            None,
748            &self.scratch_dir.join("cache"),
749            None,
750            None,
751            proxy,
752            subcommand,
753            args,
754        );
755        let command_env = npm_command_env(Some(&self.node));
756
757        Ok(NpmCommand {
758            path: self.npm.clone(),
759            args: command_args,
760            env: command_env,
761        })
762    }
763
764    async fn npm_package_installed_version(
765        &self,
766        local_package_directory: &Path,
767        name: &str,
768    ) -> Result<Option<Version>> {
769        read_package_installed_version(local_package_directory.join("node_modules"), name).await
770        // todo: allow returning a globally installed version (requires callers not to hard-code the path)
771    }
772}
773
774pub async fn read_package_installed_version(
775    node_module_directory: PathBuf,
776    name: &str,
777) -> Result<Option<Version>> {
778    let package_json_path = node_module_directory.join(name).join("package.json");
779
780    let mut file = match fs::File::open(package_json_path).await {
781        Ok(file) => file,
782        Err(err) => {
783            if err.kind() == io::ErrorKind::NotFound {
784                return Ok(None);
785            }
786
787            Err(err)?
788        }
789    };
790
791    #[derive(Deserialize)]
792    struct PackageJson {
793        version: Version,
794    }
795
796    let mut contents = String::new();
797    file.read_to_string(&mut contents).await?;
798    let package_json: PackageJson = serde_json::from_str(&contents)?;
799    Ok(Some(package_json.version))
800}
801
802#[derive(Clone)]
803pub struct UnavailableNodeRuntime {
804    error_message: Arc<String>,
805}
806
807#[async_trait::async_trait]
808impl NodeRuntimeTrait for UnavailableNodeRuntime {
809    fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
810        Box::new(self.clone())
811    }
812    fn binary_path(&self) -> Result<PathBuf> {
813        bail!("{}", self.error_message)
814    }
815
816    async fn run_npm_subcommand(
817        &self,
818        _: Option<&Path>,
819        _: Option<&Url>,
820        _: &str,
821        _: &[&str],
822    ) -> anyhow::Result<Output> {
823        bail!("{}", self.error_message)
824    }
825
826    async fn npm_command(
827        &self,
828        _proxy: Option<&Url>,
829        _subcommand: &str,
830        _args: &[&str],
831    ) -> Result<NpmCommand> {
832        bail!("{}", self.error_message)
833    }
834
835    async fn npm_package_installed_version(
836        &self,
837        _local_package_directory: &Path,
838        _: &str,
839    ) -> Result<Option<Version>> {
840        bail!("{}", self.error_message)
841    }
842}
843
844fn configure_npm_command(command: &mut smol::process::Command, directory: Option<&Path>) {
845    if let Some(directory) = directory {
846        command.current_dir(directory);
847        command.args(["--prefix".into(), directory.to_path_buf()]);
848    }
849}
850
851fn proxy_argument(proxy: Option<&Url>) -> Option<String> {
852    let mut proxy = proxy.cloned()?;
853    // Map proxy settings from `http://localhost:10809` to `http://127.0.0.1:10809`
854    // NodeRuntime without environment information can not parse `localhost`
855    // correctly.
856    // TODO: map to `[::1]` if we are using ipv6
857    if matches!(proxy.host(), Some(Host::Domain(domain)) if domain.eq_ignore_ascii_case("localhost"))
858    {
859        // When localhost is a valid Host, so is `127.0.0.1`
860        let _ = proxy.set_ip_host(IpAddr::V4(Ipv4Addr::LOCALHOST));
861    }
862
863    Some(proxy.as_str().to_string())
864}
865
866fn build_npm_command_args(
867    entrypoint: Option<&Path>,
868    cache_dir: &Path,
869    user_config: Option<&Path>,
870    global_config: Option<&Path>,
871    proxy: Option<&Url>,
872    subcommand: &str,
873    args: &[&str],
874) -> Vec<String> {
875    let mut command_args = Vec::new();
876    if let Some(entrypoint) = entrypoint {
877        command_args.push(entrypoint.to_string_lossy().into_owned());
878    }
879    command_args.push(subcommand.to_string());
880    command_args.push(format!("--cache={}", cache_dir.display()));
881    if let Some(user_config) = user_config {
882        command_args.push("--userconfig".into());
883        command_args.push(user_config.to_string_lossy().into_owned());
884    }
885    if let Some(global_config) = global_config {
886        command_args.push("--globalconfig".into());
887        command_args.push(global_config.to_string_lossy().into_owned());
888    }
889    if let Some(proxy_arg) = proxy_argument(proxy) {
890        command_args.push("--proxy".into());
891        command_args.push(proxy_arg);
892    }
893    command_args.extend(args.into_iter().map(|a| a.to_string()));
894    command_args
895}
896
897fn npm_command_env(node_binary: Option<&Path>) -> HashMap<String, String> {
898    let mut command_env = HashMap::new();
899    if let Some(node_binary) = node_binary {
900        let env_path = path_with_node_binary_prepended(node_binary).unwrap_or_default();
901        command_env.insert("PATH".into(), env_path.to_string_lossy().into_owned());
902    }
903
904    if let Ok(node_ca_certs) = env::var(NODE_CA_CERTS_ENV_VAR) {
905        if !node_ca_certs.is_empty() {
906            command_env.insert(NODE_CA_CERTS_ENV_VAR.to_string(), node_ca_certs);
907        }
908    }
909
910    #[cfg(windows)]
911    {
912        if let Some(val) = env::var("SYSTEMROOT")
913            .context("Missing environment variable: SYSTEMROOT!")
914            .log_err()
915        {
916            command_env.insert("SYSTEMROOT".into(), val);
917        }
918        if let Some(val) = env::var("ComSpec")
919            .context("Missing environment variable: ComSpec!")
920            .log_err()
921        {
922            command_env.insert("ComSpec".into(), val);
923        }
924    }
925
926    command_env
927}
928
929#[cfg(test)]
930mod tests {
931    use http_client::Url;
932
933    use super::proxy_argument;
934
935    // Map localhost to 127.0.0.1
936    // NodeRuntime without environment information can not parse `localhost` correctly.
937    #[test]
938    fn test_proxy_argument_map_localhost_proxy() {
939        const CASES: [(&str, &str); 4] = [
940            // Map localhost to 127.0.0.1
941            ("http://localhost:9090/", "http://127.0.0.1:9090/"),
942            ("https://google.com/", "https://google.com/"),
943            (
944                "http://username:password@proxy.thing.com:8080/",
945                "http://username:password@proxy.thing.com:8080/",
946            ),
947            // Test when localhost is contained within a different part of the URL
948            (
949                "http://username:localhost@localhost:8080/",
950                "http://username:localhost@127.0.0.1:8080/",
951            ),
952        ];
953
954        for (proxy, mapped_proxy) in CASES {
955            let proxy = Url::parse(proxy).unwrap();
956            let proxy = proxy_argument(Some(&proxy)).expect("Proxy was not passed correctly");
957            assert_eq!(
958                proxy, mapped_proxy,
959                "Incorrectly mapped localhost to 127.0.0.1"
960            );
961        }
962    }
963}