From c7ccc03ea69a767809feee73047e5ba9824c3e1f Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 12 Aug 2024 17:44:40 +0200 Subject: [PATCH 01/11] refactor: most specific error handling --- src/graph.rs | 42 ++++++++++++++++++--------------------- src/jsr.rs | 12 +++++------ src/lib.rs | 8 +++----- src/source/file_system.rs | 27 ++++++++++++++----------- src/source/mod.rs | 42 ++++++++++++++++++++++++++------------- tests/ecosystem_test.rs | 7 +++---- 6 files changed, 74 insertions(+), 64 deletions(-) diff --git a/src/graph.rs b/src/graph.rs index c51a9903b..ba2d92faf 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -173,15 +173,15 @@ pub enum JsrLoadError { #[error("Loader should never return an external specifier for a jsr: specifier content load.")] ContentLoadExternalSpecifier, #[error(transparent)] - ContentLoad(Arc), + ContentLoad(Arc), #[error("JSR package manifest for '{}' failed to load. {:#}", .0, .1)] - PackageManifestLoad(String, Arc), + PackageManifestLoad(String, Arc), #[error("JSR package not found: {}", .0)] PackageNotFound(String), #[error("JSR package version not found: {}", .0)] PackageVersionNotFound(PackageNv), #[error("JSR package version manifest for '{}' failed to load: {:#}", .0, .1)] - PackageVersionManifestLoad(PackageNv, Arc), + PackageVersionManifestLoad(PackageNv, Arc), #[error("JSR package version manifest for '{}' failed to load: {:#}", .0, .1)] PackageVersionManifestChecksumIntegrity(PackageNv, ChecksumIntegrityError), #[error(transparent)] @@ -225,7 +225,7 @@ pub enum ModuleLoadError { #[error(transparent)] Decode(Arc), #[error(transparent)] - Loader(Arc), + Loader(Arc), #[error(transparent)] Jsr(#[from] JsrLoadError), #[error(transparent)] @@ -2004,7 +2004,7 @@ fn resolve( use SpecifierError::*; let res_ref = response.as_ref(); if matches!(res_ref, Err(Specifier(ImportPrefixMissing { .. }))) - || matches!(res_ref, Err(Other(e)) if matches!(e.downcast_ref::(), Some(&ImportMapError::UnmappedBareSpecifier(_, _)))) + || matches!(res_ref, Err(ImportMap(ImportMapError::UnmappedBareSpecifier(_, _)))) { if let Ok(specifier) = ModuleSpecifier::parse(&format!("node:{}", specifier_text)) @@ -4370,24 +4370,20 @@ impl<'a, 'graph> Builder<'a, 'graph> { load_specifier.clone(), maybe_range.cloned(), )), - Err(err) => match err.downcast::() { - // try to return the context of a checksum integrity error - // so that it can be more easily enhanced - Ok(err) => Err(ModuleError::LoadingErr( - load_specifier.clone(), - maybe_range.cloned(), - if maybe_version_info.is_some() { - JsrLoadError::ContentChecksumIntegrity(err).into() - } else { - ModuleLoadError::HttpsChecksumIntegrity(err) - }, - )), - Err(err) => Err(ModuleError::LoadingErr( - load_specifier.clone(), - maybe_range.cloned(), - ModuleLoadError::Loader(Arc::new(err)), - )), - }, + Err(LoadError::ChecksumIntegrity(err)) => Err(ModuleError::LoadingErr( + load_specifier.clone(), + maybe_range.cloned(), + if maybe_version_info.is_some() { + JsrLoadError::ContentChecksumIntegrity(err).into() + } else { + ModuleLoadError::HttpsChecksumIntegrity(err) + }, + )), + Err(err) => Err(ModuleError::LoadingErr( + load_specifier.clone(), + maybe_range.cloned(), + ModuleLoadError::Loader(Arc::new(err)), + )), } } diff --git a/src/jsr.rs b/src/jsr.rs index f9fb763c4..4190523d1 100644 --- a/src/jsr.rs +++ b/src/jsr.rs @@ -15,8 +15,8 @@ use crate::packages::JsrPackageVersionInfo; use crate::rt::spawn; use crate::rt::JoinHandle; use crate::source::CacheSetting; -use crate::source::ChecksumIntegrityError; use crate::source::JsrUrlProvider; +use crate::source::LoadError; use crate::source::LoadOptions; use crate::source::LoadResponse; use crate::source::Loader; @@ -154,15 +154,15 @@ impl JsrMetadataStore { { let package_nv = package_nv.clone(); |e| { - match e.downcast::() { - Ok(err) => { + match e { + LoadError::ChecksumIntegrity(err) => { // use a more specific variant in order to allow the // cli to enhance this error message JsrLoadError::PackageVersionManifestChecksumIntegrity( package_nv, err, ) } - Err(err) => JsrLoadError::PackageVersionManifestLoad( + err => JsrLoadError::PackageVersionManifestLoad( package_nv, Arc::new(err), ), @@ -187,7 +187,7 @@ impl JsrMetadataStore { cache_setting: CacheSetting, maybe_expected_checksum: Option, handle_content: impl FnOnce(&[u8]) -> Result + 'static, - create_failed_load_err: impl FnOnce(anyhow::Error) -> JsrLoadError + 'static, + create_failed_load_err: impl FnOnce(LoadError) -> JsrLoadError + 'static, create_not_found_error: impl FnOnce() -> JsrLoadError + 'static, ) -> PendingResult { let fut = services.loader.load( @@ -216,7 +216,7 @@ impl JsrMetadataStore { _ => Err(create_not_found_error()), } } - .boxed_local(), + .boxed_local(), ); fut.shared_local() } diff --git a/src/lib.rs b/src/lib.rs index 6016c411a..5435f2e52 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1260,8 +1260,7 @@ console.log(a); fn resolve_builtin_node_module( &self, specifier: &deno_ast::ModuleSpecifier, - ) -> anyhow::Result, source::UnknownBuiltInNodeModuleError> - { + ) -> Result, source::UnknownBuiltInNodeModuleError> { if specifier.to_string() == "node:path" { Ok(Some("path".to_string())) } else { @@ -1317,12 +1316,11 @@ console.log(a); _mode: ResolutionMode, ) -> Result { use import_map::ImportMapError; - Err(source::ResolveError::Other( + Err(source::ResolveError::ImportMap( ImportMapError::UnmappedBareSpecifier( specifier_text.to_string(), Some(referrer_range.specifier.to_string()), - ) - .into(), + ), )) } diff --git a/src/source/file_system.rs b/src/source/file_system.rs index 99c20a44d..91129b154 100644 --- a/src/source/file_system.rs +++ b/src/source/file_system.rs @@ -11,9 +11,20 @@ pub enum DirEntryKind { File, Dir, Symlink, - Error(anyhow::Error), + Error(DirEntryError), } +#[derive(Debug, thiserror::Error)] +pub enum DirEntryError { + #[error("Failed to read directory.")] + Dir(std::io::Error), + #[error("Failed to read file type.")] + FileType(std::io::Error), + #[error("Failed to read entry in directory.")] + DirEntry(std::io::Error), +} + + #[derive(Debug)] pub struct DirEntry { pub kind: DirEntryKind, @@ -132,10 +143,7 @@ impl FileSystem for RealFileSystem { } Err(err) => { return vec![DirEntry { - kind: DirEntryKind::Error( - anyhow::Error::from(err) - .context("Failed to read directory.".to_string()), - ), + kind: DirEntryKind::Error(DirEntryError::Dir(err)), url: dir_url.clone(), }]; } @@ -162,9 +170,7 @@ impl FileSystem for RealFileSystem { continue; } Err(err) => DirEntry { - kind: DirEntryKind::Error( - anyhow::Error::from(err).context("Failed to read file type."), - ), + kind: DirEntryKind::Error(DirEntryError::FileType(err)), url: ModuleSpecifier::from_file_path(entry.path()).unwrap(), }, } @@ -179,10 +185,7 @@ impl FileSystem for RealFileSystem { } Err(err) => DirEntry { url: dir_url.clone(), - kind: DirEntryKind::Error( - anyhow::Error::from(err) - .context("Failed to read entry in directory.".to_string()), - ), + kind: DirEntryKind::Error(DirEntryError::DirEntry(err)), }, }; diff --git a/src/source/mod.rs b/src/source/mod.rs index cff7f68f5..a67ce95ac 100644 --- a/src/source/mod.rs +++ b/src/source/mod.rs @@ -12,8 +12,6 @@ use async_trait::async_trait; use deno_ast::MediaType; use deno_semver::package::PackageNv; -use anyhow::anyhow; -use anyhow::Error; use data_url::DataUrl; use deno_ast::ModuleSpecifier; use deno_semver::package::PackageReq; @@ -85,7 +83,21 @@ pub enum LoadResponse { }, } -pub type LoadResult = Result, anyhow::Error>; +#[derive(Debug, Error)] +pub enum LoadError { + #[error("Unsupported scheme: {0}")] + UnsupportedScheme(String), + #[error(transparent)] + ChecksumIntegrity(#[from] ChecksumIntegrityError), + #[error(transparent)] + JsonParse(#[from] serde_json::Error), + #[error(transparent)] + DataUrl(std::io::Error), + #[error(transparent)] + Other(#[from] anyhow::Error), +} + +pub type LoadResult = Result, LoadError>; pub type LoadFuture = LocalBoxFuture<'static, LoadResult>; #[derive(Debug, Copy, Clone, PartialEq, Eq)] @@ -122,7 +134,8 @@ pub static DEFAULT_JSR_URL: Lazy = Lazy::new(|| Url::parse("https://jsr.io").unwrap()); #[derive(Debug, Clone, Error)] -#[error("Integrity check failed.\n\nActual: {}\nExpected: {}", .actual, .expected)] +#[error("Integrity check failed.\n\nActual: {}\nExpected: {}", .actual, .expected +)] pub struct ChecksumIntegrityError { pub actual: String, pub expected: String, @@ -297,8 +310,7 @@ pub trait Loader { _specifier: &ModuleSpecifier, _source: &Arc<[u8]>, _module_info: &ModuleInfo, - ) { - } + ) {} } pub trait JsrUrlProvider { @@ -361,6 +373,8 @@ pub enum ResolveError { #[error(transparent)] Specifier(#[from] SpecifierError), #[error(transparent)] + ImportMap(#[from] import_map::ImportMapError), + #[error(transparent)] Other(#[from] anyhow::Error), } @@ -488,8 +502,8 @@ pub trait NpmResolver: fmt::Debug { pub fn load_data_url( specifier: &ModuleSpecifier, -) -> Result, anyhow::Error> { - let data_url = RawDataUrl::parse(specifier)?; +) -> Result, LoadError> { + let data_url = RawDataUrl::parse(specifier).map_err(LoadError::DataUrl)?; let (bytes, headers) = data_url.into_bytes_and_headers(); Ok(Some(LoadResponse::Module { specifier: specifier.clone(), @@ -563,7 +577,7 @@ fn get_mime_type_charset(mime_type: &str) -> Option<&str> { /// ahead of time. This is useful for testing or #[derive(Default)] pub struct MemoryLoader { - sources: HashMap>, + sources: HashMap>, cache_info: HashMap, } @@ -575,11 +589,11 @@ pub enum Source { }, Redirect(S), External(S), - Err(Error), + Err(anyhow::Error), } impl> Source { - fn into_result(self) -> Result { + fn into_result(self) -> Result { match self { Source::Module { specifier, @@ -699,7 +713,7 @@ impl Loader for MemoryLoader { ) -> LoadFuture { let response = match self.sources.get(specifier) { Some(Ok(response)) => Ok(Some(response.clone())), - Some(Err(err)) => Err(anyhow!("{}", err)), + Some(Err(err)) => Err(LoadError::Other(anyhow::anyhow!("{}", err))), None if specifier.scheme() == "data" => load_data_url(specifier), _ => Ok(None), }; @@ -924,7 +938,7 @@ pub mod tests { let actual: LoadResponse = serde_json::from_value( json!({ "kind": "external", "specifier": "https://example.com/bundle" }), ) - .unwrap(); + .unwrap(); assert_eq!( actual, LoadResponse::External { @@ -1204,7 +1218,7 @@ pub mod tests { let text = decode_owned_file_source( format!("{}{}", text_encoding::BOM_CHAR, "Hello").into_bytes(), ) - .unwrap(); + .unwrap(); assert_eq!(text, "Hello"); } diff --git a/tests/ecosystem_test.rs b/tests/ecosystem_test.rs index a35847896..942bf3792 100644 --- a/tests/ecosystem_test.rs +++ b/tests/ecosystem_test.rs @@ -178,16 +178,15 @@ impl deno_graph::source::Loader for Loader<'_> { specifier: specifier.clone(), })), Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), - Err(err) => Err(anyhow::Error::from(err)), + Err(err) => Err(anyhow::Error::from(err).into()), } } "data" => deno_graph::source::load_data_url(specifier), "jsr" | "npm" | "node" => Ok(Some(LoadResponse::External { specifier: specifier.clone(), })), - _ => Err(anyhow::anyhow!( - "Unsupported scheme: {}", - specifier.scheme() + _ => Err(deno_graph::source::LoadError::UnsupportedScheme( + specifier.scheme().to_string(), )), }; async move { res }.boxed() From 82c9145e90957695de326950b3b8472776f3f3cc Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 12 Aug 2024 17:45:26 +0200 Subject: [PATCH 02/11] fmt --- src/graph.rs | 25 +++++++++++++++---------- src/jsr.rs | 2 +- src/source/file_system.rs | 1 - src/source/mod.rs | 7 ++++--- 4 files changed, 20 insertions(+), 15 deletions(-) diff --git a/src/graph.rs b/src/graph.rs index ba2d92faf..b62e5cd3b 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -2004,7 +2004,10 @@ fn resolve( use SpecifierError::*; let res_ref = response.as_ref(); if matches!(res_ref, Err(Specifier(ImportPrefixMissing { .. }))) - || matches!(res_ref, Err(ImportMap(ImportMapError::UnmappedBareSpecifier(_, _)))) + || matches!( + res_ref, + Err(ImportMap(ImportMapError::UnmappedBareSpecifier(_, _))) + ) { if let Ok(specifier) = ModuleSpecifier::parse(&format!("node:{}", specifier_text)) @@ -4370,15 +4373,17 @@ impl<'a, 'graph> Builder<'a, 'graph> { load_specifier.clone(), maybe_range.cloned(), )), - Err(LoadError::ChecksumIntegrity(err)) => Err(ModuleError::LoadingErr( - load_specifier.clone(), - maybe_range.cloned(), - if maybe_version_info.is_some() { - JsrLoadError::ContentChecksumIntegrity(err).into() - } else { - ModuleLoadError::HttpsChecksumIntegrity(err) - }, - )), + Err(LoadError::ChecksumIntegrity(err)) => { + Err(ModuleError::LoadingErr( + load_specifier.clone(), + maybe_range.cloned(), + if maybe_version_info.is_some() { + JsrLoadError::ContentChecksumIntegrity(err).into() + } else { + ModuleLoadError::HttpsChecksumIntegrity(err) + }, + )) + } Err(err) => Err(ModuleError::LoadingErr( load_specifier.clone(), maybe_range.cloned(), diff --git a/src/jsr.rs b/src/jsr.rs index 4190523d1..3317f27af 100644 --- a/src/jsr.rs +++ b/src/jsr.rs @@ -216,7 +216,7 @@ impl JsrMetadataStore { _ => Err(create_not_found_error()), } } - .boxed_local(), + .boxed_local(), ); fut.shared_local() } diff --git a/src/source/file_system.rs b/src/source/file_system.rs index 91129b154..32a464460 100644 --- a/src/source/file_system.rs +++ b/src/source/file_system.rs @@ -24,7 +24,6 @@ pub enum DirEntryError { DirEntry(std::io::Error), } - #[derive(Debug)] pub struct DirEntry { pub kind: DirEntryKind, diff --git a/src/source/mod.rs b/src/source/mod.rs index a67ce95ac..1fda2e445 100644 --- a/src/source/mod.rs +++ b/src/source/mod.rs @@ -310,7 +310,8 @@ pub trait Loader { _specifier: &ModuleSpecifier, _source: &Arc<[u8]>, _module_info: &ModuleInfo, - ) {} + ) { + } } pub trait JsrUrlProvider { @@ -938,7 +939,7 @@ pub mod tests { let actual: LoadResponse = serde_json::from_value( json!({ "kind": "external", "specifier": "https://example.com/bundle" }), ) - .unwrap(); + .unwrap(); assert_eq!( actual, LoadResponse::External { @@ -1218,7 +1219,7 @@ pub mod tests { let text = decode_owned_file_source( format!("{}{}", text_encoding::BOM_CHAR, "Hello").into_bytes(), ) - .unwrap(); + .unwrap(); assert_eq!(text, "Hello"); } From 1f9184fa4e12af1afdbf3beff9c31feefd57da57 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 12 Aug 2024 17:51:46 +0200 Subject: [PATCH 03/11] fix wasm --- lib/lib.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/lib.rs b/lib/lib.rs index 392235d5e..42a69d773 100644 --- a/lib/lib.rs +++ b/lib/lib.rs @@ -86,7 +86,7 @@ impl Loader for JsLoader { cache_setting: options.cache_setting.as_js_str(), checksum: options.maybe_checksum.map(|c| c.into_string()), }) - .unwrap(); + .unwrap(); let result = self.load.call2(&context, &arg1, &arg2); let f = async move { let response = match result { @@ -94,13 +94,13 @@ impl Loader for JsLoader { wasm_bindgen_futures::JsFuture::from(js_sys::Promise::resolve( &result, )) - .await + .await } Err(err) => Err(err), }; response .map(|value| serde_wasm_bindgen::from_value(value).unwrap()) - .map_err(|_| anyhow!("load rejected or errored")) + .map_err(|_| anyhow!("load rejected or errored").into()) }; Box::pin(f) } @@ -335,7 +335,7 @@ pub async fn js_parse_module( module_analyzer: Default::default(), maybe_npm_resolver: None, }) - .await + .await { Ok(module) => { let serializer = @@ -362,7 +362,7 @@ mod tests { "specifier": "file:///package.json" } })) - .unwrap(); + .unwrap(); assert_eq!( actual, Some(JsResolveTypesResponse { @@ -377,7 +377,7 @@ mod tests { let actual: Option = from_value(json!({ "types": "https://deno.land/x/mod.d.ts", })) - .unwrap(); + .unwrap(); assert_eq!( actual, Some(JsResolveTypesResponse { From 128e993753a255672f1820ad5fe810a87e1a5af0 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 12 Aug 2024 17:51:58 +0200 Subject: [PATCH 04/11] fmt --- lib/lib.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/lib.rs b/lib/lib.rs index 42a69d773..7ed3b905f 100644 --- a/lib/lib.rs +++ b/lib/lib.rs @@ -86,7 +86,7 @@ impl Loader for JsLoader { cache_setting: options.cache_setting.as_js_str(), checksum: options.maybe_checksum.map(|c| c.into_string()), }) - .unwrap(); + .unwrap(); let result = self.load.call2(&context, &arg1, &arg2); let f = async move { let response = match result { @@ -94,7 +94,7 @@ impl Loader for JsLoader { wasm_bindgen_futures::JsFuture::from(js_sys::Promise::resolve( &result, )) - .await + .await } Err(err) => Err(err), }; @@ -335,7 +335,7 @@ pub async fn js_parse_module( module_analyzer: Default::default(), maybe_npm_resolver: None, }) - .await + .await { Ok(module) => { let serializer = @@ -362,7 +362,7 @@ mod tests { "specifier": "file:///package.json" } })) - .unwrap(); + .unwrap(); assert_eq!( actual, Some(JsResolveTypesResponse { @@ -377,7 +377,7 @@ mod tests { let actual: Option = from_value(json!({ "types": "https://deno.land/x/mod.d.ts", })) - .unwrap(); + .unwrap(); assert_eq!( actual, Some(JsResolveTypesResponse { From ca712972276921a900820dbdd5cac7045d479e61 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 22 Nov 2024 06:19:45 +0100 Subject: [PATCH 05/11] more --- Cargo.lock | 437 ++++++++++++++++++++++++++++++++++------ Cargo.toml | 13 +- src/graph.rs | 110 +++++++--- src/lib.rs | 26 ++- src/source/mod.rs | 54 +++-- tests/ecosystem_test.rs | 4 +- tests/helpers/mod.rs | 4 +- 7 files changed, 524 insertions(+), 124 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1c831accf..a34e42b26 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -119,7 +119,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -130,7 +130,7 @@ checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -226,6 +226,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "boxed_error" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17d4f95e880cfd28c4ca5a006cf7f6af52b4bcb7b5866f573b2faa126fb7affb" +dependencies = [ + "quote", + "syn 2.0.87", +] + [[package]] name = "bumpalo" version = "3.16.0" @@ -340,13 +350,14 @@ dependencies = [ [[package]] name = "deno_ast" -version = "0.43.2" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbbf350300650502744d50bdd31eca7ea094c25216758a5a02a2b5ac66e62cf9" +checksum = "eebc7aaabfdb3ddcad32aee1b62d250149dc8b35dfbdccbb125df2bdc62da952" dependencies = [ "base64 0.21.7", + "deno_error", "deno_media_type", - "deno_terminal", + "deno_terminal 0.2.0", "dprint-swc-ext", "once_cell", "percent-encoding", @@ -374,11 +385,35 @@ dependencies = [ "swc_visit", "swc_visit_macros", "text_lines", - "thiserror", + "thiserror 2.0.3", "unicode-width", "url", ] +[[package]] +name = "deno_error" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17093059f04120895ee7bad790f074b1e4a0aa7c68511dbe8355ad0b092a4910" +dependencies = [ + "deno_error_macro", + "libc", + "serde", + "serde_json", + "url", +] + +[[package]] +name = "deno_error_macro" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3a5d888391b76dc9b53e35651d2d11086fa05110beba167f08294920dd9059" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + [[package]] name = "deno_graph" version = "0.84.1" @@ -388,8 +423,9 @@ dependencies = [ "bincode", "data-url", "deno_ast", + "deno_error", "deno_semver", - "deno_terminal", + "deno_terminal 0.2.0", "deno_unsync", "encoding_rs", "env_logger", @@ -408,7 +444,7 @@ dependencies = [ "serde_json", "sha2", "tempfile", - "thiserror", + "thiserror 2.0.3", "tokio", "twox-hash", "url", @@ -445,14 +481,15 @@ dependencies = [ [[package]] name = "deno_semver" -version = "0.5.13" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6657fecb9ac6a7a71f552c95e8cc492466a75f5660224577e2226bcf30db9768" +checksum = "4756be7351289726087408984db18b9eb5e0186907673f39f858d119d0162071" dependencies = [ + "deno_error", "monch", "once_cell", "serde", - "thiserror", + "thiserror 2.0.3", "url", ] @@ -466,6 +503,16 @@ dependencies = [ "termcolor", ] +[[package]] +name = "deno_terminal" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daef12499e89ee99e51ad6000a91f600d3937fb028ad4918af76810c5bc9e0d5" +dependencies = [ + "once_cell", + "termcolor", +] + [[package]] name = "deno_unsync" version = "0.4.0" @@ -492,6 +539,17 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + [[package]] name = "dprint-swc-ext" version = "0.20.0" @@ -575,10 +633,10 @@ checksum = "05b23dcc1b671771c6f59fdace6da685735c925f859733e8fd07fba6cae6462a" dependencies = [ "anyhow", "crossbeam-channel", - "deno_terminal", + "deno_terminal 0.1.1", "parking_lot", "regex", - "thiserror", + "thiserror 1.0.63", ] [[package]] @@ -604,7 +662,7 @@ checksum = "32016f1242eb82af5474752d00fd8ebcd9004bd69b462b1c91de833972d08ed4" dependencies = [ "proc-macro2", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -669,7 +727,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -884,14 +942,143 @@ dependencies = [ "tracing", ] +[[package]] +name = "icu_collections" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locid" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locid_transform" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_locid_transform_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locid_transform_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" + +[[package]] +name = "icu_normalizer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" + +[[package]] +name = "icu_properties" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locid_transform", + "icu_properties_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" + +[[package]] +name = "icu_provider" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_provider_macros", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_provider_macros" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + [[package]] name = "idna" -version = "0.5.0" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" +checksum = "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71" dependencies = [ - "unicode-bidi", - "unicode-normalization", + "icu_normalizer", + "icu_properties", ] [[package]] @@ -902,15 +1089,18 @@ checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" [[package]] name = "import_map" -version = "0.20.0" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "373b8288ad259df0d1314e3e8b2fff0e5e63f22e01bc54ecd2c3c7ad77b9200c" +checksum = "1215d4d92511fbbdaea50e750e91f2429598ef817f02b579158e92803b52c00a" dependencies = [ + "boxed_error", + "deno_error", "indexmap", "log", "percent-encoding", "serde", "serde_json", + "thiserror 2.0.3", "url", ] @@ -940,7 +1130,7 @@ dependencies = [ "Inflector", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -982,6 +1172,12 @@ version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" +[[package]] +name = "litemap" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" + [[package]] name = "lock_api" version = "0.4.12" @@ -1168,7 +1364,7 @@ dependencies = [ "phf_shared", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -1197,7 +1393,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -1278,7 +1474,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls", - "thiserror", + "thiserror 1.0.63", "tokio", "tracing", ] @@ -1295,7 +1491,7 @@ dependencies = [ "rustc-hash", "rustls", "slab", - "thiserror", + "thiserror 1.0.63", "tinyvec", "tracing", ] @@ -1314,9 +1510,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.36" +version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" dependencies = [ "proc-macro2", ] @@ -1596,7 +1792,7 @@ checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -1755,7 +1951,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -1853,7 +2049,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -1902,7 +2098,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -1987,7 +2183,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2094,7 +2290,7 @@ checksum = "63db0adcff29d220c3d151c5b25c0eabe7e32dd936212b84cdaa1392e3130497" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2105,7 +2301,7 @@ checksum = "f486687bfb7b5c560868f69ed2d458b880cebc9babebcb67e49f31b55c5bf847" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2128,7 +2324,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2144,9 +2340,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.72" +version = "2.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" +checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" dependencies = [ "proc-macro2", "quote", @@ -2159,6 +2355,17 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" +[[package]] +name = "synstructure" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + [[package]] name = "tap" version = "1.0.1" @@ -2201,7 +2408,16 @@ version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.63", +] + +[[package]] +name = "thiserror" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c006c85c7651b3cf2ada4584faa36773bd07bac24acfb39f3c431b36d7e667aa" +dependencies = [ + "thiserror-impl 2.0.3", ] [[package]] @@ -2212,7 +2428,28 @@ checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + +[[package]] +name = "tinystr" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" +dependencies = [ + "displaydoc", + "zerovec", ] [[package]] @@ -2254,7 +2491,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2327,7 +2564,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2378,12 +2615,6 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" -[[package]] -name = "unicode-bidi" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" - [[package]] name = "unicode-id" version = "0.3.4" @@ -2402,15 +2633,6 @@ version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" -[[package]] -name = "unicode-normalization" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" -dependencies = [ - "tinyvec", -] - [[package]] name = "unicode-width" version = "0.1.13" @@ -2425,9 +2647,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.2" +version = "2.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" +checksum = "8d157f1b96d14500ffdc1f10ba712e780825526c03d9a49b4d0324b0d9113ada" dependencies = [ "form_urlencoded", "idna", @@ -2435,6 +2657,18 @@ dependencies = [ "serde", ] +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "utf8parse" version = "0.2.2" @@ -2489,7 +2723,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", "wasm-bindgen-shared", ] @@ -2523,7 +2757,7 @@ checksum = "642f325be6301eb8107a83d12a8ac6c1e1c54345a7ef1a9261962dfefda09e66" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -2733,6 +2967,18 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" + [[package]] name = "wyz" version = "0.5.1" @@ -2748,6 +2994,30 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" +[[package]] +name = "yoke" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" +dependencies = [ + "serde", + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.7.35" @@ -2765,7 +3035,28 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", +] + +[[package]] +name = "zerofrom" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", + "synstructure", ] [[package]] @@ -2773,3 +3064,25 @@ name = "zeroize" version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" + +[[package]] +name = "zerovec" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] diff --git a/Cargo.toml b/Cargo.toml index cde1534c1..fde2249f4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,12 +41,12 @@ harness = false anyhow = "1.0.43" async-trait = "0.1.68" data-url = "0.3.0" -deno_ast = { version = "0.43.2", features = ["dep_analysis", "emit"] } +deno_ast = { version = "0.44.0", features = ["dep_analysis", "emit"] } deno_unsync.workspace = true -deno_semver = "0.5.13" +deno_semver = "0.6.0" encoding_rs = "0.8.33" futures = "0.3.26" -import_map = "0.20.0" +import_map = "0.21.0" indexmap = { version = "2", features = ["serde"] } log = "0.4.20" monch = "0.5.0" @@ -56,9 +56,10 @@ regex = "1.10.2" serde = { version = "1.0.130", features = ["derive", "rc"] } serde_json = { version = "1.0.67", features = ["preserve_order"] } sha2 = "^0.10.0" -thiserror = "1.0.24" +thiserror = "2" +deno_error = "0.5.1" twox-hash = { version = "1.6.3", optional = true } -url = { version = "2.2.2", features = ["serde"] } +url = { version = "2.5.3", features = ["serde"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] deno_unsync = { workspace = true, features = ["tokio"] } @@ -70,7 +71,7 @@ pretty_assertions = "1.0.0" reqwest = { version = "0.12.4", default-features = false, features = ["http2", "charset", "rustls-tls-webpki-roots"] } tempfile = "3.4.0" tokio = { version = "1.10.1", features = ["macros", "rt-multi-thread", "sync"] } -deno_terminal = "0.1.1" +deno_terminal = "0.2.0" env_logger = "0.11.3" [profile.release] diff --git a/src/graph.rs b/src/graph.rs index 5b1e88551..36134692e 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -36,6 +36,8 @@ use deno_ast::MediaType; use deno_ast::ParseDiagnostic; use deno_ast::SourcePos; use deno_ast::SourceTextInfo; +use deno_error::JsError; +use deno_error::JsErrorClass; use deno_semver::jsr::JsrDepPackageReq; use deno_semver::jsr::JsrPackageNvReference; use deno_semver::jsr::JsrPackageReqReference; @@ -163,34 +165,50 @@ impl Range { } } -#[derive(Debug, Clone, Error)] +#[derive(Debug, Clone, Error, JsError)] pub enum JsrLoadError { + #[class(type)] #[error( "Unsupported checksum in JSR package manifest. Maybe try upgrading deno?" )] UnsupportedManifestChecksum, + #[class(inherit)] #[error(transparent)] - ContentChecksumIntegrity(ChecksumIntegrityError), + ContentChecksumIntegrity(#[inherit] ChecksumIntegrityError), + #[class(generic)] #[error("Loader should never return an external specifier for a jsr: specifier content load.")] ContentLoadExternalSpecifier, + #[class(generic)] // TODO: maybe inherit? #[error(transparent)] ContentLoad(Arc), + #[class(generic)] // TODO: maybe inherit? #[error("JSR package manifest for '{}' failed to load. {:#}", .0, .1)] PackageManifestLoad(String, Arc), + #[class("NotFound")] #[error("JSR package not found: {}", .0)] PackageNotFound(String), + #[class("NotFound")] #[error("JSR package version not found: {}", .0)] PackageVersionNotFound(PackageNv), + #[class(generic)] // TODO: maybe inherit? #[error("JSR package version manifest for '{}' failed to load: {:#}", .0, .1)] PackageVersionManifestLoad(PackageNv, Arc), + #[class(inherit)] #[error("JSR package version manifest for '{}' failed to load: {:#}", .0, .1)] - PackageVersionManifestChecksumIntegrity(PackageNv, ChecksumIntegrityError), + PackageVersionManifestChecksumIntegrity( + PackageNv, + #[inherit] ChecksumIntegrityError, + ), + #[class(inherit)] #[error(transparent)] - PackageFormat(JsrPackageFormatError), + PackageFormat(#[inherit] JsrPackageFormatError), + #[class("NotFound")] #[error("Could not find version of '{}' that matches specified version constraint '{}'", .0.name, .0.version_req)] PackageReqNotFound(PackageReq), + #[class(generic)] #[error("Redirects in the JSR registry are not supported (redirected to '{}')", .0)] RedirectInPackage(ModuleSpecifier), + #[class("NotFound")] #[error("Unknown export '{}' for '{}'.\n Package exports:\n{}", export_name, .nv, .exports.iter().map(|e| format!(" * {}", e)).collect::>().join("\n"))] UnknownExport { nv: PackageNv, @@ -199,7 +217,8 @@ pub enum JsrLoadError { }, } -#[derive(Error, Debug, Clone)] +#[derive(Error, Debug, Clone, JsError)] +#[class(type)] pub enum JsrPackageFormatError { #[error(transparent)] JsrPackageParseError(PackageReqReferenceParseError), @@ -207,49 +226,79 @@ pub enum JsrPackageFormatError { VersionTagNotSupported, } -#[derive(Debug, Clone, Error)] +#[derive(Debug, Clone, Error, JsError)] pub enum NpmLoadError { + #[class(type)] #[error("npm specifiers are not supported in this environment")] NotSupportedEnvironment, + #[class(inherit)] #[error(transparent)] - PackageReqResolution(Arc), + PackageReqResolution(#[inherit] Arc), + #[class(inherit)] #[error(transparent)] - PackageReqReferenceParse(PackageReqReferenceParseError), + PackageReqReferenceParse(#[inherit] PackageReqReferenceParseError), + #[class(inherit)] #[error(transparent)] - RegistryInfo(Arc), + RegistryInfo(#[inherit] Arc), } -#[derive(Debug, Error, Clone)] +#[derive(Debug, Error, Clone, JsError)] pub enum ModuleLoadError { + #[class(inherit)] #[error(transparent)] - HttpsChecksumIntegrity(ChecksumIntegrityError), + HttpsChecksumIntegrity(#[inherit] ChecksumIntegrityError), + #[class(type)] // TODO: maybe inherit? #[error(transparent)] Decode(Arc), + #[class(inherit)] #[error(transparent)] - Loader(Arc), + Loader(#[inherit] Arc), + #[class(inherit)] #[error(transparent)] - Jsr(#[from] JsrLoadError), + Jsr( + #[from] + #[inherit] + JsrLoadError, + ), + #[class(inherit)] #[error(transparent)] - NodeUnknownBuiltinModule(#[from] UnknownBuiltInNodeModuleError), + NodeUnknownBuiltinModule( + #[from] + #[inherit] + UnknownBuiltInNodeModuleError, + ), + #[class(inherit)] #[error(transparent)] - Npm(#[from] NpmLoadError), + Npm( + #[from] + #[inherit] + NpmLoadError, + ), + #[class(generic)] #[error("Too many redirects.")] TooManyRedirects, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, JsError)] pub enum ModuleError { - LoadingErr(ModuleSpecifier, Option, ModuleLoadError), + #[class(inherit)] + LoadingErr(ModuleSpecifier, Option, #[inherit] ModuleLoadError), + #[class("NotFound")] Missing(ModuleSpecifier, Option), + #[class("NotFound")] MissingDynamic(ModuleSpecifier, Range), - ParseErr(ModuleSpecifier, deno_ast::ParseDiagnostic), + #[class(inherit)] + ParseErr(ModuleSpecifier, #[inherit] ParseDiagnostic), + #[class(type)] UnsupportedMediaType(ModuleSpecifier, MediaType, Option), + #[class(syntax)] InvalidTypeAssertion { specifier: ModuleSpecifier, range: Range, actual_media_type: MediaType, expected_media_type: MediaType, }, + #[class(type)] UnsupportedImportAttributeType { specifier: ModuleSpecifier, range: Range, @@ -328,11 +377,14 @@ impl fmt::Display for ModuleError { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, JsError)] pub enum ModuleGraphError { - ModuleError(ModuleError), - ResolutionError(ResolutionError), - TypesResolutionError(ResolutionError), + #[class(inherit)] + ModuleError(#[inherit] ModuleError), + #[class(inherit)] + ResolutionError(#[inherit] ResolutionError), + #[class(inherit)] + TypesResolutionError(#[inherit] ResolutionError), } impl ModuleGraphError { @@ -391,7 +443,8 @@ impl fmt::Display for ModuleGraphError { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, JsError)] +#[class(type)] pub enum ResolutionError { InvalidDowngrade { specifier: ModuleSpecifier, @@ -1593,7 +1646,7 @@ pub struct ModuleGraph { /// The result of resolving all npm dependencies of non-dynamic /// npm specifiers in the graph. #[serde(skip_serializing)] - pub npm_dep_graph_result: Result<(), Arc>, + pub npm_dep_graph_result: Result<(), Arc>, } impl ModuleGraph { @@ -2086,14 +2139,17 @@ fn resolve( } if let Some(npm_resolver) = maybe_npm_resolver { if npm_resolver.enables_bare_builtin_node_module() { - use import_map::ImportMapError; + use import_map::ImportMapErrorKind; use ResolveError::*; use SpecifierError::*; let res_ref = response.as_ref(); if matches!(res_ref, Err(Specifier(ImportPrefixMissing { .. }))) || matches!( res_ref, - Err(ImportMap(ImportMapError::UnmappedBareSpecifier(_, _))) + Err(ImportMap(error)) if matches!( + error.as_kind(), + ImportMapErrorKind::UnmappedBareSpecifier(_, _) + ) ) { if let Ok(specifier) = @@ -4835,7 +4891,7 @@ fn validate_jsr_specifier( struct NpmSpecifierBuildPendingInfo { found_pkg_nvs: IndexSet, module_slots: HashMap, - dependencies_resolution: Option>>, + dependencies_resolution: Option>>, redirects: HashMap, } diff --git a/src/lib.rs b/src/lib.rs index 52a83d6bd..c1419675c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1320,12 +1320,13 @@ console.log(a); referrer_range: &Range, _mode: ResolutionMode, ) -> Result { - use import_map::ImportMapError; + use import_map::ImportMapErrorKind; Err(source::ResolveError::ImportMap( - ImportMapError::UnmappedBareSpecifier( + ImportMapErrorKind::UnmappedBareSpecifier( specifier_text.to_string(), Some(referrer_range.specifier.to_string()), - ), + ) + .into_box(), )) } @@ -4331,13 +4332,13 @@ export function a(a: A): B { #[derive(Debug)] struct ExtResolver; - impl crate::source::Resolver for ExtResolver { + impl Resolver for ExtResolver { fn resolve( &self, specifier_text: &str, referrer_range: &Range, mode: ResolutionMode, - ) -> Result { + ) -> Result { let specifier_text = match mode { ResolutionMode::Types => format!("{}.d.ts", specifier_text), ResolutionMode::Execution => format!("{}.js", specifier_text), @@ -4518,20 +4519,25 @@ export function a(a: A): B { #[derive(Debug)] struct FailForTypesResolver; - impl crate::source::Resolver for FailForTypesResolver { + #[derive(Debug, thiserror::Error, deno_error::JsError)] + #[class(generic)] + #[error("Failed.")] + struct FailedError; + + impl Resolver for FailForTypesResolver { fn resolve( &self, specifier_text: &str, referrer_range: &Range, mode: ResolutionMode, - ) -> Result { + ) -> Result { match mode { ResolutionMode::Execution => { Ok(resolve_import(specifier_text, &referrer_range.specifier)?) } - ResolutionMode::Types => Err(crate::source::ResolveError::Other( - anyhow::anyhow!("Failed."), - )), + ResolutionMode::Types => { + Err(source::ResolveError::Other(Box::new(FailedError))) + } } } } diff --git a/src/source/mod.rs b/src/source/mod.rs index 35eb39c8c..6d86a1a1e 100644 --- a/src/source/mod.rs +++ b/src/source/mod.rs @@ -14,6 +14,7 @@ use deno_semver::package::PackageNv; use data_url::DataUrl; use deno_ast::ModuleSpecifier; +use deno_error::JsErrorClass; use deno_semver::package::PackageReq; use futures::future; use futures::future::LocalBoxFuture; @@ -77,18 +78,35 @@ pub enum LoadResponse { }, } -#[derive(Debug, Error)] +#[derive(Debug, Error, deno_error::JsError)] pub enum LoadError { + #[class(type)] #[error("Unsupported scheme: {0}")] UnsupportedScheme(String), + #[class(inherit)] #[error(transparent)] - ChecksumIntegrity(#[from] ChecksumIntegrityError), + ChecksumIntegrity( + #[from] + #[inherit] + ChecksumIntegrityError, + ), + #[class(inherit)] #[error(transparent)] - JsonParse(#[from] serde_json::Error), + JsonParse( + #[from] + #[inherit] + serde_json::Error, + ), + #[class(inherit)] #[error(transparent)] - DataUrl(std::io::Error), + DataUrl(#[inherit] std::io::Error), + #[class(inherit)] #[error(transparent)] - Other(#[from] anyhow::Error), + Other( + #[from] + #[inherit] + Arc, + ), } pub type LoadResult = Result, LoadError>; @@ -127,7 +145,8 @@ impl CacheSetting { pub static DEFAULT_JSR_URL: Lazy = Lazy::new(|| Url::parse("https://jsr.io").unwrap()); -#[derive(Debug, Clone, Error)] +#[derive(Debug, Clone, Error, deno_error::JsError)] +#[class(generic)] #[error("Integrity check failed.\n\nActual: {}\nExpected: {}", .actual, .expected )] pub struct ChecksumIntegrityError { @@ -369,14 +388,17 @@ pub fn recommended_registry_package_url_to_nv( }) } -#[derive(Error, Debug)] +#[derive(Error, Debug, deno_error::JsError)] pub enum ResolveError { + #[class(type)] #[error(transparent)] Specifier(#[from] SpecifierError), + #[class(inherit)] #[error(transparent)] ImportMap(#[from] import_map::ImportMapError), - #[error(transparent)] - Other(#[from] anyhow::Error), + #[class(inherit)] + #[error("{0}")] + Other(Box), } /// The kind of resolution currently being done by deno_graph. @@ -446,7 +468,8 @@ pub trait Resolver: fmt::Debug { } } -#[derive(Error, Debug, Clone)] +#[derive(Error, Debug, Clone, deno_error::JsError)] +#[class("NotFound")] #[error("Unknown built-in \"node:\" module: {module_name}")] pub struct UnknownBuiltInNodeModuleError { /// Name of the invalid module. @@ -463,7 +486,7 @@ pub struct NpmResolvePkgReqsResult { /// were resolved to NVs. /// /// Don't run dependency graph resolution if there are any individual failures. - pub dep_graph_result: Result<(), Arc>, + pub dep_graph_result: Result<(), Arc>, } #[async_trait(?Send)] @@ -578,7 +601,8 @@ fn get_mime_type_charset(mime_type: &str) -> Option<&str> { /// ahead of time. This is useful for testing or #[derive(Default)] pub struct MemoryLoader { - sources: HashMap>, + sources: + HashMap>>, cache_info: HashMap, } @@ -590,11 +614,11 @@ pub enum Source { }, Redirect(S), External(S), - Err(anyhow::Error), + Err(Arc), } impl> Source { - fn into_result(self) -> Result { + fn into_result(self) -> Result> { match self { Source::Module { specifier, @@ -714,7 +738,7 @@ impl Loader for MemoryLoader { ) -> LoadFuture { let response = match self.sources.get(specifier) { Some(Ok(response)) => Ok(Some(response.clone())), - Some(Err(err)) => Err(LoadError::Other(anyhow::anyhow!("{}", err))), + Some(Err(err)) => Err(LoadError::Other(err.clone())), None if specifier.scheme() == "data" => load_data_url(specifier), _ => Ok(None), }; diff --git a/tests/ecosystem_test.rs b/tests/ecosystem_test.rs index 764b32a0b..4f436bd5b 100644 --- a/tests/ecosystem_test.rs +++ b/tests/ecosystem_test.rs @@ -179,7 +179,9 @@ impl deno_graph::source::Loader for Loader<'_> { specifier: specifier.clone(), })), Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), - Err(err) => Err(anyhow::Error::from(err).into()), + Err(err) => Err(deno_graph::source::LoadError::Other( + std::sync::Arc::new(err), + )), } } "data" => deno_graph::source::load_data_url(specifier), diff --git a/tests/helpers/mod.rs b/tests/helpers/mod.rs index ce854d9d0..9fbcae414 100644 --- a/tests/helpers/mod.rs +++ b/tests/helpers/mod.rs @@ -130,9 +130,7 @@ impl NpmResolver for TestNpmResolver { name: pkg_req.name.clone(), version, }), - Err(err) => { - Err(NpmLoadError::PackageReqResolution(Arc::new(err.into()))) - } + Err(err) => Err(NpmLoadError::PackageReqResolution(Arc::new(err))), } }) .collect::>(), From bd9f8a97d040155fdb2b0202715e637972b98952 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 22 Nov 2024 16:13:01 +0100 Subject: [PATCH 06/11] update wasm_dep_analyzer --- Cargo.lock | 7 ++++--- Cargo.toml | 4 ++-- src/graph.rs | 3 ++- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 264607b51..14054cc99 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2771,11 +2771,12 @@ checksum = "4f186bd2dcf04330886ce82d6f33dd75a7bfcf69ecf5763b89fcde53b6ac9838" [[package]] name = "wasm_dep_analyzer" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f270206a91783fd90625c8bb0d8fbd459d0b1d1bf209b656f713f01ae7c04b8" +checksum = "2eeee3bdea6257cc36d756fa745a70f9d393571e47d69e0ed97581676a5369ca" dependencies = [ - "thiserror", + "deno_error", + "thiserror 2.0.3", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 499e32dda..c1bf5b5b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,6 @@ path = "tests/ecosystem_test.rs" harness = false [dependencies] -anyhow = "1.0.43" async-trait = "0.1.68" data-url = "0.3.0" deno_ast = { version = "0.44.0", features = ["dep_analysis", "emit"] } @@ -60,7 +59,7 @@ thiserror = "2" deno_error = "0.5.1" twox-hash = { version = "1.6.3", optional = true } url = { version = "2.5.3", features = ["serde"] } -wasm_dep_analyzer = "0.1.0" +wasm_dep_analyzer = "0.2.0" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] deno_unsync = { workspace = true, features = ["tokio"] } @@ -74,6 +73,7 @@ tempfile = "3.4.0" tokio = { version = "1.10.1", features = ["macros", "rt-multi-thread", "sync"] } deno_terminal = "0.2.0" env_logger = "0.11.3" +anyhow = "1.0.43" [profile.release] codegen-units = 1 diff --git a/src/graph.rs b/src/graph.rs index 06311d64a..88633cb82 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -290,7 +290,8 @@ pub enum ModuleError { MissingDynamic(ModuleSpecifier, Range), #[class(inherit)] ParseErr(ModuleSpecifier, #[inherit] ParseDiagnostic), - WasmParseErr(ModuleSpecifier, wasm_dep_analyzer::ParseError), + #[class(inherit)] + WasmParseErr(ModuleSpecifier, #[inherit] wasm_dep_analyzer::ParseError), #[class(type)] UnsupportedMediaType(ModuleSpecifier, MediaType, Option), #[class(syntax)] From 7bf272c305213d3d3ba1250b8395298c73a78fe6 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 22 Nov 2024 16:19:14 +0100 Subject: [PATCH 07/11] clean --- src/graph.rs | 38 +++++++++++++------------------------- src/source/mod.rs | 20 ++++---------------- 2 files changed, 17 insertions(+), 41 deletions(-) diff --git a/src/graph.rs b/src/graph.rs index 88633cb82..caf10db57 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -175,7 +175,7 @@ pub enum JsrLoadError { UnsupportedManifestChecksum, #[class(inherit)] #[error(transparent)] - ContentChecksumIntegrity(#[inherit] ChecksumIntegrityError), + ContentChecksumIntegrity(ChecksumIntegrityError), #[class(generic)] #[error("Loader should never return an external specifier for a jsr: specifier content load.")] ContentLoadExternalSpecifier, @@ -202,7 +202,7 @@ pub enum JsrLoadError { ), #[class(inherit)] #[error(transparent)] - PackageFormat(#[inherit] JsrPackageFormatError), + PackageFormat(JsrPackageFormatError), #[class("NotFound")] #[error("Could not find version of '{}' that matches specified version constraint '{}'", .0.name, .0.version_req)] PackageReqNotFound(PackageReq), @@ -234,47 +234,35 @@ pub enum NpmLoadError { NotSupportedEnvironment, #[class(inherit)] #[error(transparent)] - PackageReqResolution(#[inherit] Arc), + PackageReqResolution(Arc), #[class(inherit)] #[error(transparent)] - PackageReqReferenceParse(#[inherit] PackageReqReferenceParseError), + PackageReqReferenceParse(PackageReqReferenceParseError), #[class(inherit)] #[error(transparent)] - RegistryInfo(#[inherit] Arc), + RegistryInfo(Arc), } #[derive(Debug, Error, Clone, JsError)] pub enum ModuleLoadError { #[class(inherit)] #[error(transparent)] - HttpsChecksumIntegrity(#[inherit] ChecksumIntegrityError), + HttpsChecksumIntegrity(ChecksumIntegrityError), #[class(type)] // TODO: maybe inherit? #[error(transparent)] Decode(Arc), #[class(inherit)] #[error(transparent)] - Loader(#[inherit] Arc), + Loader(Arc), #[class(inherit)] #[error(transparent)] - Jsr( - #[from] - #[inherit] - JsrLoadError, - ), + Jsr(#[from] JsrLoadError), #[class(inherit)] #[error(transparent)] - NodeUnknownBuiltinModule( - #[from] - #[inherit] - UnknownBuiltInNodeModuleError, - ), + NodeUnknownBuiltinModule(#[from] UnknownBuiltInNodeModuleError), #[class(inherit)] #[error(transparent)] - Npm( - #[from] - #[inherit] - NpmLoadError, - ), + Npm(#[from] NpmLoadError), #[class(generic)] #[error("Too many redirects.")] TooManyRedirects, @@ -387,11 +375,11 @@ impl fmt::Display for ModuleError { #[derive(Debug, Clone, JsError)] pub enum ModuleGraphError { #[class(inherit)] - ModuleError(#[inherit] ModuleError), + ModuleError(ModuleError), #[class(inherit)] - ResolutionError(#[inherit] ResolutionError), + ResolutionError(ResolutionError), #[class(inherit)] - TypesResolutionError(#[inherit] ResolutionError), + TypesResolutionError(ResolutionError), } impl ModuleGraphError { diff --git a/src/source/mod.rs b/src/source/mod.rs index 3b26eb240..6e2dbcef6 100644 --- a/src/source/mod.rs +++ b/src/source/mod.rs @@ -86,28 +86,16 @@ pub enum LoadError { UnsupportedScheme(String), #[class(inherit)] #[error(transparent)] - ChecksumIntegrity( - #[from] - #[inherit] - ChecksumIntegrityError, - ), + ChecksumIntegrity(#[from] ChecksumIntegrityError), #[class(inherit)] #[error(transparent)] - JsonParse( - #[from] - #[inherit] - serde_json::Error, - ), + JsonParse(#[from] serde_json::Error), #[class(inherit)] #[error(transparent)] - DataUrl(#[inherit] std::io::Error), + DataUrl(std::io::Error), #[class(inherit)] #[error(transparent)] - Other( - #[from] - #[inherit] - Arc, - ), + Other(#[from] Arc), } pub type LoadResult = Result, LoadError>; From bd989abb5b4c6eae56b27d2978ca2fc0fdb1940b Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 22 Nov 2024 16:32:19 +0100 Subject: [PATCH 08/11] box packagenv in error cases --- Cargo.lock | 1 + Cargo.toml | 1 + src/graph.rs | 10 +++++----- src/jsr.rs | 7 ++++--- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 14054cc99..5d9c76649 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -421,6 +421,7 @@ dependencies = [ "anyhow", "async-trait", "bincode", + "boxed_error", "data-url", "deno_ast", "deno_error", diff --git a/Cargo.toml b/Cargo.toml index c1bf5b5b1..f0f558c9d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,6 +57,7 @@ serde_json = { version = "1.0.67", features = ["preserve_order"] } sha2 = "^0.10.0" thiserror = "2" deno_error = "0.5.1" +boxed_error = "0.2.3" twox-hash = { version = "1.6.3", optional = true } url = { version = "2.5.3", features = ["serde"] } wasm_dep_analyzer = "0.2.0" diff --git a/src/graph.rs b/src/graph.rs index caf10db57..47c7cf46b 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -190,14 +190,14 @@ pub enum JsrLoadError { PackageNotFound(String), #[class("NotFound")] #[error("JSR package version not found: {}", .0)] - PackageVersionNotFound(PackageNv), + PackageVersionNotFound(Box), #[class(generic)] // TODO: maybe inherit? #[error("JSR package version manifest for '{}' failed to load: {:#}", .0, .1)] - PackageVersionManifestLoad(PackageNv, Arc), + PackageVersionManifestLoad(Box, Arc), #[class(inherit)] #[error("JSR package version manifest for '{}' failed to load: {:#}", .0, .1)] PackageVersionManifestChecksumIntegrity( - PackageNv, + Box, #[inherit] ChecksumIntegrityError, ), #[class(inherit)] @@ -212,7 +212,7 @@ pub enum JsrLoadError { #[class("NotFound")] #[error("Unknown export '{}' for '{}'.\n Package exports:\n{}", export_name, .nv, .exports.iter().map(|e| format!(" * {}", e)).collect::>().join("\n"))] UnknownExport { - nv: PackageNv, + nv: Box, export_name: String, exports: Vec, }, @@ -3782,7 +3782,7 @@ impl<'a, 'graph> Builder<'a, 'graph> { resolution_item.maybe_range, JsrLoadError::UnknownExport { export_name: export_name.to_string(), - nv: resolution_item.nv_ref.into_inner().nv, + nv: Box::new(resolution_item.nv_ref.into_inner().nv), exports: version_info .exports() .map(|(k, _)| k.to_string()) diff --git a/src/jsr.rs b/src/jsr.rs index 7b8a97e18..8cef927e8 100644 --- a/src/jsr.rs +++ b/src/jsr.rs @@ -159,11 +159,12 @@ impl JsrMetadataStore { // use a more specific variant in order to allow the // cli to enhance this error message JsrLoadError::PackageVersionManifestChecksumIntegrity( - package_nv, err, + Box::new(package_nv), + err, ) } err => JsrLoadError::PackageVersionManifestLoad( - package_nv, + Box::new(package_nv), Arc::new(err), ), } @@ -171,7 +172,7 @@ impl JsrMetadataStore { }, { let package_nv = package_nv.clone(); - || JsrLoadError::PackageVersionNotFound(package_nv) + || JsrLoadError::PackageVersionNotFound(Box::new(package_nv)) }, ); self From 1a558dcacfcab20bff0b85e518f514d073e42e86 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 22 Nov 2024 16:32:45 +0100 Subject: [PATCH 09/11] clean --- Cargo.lock | 1 - Cargo.toml | 1 - 2 files changed, 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d9c76649..14054cc99 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -421,7 +421,6 @@ dependencies = [ "anyhow", "async-trait", "bincode", - "boxed_error", "data-url", "deno_ast", "deno_error", diff --git a/Cargo.toml b/Cargo.toml index f0f558c9d..c1bf5b5b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,7 +57,6 @@ serde_json = { version = "1.0.67", features = ["preserve_order"] } sha2 = "^0.10.0" thiserror = "2" deno_error = "0.5.1" -boxed_error = "0.2.3" twox-hash = { version = "1.6.3", optional = true } url = { version = "2.5.3", features = ["serde"] } wasm_dep_analyzer = "0.2.0" From 3e905fcaa2f8e39082e5dc36207a05b339c33a92 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 22 Nov 2024 16:49:40 +0100 Subject: [PATCH 10/11] fix wasm --- Cargo.lock | 3 ++- Cargo.toml | 6 ++++-- lib/Cargo.toml | 3 ++- lib/lib.rs | 31 +++++++++++++++++++++++-------- src/source/mod.rs | 14 +++++++++++++- 5 files changed, 44 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 14054cc99..d769491bb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -455,8 +455,8 @@ dependencies = [ name = "deno_graph_wasm" version = "0.0.0" dependencies = [ - "anyhow", "console_error_panic_hook", + "deno_error", "deno_graph", "futures", "getrandom", @@ -465,6 +465,7 @@ dependencies = [ "serde", "serde-wasm-bindgen", "serde_json", + "thiserror 2.0.3", "wasm-bindgen", "wasm-bindgen-futures", ] diff --git a/Cargo.toml b/Cargo.toml index c1bf5b5b1..f8f6e26a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,8 @@ members = ["lib"] [workspace.dependencies] deno_unsync = { version = "0.4.0", default-features = false } +thiserror = "2" +deno_error = "0.5.1" [lib] name = "deno_graph" @@ -55,8 +57,8 @@ regex = "1.10.2" serde = { version = "1.0.130", features = ["derive", "rc"] } serde_json = { version = "1.0.67", features = ["preserve_order"] } sha2 = "^0.10.0" -thiserror = "2" -deno_error = "0.5.1" +thiserror.workspace = true +deno_error.workspace = true twox-hash = { version = "1.6.3", optional = true } url = { version = "2.5.3", features = ["serde"] } wasm_dep_analyzer = "0.2.0" diff --git a/lib/Cargo.toml b/lib/Cargo.toml index 1bfdd93d4..75a82e36b 100644 --- a/lib/Cargo.toml +++ b/lib/Cargo.toml @@ -14,7 +14,6 @@ path = "lib.rs" crate-type = ["cdylib"] [dependencies] -anyhow = "1.0.43" console_error_panic_hook = "0.1.7" deno_graph = { path = "../", default-features = false } getrandom = { version = "*", features = ["js"] } @@ -25,6 +24,8 @@ serde_json = { version = "1.0.67", features = ["preserve_order"] } serde-wasm-bindgen = "0.5.0" wasm-bindgen = { version = "=0.2.91" } wasm-bindgen-futures = { version = "=0.4.41" } +thiserror.workspace = true +deno_error.workspace = true [dev-dependencies] pretty_assertions = "1.0.0" diff --git a/lib/lib.rs b/lib/lib.rs index 7ed3b905f..feb4fad15 100644 --- a/lib/lib.rs +++ b/lib/lib.rs @@ -5,8 +5,6 @@ #![deny(clippy::disallowed_methods)] #![deny(clippy::disallowed_types)] -use std::collections::HashMap; - use deno_graph::resolve_import; use deno_graph::source::load_data_url; use deno_graph::source::CacheInfo; @@ -25,13 +23,28 @@ use deno_graph::ModuleSpecifier; use deno_graph::Range; use deno_graph::ReferrerImports; use deno_graph::SpecifierError; +use std::collections::HashMap; +use std::sync::Arc; -use anyhow::anyhow; use futures::future; use serde::Deserialize; use serde::Serialize; use wasm_bindgen::prelude::*; +#[derive(Debug, thiserror::Error, deno_error::JsError)] +#[class(generic)] +pub enum WasmError { + #[error("load rejected or errored")] + Load, + #[error("JavaScript resolve threw.")] + JavaScriptResolve, + #[error("JavaScript resolveTypes() function threw.")] + JavaScriptResolveTypes, + #[error("{0}")] + // String because serde_wasm_bindgen::Error is not thread-safe. + Deserialize(String), +} + pub struct JsLoader { load: js_sys::Function, maybe_cache_info: Option, @@ -100,7 +113,7 @@ impl Loader for JsLoader { }; response .map(|value| serde_wasm_bindgen::from_value(value).unwrap()) - .map_err(|_| anyhow!("load rejected or errored").into()) + .map_err(|_| Arc::new(WasmError::Load).into()) }; Box::pin(f) } @@ -168,11 +181,13 @@ impl Resolver for JsResolver { let arg2 = JsValue::from(referrer_range.specifier.to_string()); let value = match resolve.call2(&this, &arg1, &arg2) { Ok(value) => value, - Err(_) => return Err(anyhow!("JavaScript resolve threw.").into()), + Err(_) => return Err(Box::new(WasmError::JavaScriptResolve).into()), }; let value: String = match serde_wasm_bindgen::from_value(value) { Ok(value) => value, - Err(err) => return Err(anyhow!("{}", err.to_string()).into()), + Err(err) => { + return Err(Box::new(WasmError::Deserialize(err.to_string())).into()) + } }; ModuleSpecifier::parse(&value) .map_err(|err| ResolveError::Specifier(SpecifierError::InvalidUrl(err))) @@ -191,10 +206,10 @@ impl Resolver for JsResolver { let arg1 = JsValue::from(specifier.to_string()); let value = resolve_types .call1(&this, &arg1) - .map_err(|_| anyhow!("JavaScript resolveTypes() function threw."))?; + .map_err(|_| Box::new(WasmError::JavaScriptResolveTypes))?; let result: Option = serde_wasm_bindgen::from_value(value) - .map_err(|err| anyhow!("{}", err.to_string()))?; + .map_err(|err| Box::new(WasmError::Deserialize(err.to_string())))?; Ok(result.map(|v| (v.types, v.source))) } else { Ok(None) diff --git a/src/source/mod.rs b/src/source/mod.rs index 6e2dbcef6..4fcafc7f0 100644 --- a/src/source/mod.rs +++ b/src/source/mod.rs @@ -95,7 +95,13 @@ pub enum LoadError { DataUrl(std::io::Error), #[class(inherit)] #[error(transparent)] - Other(#[from] Arc), + Other(Arc), +} + +impl From> for LoadError { + fn from(value: Arc) -> Self { + Self::Other(value) + } } pub type LoadResult = Result, LoadError>; @@ -390,6 +396,12 @@ pub enum ResolveError { Other(Box), } +impl From> for ResolveError { + fn from(value: Box) -> Self { + Self::Other(value) + } +} + /// The kind of resolution currently being done by deno_graph. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ResolutionMode { From 54a60082af04e7d911aea31bf6abad1cd545aabe Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 22 Nov 2024 16:57:48 +0100 Subject: [PATCH 11/11] add unnecessary_wraps --- Cargo.lock | 1 - Cargo.toml | 1 - lib/lib.rs | 1 + src/fast_check/transform_dts.rs | 36 ++++++++++++++------------------- src/graph.rs | 21 +++++++++---------- src/lib.rs | 7 +++++-- tests/ecosystem_test.rs | 5 +---- tests/helpers/mod.rs | 6 +++--- tests/specs_test.rs | 17 ++++++++-------- 9 files changed, 42 insertions(+), 53 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d769491bb..e96f50fa6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -418,7 +418,6 @@ dependencies = [ name = "deno_graph" version = "0.85.1" dependencies = [ - "anyhow", "async-trait", "bincode", "data-url", diff --git a/Cargo.toml b/Cargo.toml index f8f6e26a6..aab82c61d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -75,7 +75,6 @@ tempfile = "3.4.0" tokio = { version = "1.10.1", features = ["macros", "rt-multi-thread", "sync"] } deno_terminal = "0.2.0" env_logger = "0.11.3" -anyhow = "1.0.43" [profile.release] codegen-units = 1 diff --git a/lib/lib.rs b/lib/lib.rs index feb4fad15..cde06adfa 100644 --- a/lib/lib.rs +++ b/lib/lib.rs @@ -4,6 +4,7 @@ #![allow(clippy::unused_unit)] #![deny(clippy::disallowed_methods)] #![deny(clippy::disallowed_types)] +#![deny(clippy::unnecessary_wraps)] use deno_graph::resolve_import; use deno_graph::source::load_data_url; diff --git a/src/fast_check/transform_dts.rs b/src/fast_check/transform_dts.rs index fd0b2c374..8f1a1b86f 100644 --- a/src/fast_check/transform_dts.rs +++ b/src/fast_check/transform_dts.rs @@ -47,19 +47,13 @@ impl FastCheckDtsDiagnostic { } } - pub fn range(&self) -> Option<&FastCheckDiagnosticRange> { + pub fn range(&self) -> &FastCheckDiagnosticRange { match self { - FastCheckDtsDiagnostic::UnableToInferType { range } => Some(range), - FastCheckDtsDiagnostic::UnableToInferTypeFallbackAny { range } => { - Some(range) - } - FastCheckDtsDiagnostic::UnableToInferTypeFromProp { range } => { - Some(range) - } - FastCheckDtsDiagnostic::UnableToInferTypeFromSpread { range } => { - Some(range) - } - FastCheckDtsDiagnostic::UnsupportedUsing { range } => Some(range), + FastCheckDtsDiagnostic::UnableToInferType { range } => range, + FastCheckDtsDiagnostic::UnableToInferTypeFallbackAny { range } => range, + FastCheckDtsDiagnostic::UnableToInferTypeFromProp { range } => range, + FastCheckDtsDiagnostic::UnableToInferTypeFromSpread { range } => range, + FastCheckDtsDiagnostic::UnsupportedUsing { range } => range, } } } @@ -756,14 +750,14 @@ impl<'a> FastCheckDtsTransformer<'a> { expr: Expr, as_const: bool, as_readonly: bool, - ) -> Option> { + ) -> Box { if let Some(ts_type) = self.expr_to_ts_type(expr.clone(), as_const, as_readonly) { - Some(type_ann(ts_type)) + type_ann(ts_type) } else { self.mark_diagnostic_any_fallback(expr.range()); - Some(any_type_ann()) + any_type_ann() } } @@ -915,11 +909,11 @@ impl<'a> FastCheckDtsTransformer<'a> { match &mut *assign_pat.left { Pat::Ident(ident) => { if ident.type_ann.is_none() { - ident.type_ann = self.infer_expr_fallback_any( + ident.type_ann = Some(self.infer_expr_fallback_any( *assign_pat.right.clone(), false, false, - ); + )); } ident.optional = true; @@ -927,11 +921,11 @@ impl<'a> FastCheckDtsTransformer<'a> { } Pat::Array(arr_pat) => { if arr_pat.type_ann.is_none() { - arr_pat.type_ann = self.infer_expr_fallback_any( + arr_pat.type_ann = Some(self.infer_expr_fallback_any( *assign_pat.right.clone(), false, false, - ); + )); } arr_pat.optional = true; @@ -939,11 +933,11 @@ impl<'a> FastCheckDtsTransformer<'a> { } Pat::Object(obj_pat) => { if obj_pat.type_ann.is_none() { - obj_pat.type_ann = self.infer_expr_fallback_any( + obj_pat.type_ann = Some(self.infer_expr_fallback_any( *assign_pat.right.clone(), false, false, - ); + )); } obj_pat.optional = true; diff --git a/src/graph.rs b/src/graph.rs index 47c7cf46b..704ddc4fb 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -2470,15 +2470,15 @@ pub(crate) fn parse_module( maybe_resolver: Option<&dyn Resolver>, maybe_npm_resolver: Option<&dyn NpmResolver>, options: ParseModuleOptions, -) -> Result { +) -> Module { match options.module_source_and_info { ModuleSourceAndInfo::Json { specifier, source } => { - Ok(Module::Json(JsonModule { + Module::Json(JsonModule { maybe_cache_info: None, source, media_type: MediaType::Json, specifier, - })) + }) } ModuleSourceAndInfo::Js { specifier, @@ -2486,7 +2486,7 @@ pub(crate) fn parse_module( source, maybe_headers, module_info, - } => Ok(Module::Js(parse_js_module_from_module_info( + } => Module::Js(parse_js_module_from_module_info( options.graph_kind, specifier, media_type, @@ -2497,13 +2497,13 @@ pub(crate) fn parse_module( jsr_url_provider, maybe_resolver, maybe_npm_resolver, - ))), + )), ModuleSourceAndInfo::Wasm { specifier, source, source_dts, module_info, - } => Ok(Module::Wasm(parse_wasm_module_from_module_info( + } => Module::Wasm(parse_wasm_module_from_module_info( options.graph_kind, specifier, *module_info, @@ -2513,7 +2513,7 @@ pub(crate) fn parse_module( jsr_url_provider, maybe_resolver, maybe_npm_resolver, - ))), + )), } } @@ -4887,7 +4887,7 @@ impl<'a, 'graph> Builder<'a, 'graph> { module_source_and_info: ModuleSourceAndInfo, maybe_version_info: Option<&JsrPackageVersionInfoExt>, ) -> ModuleSlot { - let parse_module_result = parse_module( + let module = parse_module( self.file_system, self.jsr_url_provider, self.resolver, @@ -4898,10 +4898,7 @@ impl<'a, 'graph> Builder<'a, 'graph> { }, ); - let mut module_slot = match parse_module_result { - Ok(module) => ModuleSlot::Module(module), - Err(err) => ModuleSlot::Err(err), - }; + let mut module_slot = ModuleSlot::Module(module); match &mut module_slot { ModuleSlot::Module(Module::Js(module)) => { diff --git a/src/lib.rs b/src/lib.rs index 4f4b061ae..556ea506a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,7 @@ #![deny(clippy::print_stderr)] #![deny(clippy::print_stdout)] #![deny(clippy::unused_async)] +#![deny(clippy::unnecessary_wraps)] mod analyzer; mod ast; @@ -140,7 +141,7 @@ pub async fn parse_module( }, ) .await?; - graph::parse_module( + let module = graph::parse_module( options.file_system, options.jsr_url_provider, options.maybe_resolver, @@ -149,7 +150,9 @@ pub async fn parse_module( graph_kind: options.graph_kind, module_source_and_info, }, - ) + ); + + Ok(module) } pub struct ParseModuleFromAstOptions<'a> { diff --git a/tests/ecosystem_test.rs b/tests/ecosystem_test.rs index 4f436bd5b..28cc77e3c 100644 --- a/tests/ecosystem_test.rs +++ b/tests/ecosystem_test.rs @@ -2,7 +2,6 @@ use std::collections::HashSet; use std::io::Write as _; use std::path::PathBuf; -use anyhow::Context; use deno_ast::diagnostics::Diagnostic; use deno_ast::MediaType; use deno_graph::source::LoadResponse; @@ -376,9 +375,7 @@ async fn test_version( if let Some(fcm) = module.fast_check_module() { let path = format!("{}{}", tmpdir_path.display(), module.specifier.path()); - std::fs::write(&path, fcm.source.as_bytes()) - .with_context(|| format!("failed writing {}", path)) - .unwrap(); + std::fs::write(&path, fcm.source.as_bytes()).unwrap(); } } } diff --git a/tests/helpers/mod.rs b/tests/helpers/mod.rs index 9fbcae414..5c5a6fdb4 100644 --- a/tests/helpers/mod.rs +++ b/tests/helpers/mod.rs @@ -333,7 +333,7 @@ impl TestBuilder { #[allow(unused)] #[cfg(feature = "symbols")] - pub async fn symbols(&mut self) -> anyhow::Result { + pub async fn symbols(&mut self) -> symbols::SymbolsResult { fn check_fatal_diagnostics( module: deno_graph::symbols::ModuleInfoRef, ) -> Vec { @@ -449,7 +449,7 @@ impl TestBuilder { let entry_point_types_url = ModuleSpecifier::parse(&self.entry_point_types).unwrap(); let root_symbol = build_result.root_symbol(); - Ok(symbols::SymbolsResult { + symbols::SymbolsResult { output: { let entrypoint_symbol = root_symbol .module_from_specifier(&entry_point_types_url) @@ -590,7 +590,7 @@ impl TestBuilder { } output_text }, - }) + } } } diff --git a/tests/specs_test.rs b/tests/specs_test.rs index 2523a908a..f23e16660 100644 --- a/tests/specs_test.rs +++ b/tests/specs_test.rs @@ -200,14 +200,13 @@ fn run_graph_test(test: &CollectedTest) { let message = dts .diagnostics .iter() - .map(|d| match d.range() { - Some(range) => { - format!( - "{}\n at {}@{}", - d, range.specifier, range.range.start - ) - } - None => format!("{}\n at {}", d, d.specifier()), + .map(|d| { + let range = d.range(); + + format!( + "{}\n at {}@{}", + d, range.specifier, range.range.start + ) }) .collect::>() .join("\n\n"); @@ -292,7 +291,7 @@ fn run_symbol_test(test: &CollectedTest) { .enable_all() .build() .unwrap(); - let result = rt.block_on(async { builder.symbols().await.unwrap() }); + let result = rt.block_on(async { builder.symbols().await }); let spec = if std::env::var("UPDATE").as_deref() == Ok("1") { let mut spec = spec; spec.output_file.text.clone_from(&result.output);