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