use std::{ borrow::Cow, hash::{Hash, Hasher}, path::Path, sync::Arc, }; use serde::{Deserialize, Serialize}; use url::Url; use crate::{Diagnostic, PathId}; #[derive(PartialEq, Eq, Debug, Default, Clone, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SourceLocation { /// URL to the location of the file. pub url: SourceUrl, /// Line and column offset of the start of the location within the file. pub start: Location, /// Line and column offset of the end of the location within the file. pub end: Location, } impl SourceLocation { pub fn stable_hash(&self, project_root: &PathId, state: &mut H) { self.url.stable_hash(project_root, state); self.start.hash(state); self.end.hash(state); } } #[derive(PartialEq, Eq, Debug, Default, Clone, Hash, Serialize, Deserialize)] pub struct Location { #[serde(default)] pub line: u32, #[serde(default)] pub column: u32, } /// A source location backed by either an interned file path or a fallback URL for non-file schemes. /// File-backed source URLs keep the original path internally. Portable project-relative URLs are /// derived on demand for stable hashes and other output-facing identities. #[derive(PartialEq, Eq, Clone, Hash)] pub enum SourceUrl { Path { path: PathId, query: Option>, is_directory: bool, }, Url(Arc), } impl serde::Serialize for SourceUrl { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { self.to_string().serialize(serializer) } } impl<'de> serde::Deserialize<'de> for SourceUrl { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { let url: &str = Deserialize::deserialize(deserializer)?; SourceUrl::parse(url).map_err(|e| serde::de::Error::custom(e.message)) } } impl Default for SourceUrl { fn default() -> Self { SourceUrl::from_path(&PathId::new(Path::new("/default"))) } } impl SourceUrl { pub fn parse(url: &str) -> Result { let parsed = Url::parse(url).map_err(|err| { Diagnostic::from_message(format!("Could not parse url {:?} {}", url, err.to_string())) })?; let is_directory = parsed.path().ends_with('/'); let query = parsed.query().map(Arc::from); match parsed.scheme() { "file" => parsed .to_file_path() .map(|path| SourceUrl::Path { path: PathId::new(&path), query, is_directory, }) .map_err(|_| { Diagnostic::from_message(format!( "Could not convert file URL to path: {:?}", parsed.as_str() )) }), _ => Ok(SourceUrl::Url(Arc::new(parsed))), } } /// Creates a file-backed `SourceUrl` from a file path. pub fn from_path(path: &PathId) -> SourceUrl { SourceUrl::Path { path: *path, query: None, is_directory: false, } } /// Creates a `SourceUrl` from a directory path (URL will have a trailing slash). pub fn from_directory_path(path: &PathId) -> SourceUrl { SourceUrl::Path { path: *path, query: None, is_directory: true, } } fn project_relative_slash_path(&self, project_root: &PathId) -> Option { match self { SourceUrl::Path { path, .. } => path.slash_path_below(*project_root), SourceUrl::Url(_) => None, } } pub fn stable_id(&self, project_root: &PathId) -> String { if let Some(mut path) = self.project_relative_slash_path(project_root) { if !path.starts_with('/') { path.insert(0, '/'); } if path == "/" && !self.is_directory() { path.clear(); path.push('/'); } let mut res = format!("project://{}", path); if self.is_directory() && !res.ends_with('/') { res.push('/'); } if let Some(query) = self.query() { res.push('?'); res.push_str(query); } res } else { self.to_string() } } pub fn stable_hash(&self, project_root: &PathId, state: &mut H) { let id = self.stable_id(project_root); // A `Url` hashes its serialization, so an id that parsing would leave unchanged hashes the same // without paying for the parse (asset ids are computed often while packaging). if is_normalized_project_url(&id) { debug_assert_eq!(Url::parse(&id).unwrap().as_str(), id); id.hash(state); } else { Url::parse(&id) .expect("SourceUrl stable id should be a valid URL") .hash(state); } } /// Creates a file-backed `SourceUrl` from an absolute file path and optional query string. pub fn from_path_and_query(path: &PathId, query: Option<&str>) -> SourceUrl { let base = SourceUrl::from_path(path); if query.is_none() { return base; } base.with_query(query) } pub fn with_query(&self, query: Option<&str>) -> SourceUrl { let query = query.map(Arc::from); match self { SourceUrl::Path { path, is_directory, .. } => SourceUrl::Path { path: *path, query, is_directory: *is_directory, }, SourceUrl::Url(url) => { let mut url = (**url).clone(); url.set_query(query.as_deref()); SourceUrl::Url(Arc::new(url)) } } } /// Converts the source URL to a file system path. Fallback non-file URLs cannot be converted. pub fn to_file_path(&self) -> Result { match self { SourceUrl::Path { path, .. } => Ok(*path), SourceUrl::Url(url) => url.to_file_path().map(|p| PathId::new(&p)).map_err(|_| { Diagnostic::from_message(format!( "Could not convert SourceUrl to file path: {:?}", url.as_str() )) }), } } pub fn to_string(&self) -> String { match self { SourceUrl::Path { path, query, is_directory, } => { let mut url = if *is_directory { Url::from_directory_path(path.to_path_buf()).unwrap() } else { Url::from_file_path(path.to_path_buf()).unwrap() }; url.set_query(query.as_deref()); url.to_string() } SourceUrl::Url(url) => url.to_string(), } } pub fn extension(&self) -> &str { match self { SourceUrl::Path { path, .. } => path.extension().unwrap_or(""), SourceUrl::Url(url) => { let path = url.path(); let (_, ext) = path.rsplit_once('.').unwrap_or((path, "")); ext } } } pub fn query(&self) -> Option<&str> { match self { SourceUrl::Path { query, .. } => query.as_deref(), SourceUrl::Url(url) => url.query(), } } pub fn query_pairs(&self) -> Box, Cow<'_, str>)> + '_> { match self { SourceUrl::Path { query, .. } => Box::new(url::form_urlencoded::parse( query.as_deref().unwrap_or("").as_bytes(), )), SourceUrl::Url(url) => Box::new(url.query_pairs()), } } fn is_directory(&self) -> bool { match self { SourceUrl::Path { is_directory, .. } => *is_directory, SourceUrl::Url(url) => url.path().ends_with('/'), } } /// Returns a relative URL string from `from` to `self` when both can be represented as URLs. pub fn relative(&self, from: &SourceUrl) -> Option { let from_url = Url::parse(&from.to_string()).ok()?; let self_url = Url::parse(&self.to_string()).ok()?; if let Some(rel) = from_url.make_relative(&self_url) { return Some(rel); } None } pub fn join(&self, other: &str) -> SourceUrl { let url = Url::parse(&self.to_string()).unwrap().join(other).unwrap(); SourceUrl::parse(url.as_str()).unwrap() } } impl std::fmt::Display for SourceUrl { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.to_string().fmt(f) } } impl std::fmt::Debug for SourceUrl { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.to_string().fmt(f) } } /// Whether `Url::parse` serializes `id` unchanged: a `project:` URL without a query whose path has /// no characters that would be percent-encoded and no dot segments that would be removed. fn is_normalized_project_url(id: &str) -> bool { let Some(path) = id.strip_prefix("project://") else { return false; }; path.starts_with('/') && path.bytes().all(|b| { b.is_ascii_alphanumeric() || matches!(b, b'/' | b'-' | b'_' | b'.' | b'~' | b'@' | b'+') }) && path .split('/') .all(|segment| segment != "." && segment != "..") } #[cfg(test)] mod tests { use super::*; use crate::test_utils::{path as test_path, url as test_url}; use std::hash::{DefaultHasher, Hasher}; fn make_root(path: &str) -> PathId { PathId::new(test_path(path).as_path()) } fn make_path(path: &str) -> PathId { PathId::new(test_path(path).as_path()) } #[test] fn default_url_is_an_absolute_file_url() { let url = SourceUrl::default(); assert!(url.to_file_path().unwrap().to_path_buf().is_absolute()); assert_eq!(SourceUrl::parse(&url.to_string()).unwrap(), url); } #[test] fn test_from_path_within_project() { let url = SourceUrl::from_path(&make_path("/home/user/project/src/foo.js")); assert_eq!( url.to_string(), test_url("file:///home/user/project/src/foo.js").as_str() ); } #[test] fn test_from_path_outside_project() { let url = SourceUrl::from_path(&make_path("/usr/lib/node_modules/foo.js")); assert_eq!( url.to_string(), test_url("file:///usr/lib/node_modules/foo.js").as_str() ); } #[test] fn test_from_path_is_project_root() { let url = SourceUrl::from_path(&make_path("/home/user/project")); assert_eq!( url.to_string(), test_url("file:///home/user/project").as_str() ); } #[test] fn test_from_directory_path_within_project() { let url = SourceUrl::from_directory_path(&make_path("/home/user/project/src")); assert_eq!( url.to_string(), test_url("file:///home/user/project/src/").as_str() ); } #[test] fn test_from_directory_path_is_project_root() { let url = SourceUrl::from_directory_path(&make_path("/home/user/project")); assert_eq!( url.to_string(), test_url("file:///home/user/project/").as_str() ); } #[test] fn test_from_directory_path_outside_project() { let url = SourceUrl::from_directory_path(&make_path("/usr/lib")); assert_eq!(url.to_string(), test_url("file:///usr/lib/").as_str()); } #[test] fn test_to_file_path_file_url() { let url = SourceUrl::parse(test_url("file:///usr/lib/foo.js").as_str()).unwrap(); let path = url.to_file_path().unwrap(); assert_eq!(path.to_path_buf(), test_path("/usr/lib/foo.js").as_path()); } #[test] fn test_roundtrip_within_project() { let original = test_path("/home/user/project/src/foo.js"); let url = SourceUrl::from_path(&PathId::new(&original)); let path = url.to_file_path().unwrap(); assert_eq!(path.to_path_buf(), original); } #[test] fn test_roundtrip_outside_project() { let original = test_path("/usr/lib/node_modules/foo.js"); let url = SourceUrl::from_path(&PathId::new(&original)); let path = url.to_file_path().unwrap(); assert_eq!(path.to_path_buf(), original); } #[test] fn test_hash_portability() { // Same relative paths in different absolute project roots should produce the same hash. let root1 = make_root("/home/user1/project"); let root2 = make_root("/home/user2/different_project"); let url1 = SourceUrl::from_path(&make_path("/home/user1/project/src/foo.js")); let url2 = SourceUrl::from_path(&make_path("/home/user2/different_project/src/foo.js")); let mut h1 = DefaultHasher::new(); let mut h2 = DefaultHasher::new(); url1.stable_hash(&root1, &mut h1); url2.stable_hash(&root2, &mut h2); assert_eq!(h1.finish(), h2.finish()); } #[test] fn test_from_path_and_query() { let url = SourceUrl::from_path_and_query( &make_path("/home/user/project/src/foo.js"), Some("transform=true"), ); assert_eq!( url.to_string(), test_url("file:///home/user/project/src/foo.js?transform=true").as_str() ); assert_eq!(url.query(), Some("transform=true")); } #[test] fn test_from_path_and_query_to_file_path() { let url = SourceUrl::from_path_and_query( &make_path("/home/user/project/src/foo.js"), Some("transform=true"), ); let path = url.to_file_path().unwrap(); assert_eq!( path.to_path_buf(), test_path("/home/user/project/src/foo.js").as_path() ); } #[test] fn test_with_percent_encoded_path() { let url = SourceUrl::from_path(&make_path("/home/user/project/src/foo bar.js")); // URL should be percent-encoded assert!(url.to_string().contains("foo%20bar") || url.to_string().contains("foo bar")); let path = url.to_file_path().unwrap(); assert_eq!( path.to_path_buf(), test_path("/home/user/project/src/foo bar.js").as_path() ); } #[test] fn test_extension() { let url = SourceUrl::from_path(&make_path("/home/user/project/src/foo.js")); assert_eq!(url.extension(), "js"); } #[test] fn normalized_project_urls_match_parsed_serialization() { for id in [ "project:///", "project:///src/foo.js", "project:///node_modules/@scope/pkg-name/dist/index.min.js", "project:///a_b/c~d/e+f/g.h.i", "project:///dist/", "project:///.parcel-cache/x", ] { assert!(is_normalized_project_url(id), "{id}"); assert_eq!(Url::parse(id).unwrap().as_str(), id); } for id in [ "project:///a/./b", "project:///a/../b", "project:///a/..", "project:///a b", "project:///a?q", "project:///a#b", "project:///caf\u{e9}", "project:///a%2e", "file:///a", ] { assert!(!is_normalized_project_url(id), "{id}"); } } }