use std::error::Error;
use std::fmt;
use std::path::PathBuf;
use url::ParseError;
pub type ModuleSpecifier = deno_ast::ModuleSpecifier;
pub const EMPTY_SPECIFIER: &str = "deno://empty";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpecifierError {
InvalidUrl(ParseError),
ImportPrefixMissing(String, Option<ModuleSpecifier>),
}
use SpecifierError::*;
impl Error for SpecifierError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
InvalidUrl(ref err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for SpecifierError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
InvalidUrl(ref err) => write!(f, "invalid URL: {err}"),
ImportPrefixMissing(ref specifier, _) => write!(
f,
"Relative import path \"{specifier}\" not prefixed with / or ./ or ../",
),
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn specifier_from_path(path: PathBuf) -> ModuleSpecifier {
ModuleSpecifier::from_file_path(path).unwrap()
}
#[cfg(target_arch = "wasm32")]
fn specifier_from_path(_path: PathBuf) -> ModuleSpecifier {
ModuleSpecifier::parse(EMPTY_SPECIFIER).unwrap()
}
pub fn resolve_import(
specifier: &str,
referrer: &ModuleSpecifier,
) -> Result<ModuleSpecifier, SpecifierError> {
let url = match ModuleSpecifier::parse(specifier) {
Ok(url) => url,
Err(ParseError::RelativeUrlWithoutBase)
if !(specifier.starts_with('/')
|| specifier.starts_with("./")
|| specifier.starts_with("../")) =>
{
return Err(ImportPrefixMissing(
specifier.to_string(),
Some(referrer.clone()),
));
}
Err(ParseError::RelativeUrlWithoutBase) => {
let referrer = if referrer.as_str() == EMPTY_SPECIFIER {
let path = std::env::current_dir().unwrap().join("empty");
specifier_from_path(path)
} else {
referrer.clone()
};
referrer.join(specifier).map_err(InvalidUrl)?
}
Err(err) => return Err(InvalidUrl(err)),
};
Ok(url)
}
pub fn is_fs_root_specifier(url: &ModuleSpecifier) -> bool {
if url.scheme() != "file" {
return false;
}
let path = url.path();
let path = path.trim_start_matches('/').trim_end_matches('/');
let mut parts = path.split('/');
let Some(first_part) = parts.next() else {
return true;
};
if parts.next().is_some() {
return false;
}
let mut first_part_chars = first_part.chars();
let Some(first_char) = first_part_chars.next() else {
return true;
};
let Some(second_char) = first_part_chars.next() else {
return false;
};
first_part_chars.next().is_none()
&& first_char.is_ascii_alphabetic()
&& second_char == ':'
}
#[cfg(test)]
mod test {
use crate::ModuleSpecifier;
use super::*;
#[test]
fn test_is_fs_root_specifier() {
let cases = [
("https://deno.land", false),
("file:///", true),
("file://", true),
("file:///C:/", true),
("file:///V:/", true),
("file:///V:/test/", false),
];
for (specifier, expected) in cases {
let url = ModuleSpecifier::parse(specifier).unwrap();
assert_eq!(is_fs_root_specifier(&url), expected, "{:?}", specifier);
}
}
}