deno_dir.rs 61.6 KB
Newer Older
R
Ryan Dahl 已提交
1
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
K
Kitson Kelly 已提交
2
use crate::compiler::ModuleMetaData;
A
Andy Hayden 已提交
3 4 5 6 7 8 9 10
use crate::errors;
use crate::errors::DenoError;
use crate::errors::DenoResult;
use crate::errors::ErrorKind;
use crate::fs as deno_fs;
use crate::http_util;
use crate::js_errors::SourceMapGetter;
use crate::msg;
11
use crate::tokio_util;
12
use crate::version;
A
Andy Hayden 已提交
13
use dirs;
14
use futures::future::{loop_fn, Either, Loop};
15
use futures::Future;
16
use http;
R
Ryan Dahl 已提交
17
use ring;
18
use serde_json;
R
Ryan Dahl 已提交
19
use std;
20
use std::fmt::Write;
21
use std::fs;
R
Ryan Dahl 已提交
22 23 24
use std::path::Path;
use std::path::PathBuf;
use std::result::Result;
K
Kitson Kelly 已提交
25
use std::str;
R
Ryan Dahl 已提交
26 27
use url;
use url::Url;
R
Ryan Dahl 已提交
28

29 30 31 32 33 34 35 36 37 38
/// Gets corresponding MediaType given extension
fn extmap(ext: &str) -> msg::MediaType {
  match ext {
    "ts" => msg::MediaType::TypeScript,
    "js" => msg::MediaType::JavaScript,
    "json" => msg::MediaType::Json,
    _ => msg::MediaType::Unknown,
  }
}

39
#[derive(Clone)]
R
Ryan Dahl 已提交
40 41 42 43 44 45 46 47 48 49 50
pub struct DenoDir {
  // Example: /Users/rld/.deno/
  pub root: PathBuf,
  // In the Go code this was called SrcDir.
  // This is where we cache http resources. Example:
  // /Users/rld/.deno/deps/github.com/ry/blah.js
  pub gen: PathBuf,
  // In the Go code this was called CacheDir.
  // This is where we cache compilation outputs. Example:
  // /Users/rld/.deno/gen/f39a473452321cacd7c346a870efb0e3e1264b43.js
  pub deps: PathBuf,
51 52 53
  // This splits to http and https deps
  pub deps_http: PathBuf,
  pub deps_https: PathBuf,
R
Ryan Dahl 已提交
54 55 56 57
}

impl DenoDir {
  // Must be called before using any function from this module.
R
Ryan Dahl 已提交
58
  // https://github.com/denoland/deno/blob/golang/deno_dir.go#L99-L111
59
  pub fn new(custom_root: Option<PathBuf>) -> std::io::Result<Self> {
R
Ryan Dahl 已提交
60
    // Only setup once.
61
    let home_dir = dirs::home_dir().expect("Could not get home directory.");
62 63 64 65 66 67 68
    let fallback = home_dir.join(".deno");
    // We use the OS cache dir because all files deno writes are cache files
    // Once that changes we need to start using different roots if DENO_DIR
    // is not set, and keep a single one if it is.
    let default = dirs::cache_dir()
      .map(|d| d.join("deno"))
      .unwrap_or(fallback);
R
Ryan Dahl 已提交
69

F
F001 已提交
70
    let root: PathBuf = custom_root.unwrap_or(default);
R
Ryan Dahl 已提交
71 72
    let gen = root.as_path().join("gen");
    let deps = root.as_path().join("deps");
73 74
    let deps_http = deps.join("http");
    let deps_https = deps.join("https");
R
Ryan Dahl 已提交
75

76
    let deno_dir = Self {
R
Ryan Dahl 已提交
77 78 79
      root,
      gen,
      deps,
80 81
      deps_http,
      deps_https,
R
Ryan Dahl 已提交
82
    };
83 84 85 86 87 88

    // TODO Lazily create these directories.
    deno_fs::mkdir(deno_dir.gen.as_ref(), 0o755, true)?;
    deno_fs::mkdir(deno_dir.deps.as_ref(), 0o755, true)?;
    deno_fs::mkdir(deno_dir.deps_http.as_ref(), 0o755, true)?;
    deno_fs::mkdir(deno_dir.deps_https.as_ref(), 0o755, true)?;
R
Ryan Dahl 已提交
89 90 91 92

    debug!("root {}", deno_dir.root.display());
    debug!("gen {}", deno_dir.gen.display());
    debug!("deps {}", deno_dir.deps.display());
93 94
    debug!("deps_http {}", deno_dir.deps_http.display());
    debug!("deps_https {}", deno_dir.deps_https.display());
R
Ryan Dahl 已提交
95 96 97 98

    Ok(deno_dir)
  }

R
Ryan Dahl 已提交
99
  // https://github.com/denoland/deno/blob/golang/deno_dir.go#L32-L35
R
Ryan Dahl 已提交
100
  pub fn cache_path(
101
    self: &Self,
R
Ryan Dahl 已提交
102
    filename: &str,
K
Kitson Kelly 已提交
103
    source_code: &[u8],
104
  ) -> (PathBuf, PathBuf) {
105
    let cache_key = source_code_hash(filename, source_code, version::DENO);
106 107 108 109
    (
      self.gen.join(cache_key.to_string() + ".js"),
      self.gen.join(cache_key.to_string() + ".js.map"),
    )
R
Ryan Dahl 已提交
110 111 112
  }

  pub fn code_cache(
113
    self: &Self,
K
Kitson Kelly 已提交
114
    module_meta_data: &ModuleMetaData,
R
Ryan Dahl 已提交
115
  ) -> std::io::Result<()> {
K
Kitson Kelly 已提交
116 117
    let (cache_path, source_map_path) = self
      .cache_path(&module_meta_data.filename, &module_meta_data.source_code);
R
Ryan Dahl 已提交
118 119 120 121
    // TODO(ry) This is a race condition w.r.t to exists() -- probably should
    // create the file in exclusive mode. A worry is what might happen is there
    // are two processes and one reads the cache file while the other is in the
    // midst of writing it.
122
    if cache_path.exists() && source_map_path.exists() {
R
Ryan Dahl 已提交
123 124
      Ok(())
    } else {
K
Kitson Kelly 已提交
125 126 127 128 129 130 131 132
      match &module_meta_data.maybe_output_code {
        Some(output_code) => fs::write(cache_path, output_code),
        _ => Ok(()),
      }?;
      match &module_meta_data.maybe_source_map {
        Some(source_map) => fs::write(source_map_path, source_map),
        _ => Ok(()),
      }?;
133
      Ok(())
R
Ryan Dahl 已提交
134 135 136
    }
  }

137
  pub fn fetch_module_meta_data_async(
138
    self: &Self,
R
Ryan Dahl 已提交
139 140
    specifier: &str,
    referrer: &str,
141
    use_cache: bool,
142
  ) -> impl Future<Item = ModuleMetaData, Error = errors::DenoError> {
K
Kitson Kelly 已提交
143 144 145 146
    debug!(
      "fetch_module_meta_data. specifier {} referrer {}",
      specifier, referrer
    );
R
Ryan Dahl 已提交
147

148 149
    let specifier = specifier.to_string();
    let referrer = referrer.to_string();
R
Ryan Dahl 已提交
150

151 152 153
    let result = self.resolve_module(&specifier, &referrer);
    if let Err(err) = result {
      return Either::A(futures::future::err(DenoError::from(err)));
K
Kitson Kelly 已提交
154
    }
155 156 157 158 159
    let (module_name, filename) = result.unwrap();

    let gen = self.gen.clone();

    Either::B(
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
      get_source_code_async(
        self,
        module_name.as_str(),
        filename.as_str(),
        use_cache,
      ).then(move |result| {
        let mut out = match result {
          Ok(out) => out,
          Err(err) => {
            if err.kind() == ErrorKind::NotFound {
              // For NotFound, change the message to something better.
              return Err(errors::new(
                ErrorKind::NotFound,
                format!(
                  "Cannot resolve module \"{}\" from \"{}\"",
                  specifier, referrer
                ),
              ));
            } else {
              return Err(err);
180 181
            }
          }
182
        };
R
Ryan Dahl 已提交
183

184 185 186
        if out.source_code.starts_with(b"#!") {
          out.source_code = filter_shebang(out.source_code);
        }
187

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
        // If TypeScript we have to also load corresponding compile js and
        // source maps (called output_code and output_source_map)
        if out.media_type != msg::MediaType::TypeScript || !use_cache {
          return Ok(out);
        }

        let cache_key =
          source_code_hash(&out.filename, &out.source_code, version::DENO);
        let (output_code_filename, output_source_map_filename) = (
          gen.join(cache_key.to_string() + ".js"),
          gen.join(cache_key.to_string() + ".js.map"),
        );

        let result =
          load_cache2(&output_code_filename, &output_source_map_filename);
        match result {
          Err(err) => {
            if err.kind() == std::io::ErrorKind::NotFound {
              // If there's no compiled JS or source map, that's ok, just
              // return what we have.
208
              Ok(out)
209 210
            } else {
              Err(err.into())
211
            }
212
          }
213 214 215 216 217 218 219 220 221 222 223
          Ok((output_code, source_map)) => {
            out.maybe_output_code = Some(output_code);
            out.maybe_source_map = Some(source_map);
            out.maybe_output_code_filename =
              Some(output_code_filename.to_str().unwrap().to_string());
            out.maybe_source_map_filename =
              Some(output_source_map_filename.to_str().unwrap().to_string());
            Ok(out)
          }
        }
      }),
224 225 226 227 228 229 230 231 232
    )
  }

  /// Synchronous version of fetch_module_meta_data_async
  /// This function is deprecated.
  pub fn fetch_module_meta_data(
    self: &Self,
    specifier: &str,
    referrer: &str,
233
    use_cache: bool,
234
  ) -> Result<ModuleMetaData, errors::DenoError> {
235 236 237
    tokio_util::block_on(
      self.fetch_module_meta_data_async(specifier, referrer, use_cache),
    )
R
Ryan Dahl 已提交
238 239
  }

R
Ryan Dahl 已提交
240
  // Prototype: https://github.com/denoland/deno/blob/golang/os.go#L56-L68
241
  fn src_file_to_url(self: &Self, filename: &str) -> String {
R
Ryan Dahl 已提交
242 243
    let filename_path = Path::new(filename);
    if filename_path.starts_with(&self.deps) {
244 245 246 247 248 249 250 251 252 253 254 255
      let (rest, prefix) = if filename_path.starts_with(&self.deps_https) {
        let rest = filename_path.strip_prefix(&self.deps_https).unwrap();
        let prefix = "https://".to_string();
        (rest, prefix)
      } else if filename_path.starts_with(&self.deps_http) {
        let rest = filename_path.strip_prefix(&self.deps_http).unwrap();
        let prefix = "http://".to_string();
        (rest, prefix)
      } else {
        // TODO(kevinkassimo): change this to support other protocols than http
        unimplemented!()
      };
R
Ryan Dahl 已提交
256 257 258 259 260
      // Windows doesn't support ":" in filenames, so we represent port using a
      // special string.
      // TODO(ry) This current implementation will break on a URL that has
      // the default port but contains "_PORT" in the path.
      let rest = rest.to_str().unwrap().replacen("_PORT", ":", 1);
261
      prefix + &rest
R
Ryan Dahl 已提交
262
    } else {
R
Ryan Dahl 已提交
263
      String::from(filename)
R
Ryan Dahl 已提交
264 265 266
    }
  }

267
  /// Returns (module name, local filename)
R
Ryan Dahl 已提交
268
  pub fn resolve_module_url(
269
    self: &Self,
R
Ryan Dahl 已提交
270 271
    specifier: &str,
    referrer: &str,
R
Ryan Dahl 已提交
272
  ) -> Result<Url, url::ParseError> {
R
Ryan Dahl 已提交
273
    let specifier = self.src_file_to_url(specifier);
274
    let mut referrer = self.src_file_to_url(referrer);
R
Ryan Dahl 已提交
275

R
Ryan Dahl 已提交
276
    debug!(
R
Ryan Dahl 已提交
277 278
      "resolve_module specifier {} referrer {}",
      specifier, referrer
R
Ryan Dahl 已提交
279 280
    );

281
    if referrer.starts_with('.') {
282 283 284 285 286
      let cwd = std::env::current_dir().unwrap();
      let referrer_path = cwd.join(referrer);
      referrer = referrer_path.to_str().unwrap().to_string() + "/";
    }

287 288 289
    let j = if is_remote(&specifier)
      || (Path::new(&specifier).is_absolute() && !is_remote(&referrer))
    {
R
Ryan Dahl 已提交
290 291 292
      parse_local_or_remote(&specifier)?
    } else if referrer.ends_with('/') {
      let r = Url::from_directory_path(&referrer);
R
Ryan Dahl 已提交
293 294
      // TODO(ry) Properly handle error.
      if r.is_err() {
R
Ryan Dahl 已提交
295
        error!("Url::from_directory_path error {}", referrer);
R
Ryan Dahl 已提交
296 297
      }
      let base = r.unwrap();
R
Ryan Dahl 已提交
298
      base.join(specifier.as_ref())?
R
Ryan Dahl 已提交
299
    } else {
R
Ryan Dahl 已提交
300 301
      let base = parse_local_or_remote(&referrer)?;
      base.join(specifier.as_ref())?
R
Ryan Dahl 已提交
302
    };
R
Ryan Dahl 已提交
303 304 305 306 307 308 309 310 311 312
    Ok(j)
  }

  /// Returns (module name, local filename)
  pub fn resolve_module(
    self: &Self,
    specifier: &str,
    referrer: &str,
  ) -> Result<(String, String), url::ParseError> {
    let j = self.resolve_module_url(specifier, referrer)?;
R
Ryan Dahl 已提交
313

R
Ryan Dahl 已提交
314 315
    let module_name = j.to_string();
    let filename;
R
Ryan Dahl 已提交
316 317
    match j.scheme() {
      "file" => {
R
Ryan Dahl 已提交
318
        filename = deno_fs::normalize_path(j.to_file_path().unwrap().as_ref());
R
Ryan Dahl 已提交
319
      }
320 321
      "https" => {
        filename = deno_fs::normalize_path(
A
Andy Hayden 已提交
322
          get_cache_filename(self.deps_https.as_path(), &j).as_ref(),
323 324 325
        )
      }
      "http" => {
326
        filename = deno_fs::normalize_path(
A
Andy Hayden 已提交
327
          get_cache_filename(self.deps_http.as_path(), &j).as_ref(),
R
Ryan Dahl 已提交
328
        )
R
Ryan Dahl 已提交
329
      }
330
      // TODO(kevinkassimo): change this to support other protocols than http.
331
      _ => unimplemented!(),
R
Ryan Dahl 已提交
332 333
    }

R
Ryan Dahl 已提交
334
    debug!("module_name: {}, filename: {}", module_name, filename);
R
Ryan Dahl 已提交
335 336 337 338
    Ok((module_name, filename))
  }
}

339
impl SourceMapGetter for DenoDir {
K
Kitson Kelly 已提交
340
  fn get_source_map(&self, script_name: &str) -> Option<Vec<u8>> {
341
    match self.fetch_module_meta_data(script_name, ".", true) {
342
      Err(_e) => None,
343
      Ok(out) => match out.maybe_source_map {
344 345
        None => None,
        Some(source_map) => Some(source_map),
346 347 348 349 350
      },
    }
  }
}

351 352 353 354 355 356 357 358 359 360 361 362 363 364
/// This fetches source code, locally or remotely.
/// module_name is the URL specifying the module.
/// filename is the local path to the module (if remote, it is in the cache
/// folder, and potentially does not exist yet)
///
/// It *does not* fill the compiled JS nor source map portions of
/// ModuleMetaData. This is the only difference between this function and
/// fetch_module_meta_data_async(). TODO(ry) change return type to reflect this
/// fact.
///
/// If this is a remote module, and it has not yet been cached, the resulting
/// download will be written to "filename". This happens no matter the value of
/// use_cache.
fn get_source_code_async(
365
  deno_dir: &DenoDir,
366 367 368 369 370 371 372 373
  module_name: &str,
  filename: &str,
  use_cache: bool,
) -> impl Future<Item = ModuleMetaData, Error = DenoError> {
  let filename = filename.to_string();
  let module_name = module_name.to_string();
  let is_module_remote = is_remote(&module_name);
  // We try fetch local. Two cases:
374 375
  // 1. This is a remote module and we're allowed to use cached downloads.
  // 2. This is a local module.
376 377 378 379 380 381
  if !is_module_remote || use_cache {
    debug!(
      "fetch local or reload {} is_module_remote {}",
      module_name, is_module_remote
    );
    // Note that local fetch is done synchronously.
382
    match fetch_local_source(deno_dir, &module_name, &filename, None) {
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
      Ok(Some(output)) => {
        debug!("found local source ");
        return Either::A(futures::future::ok(output));
      }
      Ok(None) => {
        debug!("fetch_local_source returned None");
      }
      Err(err) => {
        return Either::A(futures::future::err(err));
      }
    }
  }

  // If not remote file, stop here!
  if !is_module_remote {
    debug!("not remote file stop here");
    return Either::A(futures::future::err(DenoError::from(
      std::io::Error::new(
        std::io::ErrorKind::NotFound,
        format!("cannot find local file '{}'", &filename),
      ),
    )));
  }

  debug!("is remote but didn't find module");

409 410 411 412 413 414 415 416 417 418 419 420
  // not cached/local, try remote.
  Either::B(
    fetch_remote_source_async(deno_dir, &module_name, &filename).and_then(
      move |maybe_remote_source| match maybe_remote_source {
        Some(output) => Ok(output),
        None => Err(DenoError::from(std::io::Error::new(
          std::io::ErrorKind::NotFound,
          format!("cannot find remote file '{}'", &filename),
        ))),
      },
    ),
  )
421 422 423 424 425 426
}

#[cfg(test)]
/// Synchronous version of get_source_code_async
/// This function is deprecated.
fn get_source_code(
427
  deno_dir: &DenoDir,
428 429 430 431
  module_name: &str,
  filename: &str,
  use_cache: bool,
) -> DenoResult<ModuleMetaData> {
432 433 434 435 436 437
  tokio_util::block_on(get_source_code_async(
    deno_dir,
    module_name,
    filename,
    use_cache,
  ))
438 439
}

A
Andy Hayden 已提交
440
fn get_cache_filename(basedir: &Path, url: &Url) -> PathBuf {
R
Ryan Dahl 已提交
441 442 443 444 445 446 447 448
  let host = url.host_str().unwrap();
  let host_port = match url.port() {
    // Windows doesn't support ":" in filenames, so we represent port using a
    // special string.
    Some(port) => format!("{}_PORT{}", host, port),
    None => host.to_string(),
  };

R
Ryan Dahl 已提交
449
  let mut out = basedir.to_path_buf();
R
Ryan Dahl 已提交
450
  out.push(host_port);
R
Ryan Dahl 已提交
451 452 453 454 455 456
  for path_seg in url.path_segments().unwrap() {
    out.push(path_seg);
  }
  out
}

457 458 459 460 461 462 463 464 465 466 467 468 469 470
fn load_cache2(
  js_filename: &PathBuf,
  map_filename: &PathBuf,
) -> Result<(Vec<u8>, Vec<u8>), std::io::Error> {
  debug!(
    "load_cache code: {} map: {}",
    js_filename.display(),
    map_filename.display()
  );
  let read_output_code = fs::read(&js_filename)?;
  let read_source_map = fs::read(&map_filename)?;
  Ok((read_output_code, read_source_map))
}

471 472
fn source_code_hash(
  filename: &str,
K
Kitson Kelly 已提交
473
  source_code: &[u8],
474 475
  version: &str,
) -> String {
R
Ryan Dahl 已提交
476
  let mut ctx = ring::digest::Context::new(&ring::digest::SHA1);
477
  ctx.update(version.as_bytes());
R
Ryan Dahl 已提交
478
  ctx.update(filename.as_bytes());
K
Kitson Kelly 已提交
479
  ctx.update(source_code);
R
Ryan Dahl 已提交
480
  let digest = ctx.finish();
481 482
  let mut out = String::new();
  // TODO There must be a better way to do this...
R
Ryan Dahl 已提交
483
  for byte in digest.as_ref() {
484
    write!(&mut out, "{:02x}", byte).unwrap();
R
Ryan Dahl 已提交
485 486
  }
  out
R
Ryan Dahl 已提交
487 488
}

R
Ryan Dahl 已提交
489
fn is_remote(module_name: &str) -> bool {
490
  module_name.starts_with("http://") || module_name.starts_with("https://")
R
Ryan Dahl 已提交
491
}
R
Ryan Dahl 已提交
492 493

fn parse_local_or_remote(p: &str) -> Result<url::Url, url::ParseError> {
R
Ryan Dahl 已提交
494
  if is_remote(p) || p.starts_with("file:") {
R
Ryan Dahl 已提交
495 496 497 498 499
    Url::parse(p)
  } else {
    Url::from_file_path(p).map_err(|_err| url::ParseError::IdnaError)
  }
}
K
Kitson Kelly 已提交
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519

fn map_file_extension(path: &Path) -> msg::MediaType {
  match path.extension() {
    None => msg::MediaType::Unknown,
    Some(os_str) => match os_str.to_str() {
      Some("ts") => msg::MediaType::TypeScript,
      Some("js") => msg::MediaType::JavaScript,
      Some("json") => msg::MediaType::Json,
      _ => msg::MediaType::Unknown,
    },
  }
}

// convert a ContentType string into a enumerated MediaType
fn map_content_type(path: &Path, content_type: Option<&str>) -> msg::MediaType {
  match content_type {
    Some(content_type) => {
      // sometimes there is additional data after the media type in
      // Content-Type so we have to do a bit of manipulation so we are only
      // dealing with the actual media type
A
Andy Hayden 已提交
520
      let ct_vector: Vec<&str> = content_type.split(';').collect();
K
Kitson Kelly 已提交
521 522 523 524 525
      let ct: &str = ct_vector.first().unwrap();
      match ct.to_lowercase().as_ref() {
        "application/typescript"
        | "text/typescript"
        | "video/vnd.dlna.mpeg-tts"
526 527
        | "video/mp2t"
        | "application/x-typescript" => msg::MediaType::TypeScript,
K
Kitson Kelly 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        "application/javascript"
        | "text/javascript"
        | "application/ecmascript"
        | "text/ecmascript"
        | "application/x-javascript" => msg::MediaType::JavaScript,
        "application/json" | "text/json" => msg::MediaType::Json,
        "text/plain" => map_file_extension(path),
        _ => {
          debug!("unknown content type: {}", content_type);
          msg::MediaType::Unknown
        }
      }
    }
    None => map_file_extension(path),
  }
}

K
Kitson Kelly 已提交
545 546 547 548 549
fn filter_shebang(bytes: Vec<u8>) -> Vec<u8> {
  let string = str::from_utf8(&bytes).unwrap();
  if let Some(i) = string.find('\n') {
    let (_, rest) = string.split_at(i);
    rest.as_bytes().to_owned()
A
Andy Hayden 已提交
550
  } else {
K
Kitson Kelly 已提交
551
    Vec::new()
R
Ryan Dahl 已提交
552 553 554
  }
}

555 556 557
/// Asynchronously fetch remote source file specified by the URL `module_name`
/// and write it to disk at `filename`.
fn fetch_remote_source_async(
558
  deno_dir: &DenoDir,
559 560
  module_name: &str,
  filename: &str,
561
) -> impl Future<Item = Option<ModuleMetaData>, Error = DenoError> {
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
  use crate::http_util::FetchOnceResult;
  {
    eprintln!("Downloading {}", module_name);
  }

  let filename = filename.to_owned();
  let module_name = module_name.to_owned();

  // We write a special ".headers.json" file into the `.deno/deps` directory along side the
  // cached file, containing just the media type and possible redirect target (both are http headers).
  // If redirect target is present, the file itself if not cached.
  // In future resolutions, we would instead follow this redirect target ("redirect_to").
  loop_fn(
    (
      deno_dir.clone(),
      None,
      None,
      module_name.clone(),
      filename.clone(),
    ),
    |(
      dir,
584 585
      mut maybe_initial_module_name,
      mut maybe_initial_filename,
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
      module_name,
      filename,
    )| {
      let url = module_name.parse::<http::uri::Uri>().unwrap();
      // Single pass fetch, either yields code or yields redirect.
      http_util::fetch_string_once(url).and_then(move |fetch_once_result| {
        match fetch_once_result {
          FetchOnceResult::Redirect(url) => {
            // If redirects, update module_name and filename for next looped call.
            let resolve_result = dir
              .resolve_module(&(url.to_string()), ".")
              .map_err(DenoError::from);
            match resolve_result {
              Ok((new_module_name, new_filename)) => {
                if maybe_initial_module_name.is_none() {
                  maybe_initial_module_name = Some(module_name.clone());
                  maybe_initial_filename = Some(filename.clone());
                }
                // Not yet completed. Follow the redirect and loop.
                Ok(Loop::Continue((
                  dir,
                  maybe_initial_module_name,
                  maybe_initial_filename,
                  new_module_name,
                  new_filename,
                )))
              }
              Err(e) => Err(e),
            }
          }
          FetchOnceResult::Code(source, maybe_content_type) => {
            // We land on the code.
            let p = PathBuf::from(filename.clone());
            match p.parent() {
              Some(ref parent) => fs::create_dir_all(parent),
              None => Ok(()),
            }?;
            // Write file and create .headers.json for the file.
            deno_fs::write_file(&p, &source, 0o666)?;
            {
626 627 628 629 630
              save_source_code_headers(
                &filename,
                maybe_content_type.clone(),
                None,
              );
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
            }
            // Check if this file is downloaded due to some old redirect request.
            if maybe_initial_filename.is_some() {
              // If yes, record down the headers for redirect.
              // Also create its containing folder.
              let pp = PathBuf::from(filename.clone());
              match pp.parent() {
                Some(ref parent) => fs::create_dir_all(parent),
                None => Ok(()),
              }?;
              {
                save_source_code_headers(
                  &maybe_initial_filename.clone().unwrap(),
                  maybe_content_type.clone(),
                  Some(module_name.clone()),
                );
              }
            }
            Ok(Loop::Break(Some(ModuleMetaData {
              module_name: module_name.to_string(),
              module_redirect_source_name: maybe_initial_module_name,
              filename: filename.to_string(),
              media_type: map_content_type(
                &p,
B
Bert Belder 已提交
655
                maybe_content_type.as_ref().map(String::as_str),
656 657 658 659 660 661 662 663 664 665
              ),
              source_code: source.as_bytes().to_owned(),
              maybe_output_code_filename: None,
              maybe_output_code: None,
              maybe_source_map_filename: None,
              maybe_source_map: None,
            })))
          }
        }
      })
666 667 668 669 670
    },
  )
}

/// Fetch remote source code.
671
#[cfg(test)]
672
fn fetch_remote_source(
673
  deno_dir: &DenoDir,
674 675 676
  module_name: &str,
  filename: &str,
) -> DenoResult<Option<ModuleMetaData>> {
677 678 679 680 681
  tokio_util::block_on(fetch_remote_source_async(
    deno_dir,
    module_name,
    filename,
  ))
682 683 684
}

/// Fetch local or cached source code.
685 686 687 688 689 690 691 692
/// This is a recursive operation if source file has redirection.
/// It will keep reading filename.headers.json for information about redirection.
/// module_initial_source_name would be None on first call,
/// and becomes the name of the very first module that initiates the call
/// in subsequent recursions.
/// AKA if redirection occurs, module_initial_source_name is the source path
/// that user provides, and the final module_name is the resolved path
/// after following all redirections.
693
fn fetch_local_source(
694
  deno_dir: &DenoDir,
695 696
  module_name: &str,
  filename: &str,
697
  module_initial_source_name: Option<String>,
698 699
) -> DenoResult<Option<ModuleMetaData>> {
  let p = Path::new(&filename);
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
  let source_code_headers = get_source_code_headers(&filename);
  // If source code headers says that it would redirect elsewhere,
  // (meaning that the source file might not exist; only .headers.json is present)
  // Abort reading attempts to the cached source file and and follow the redirect.
  if let Some(redirect_to) = source_code_headers.redirect_to {
    // E.g.
    // module_name https://import-meta.now.sh/redirect.js
    // filename /Users/kun/Library/Caches/deno/deps/https/import-meta.now.sh/redirect.js
    // redirect_to https://import-meta.now.sh/sub/final1.js
    // real_filename /Users/kun/Library/Caches/deno/deps/https/import-meta.now.sh/sub/final1.js
    // real_module_name = https://import-meta.now.sh/sub/final1.js
    let (real_module_name, real_filename) =
      deno_dir.resolve_module(&redirect_to, ".")?;
    let mut module_initial_source_name = module_initial_source_name;
    // If this is the first redirect attempt,
    // then module_initial_source_name should be None.
    // In that case, use current module name as module_initial_source_name.
    if module_initial_source_name.is_none() {
      module_initial_source_name = Some(module_name.to_owned());
    }
    // Recurse.
    return fetch_local_source(
      deno_dir,
      &real_module_name,
      &real_filename,
      module_initial_source_name,
    );
  }
  // No redirect needed or end of redirects.
  // We can try read the file
730 731 732 733 734 735 736 737 738 739 740 741
  let source_code = match fs::read(p) {
    Err(e) => {
      if e.kind() == std::io::ErrorKind::NotFound {
        return Ok(None);
      } else {
        return Err(e.into());
      }
    }
    Ok(c) => c,
  };
  Ok(Some(ModuleMetaData {
    module_name: module_name.to_string(),
742
    module_redirect_source_name: module_initial_source_name,
743
    filename: filename.to_string(),
744 745 746 747
    media_type: map_content_type(
      &p,
      source_code_headers.mime_type.as_ref().map(String::as_str),
    ),
748 749 750 751 752 753 754 755
    source_code,
    maybe_output_code_filename: None,
    maybe_output_code: None,
    maybe_source_map_filename: None,
    maybe_source_map: None,
  }))
}

756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
#[derive(Debug)]
/// Header metadata associated with a particular "symbolic" source code file.
/// (the associated source code file might not be cached, while remaining
/// a user accessible entity through imports (due to redirects)).
pub struct SourceCodeHeaders {
  /// MIME type of the source code.
  pub mime_type: Option<String>,
  /// Where should we actually look for source code.
  /// This should be an absolute path!
  pub redirect_to: Option<String>,
}

static MIME_TYPE: &'static str = "mime_type";
static REDIRECT_TO: &'static str = "redirect_to";

fn source_code_headers_filename(filename: &str) -> String {
  [&filename, ".headers.json"].concat()
}

/// Get header metadata associated with a single source code file.
/// NOTICE: chances are that the source code itself is not downloaded due to redirects.
/// In this case, the headers file provides info about where we should go and get
/// the source code that redirect eventually points to (which should be cached).
fn get_source_code_headers(filename: &str) -> SourceCodeHeaders {
  let headers_filename = source_code_headers_filename(filename);
  let hd = Path::new(&headers_filename);
  // .headers.json file might not exists.
  // This is okay for local source.
  let maybe_headers_string = fs::read_to_string(&hd).ok();
  if let Some(headers_string) = maybe_headers_string {
    // TODO(kevinkassimo): consider introduce serde::Deserialize to make things simpler.
    let maybe_headers: serde_json::Result<serde_json::Value> =
      serde_json::from_str(&headers_string);
    if let Ok(headers) = maybe_headers {
      return SourceCodeHeaders {
        mime_type: headers[MIME_TYPE].as_str().map(String::from),
        redirect_to: headers[REDIRECT_TO].as_str().map(String::from),
      };
    }
  }
  SourceCodeHeaders {
    mime_type: None,
    redirect_to: None,
  }
}

/// Save headers related to source filename to {filename}.headers.json file,
/// only when there is actually something necessary to save.
/// For example, if the extension ".js" already mean JS file and we have
/// content type of "text/javascript", then we would not save the mime type.
/// If nothing needs to be saved, the headers file is not created.
fn save_source_code_headers(
  filename: &str,
  mime_type: Option<String>,
  redirect_to: Option<String>,
) {
  let headers_filename = source_code_headers_filename(filename);
  // Remove possibly existing stale .headers.json file.
  // May not exist. DON'T unwrap.
  let _ = std::fs::remove_file(&headers_filename);
  let p = PathBuf::from(filename);
  // TODO(kevinkassimo): consider introduce serde::Deserialize to make things simpler.
  // This is super ugly at this moment...
  // Had trouble to make serde_derive work: I'm unable to build proc-macro2.
  let mut value_map = serde_json::map::Map::new();
  if mime_type.is_some() {
    let mime_type_string = mime_type.clone().unwrap();
    let resolved_mime_type =
      { map_content_type(Path::new(""), Some(mime_type_string.as_str())) };
    let ext = p
      .extension()
      .map(|x| x.to_str().unwrap_or(""))
      .unwrap_or("");
    let ext_based_mime_type = extmap(&ext);
    // Add mime to headers only when content type is different from extension.
    if ext_based_mime_type == msg::MediaType::Unknown
      || resolved_mime_type != ext_based_mime_type
    {
      value_map.insert(MIME_TYPE.to_string(), json!(mime_type_string));
    }
  }
  if redirect_to.is_some() {
    value_map.insert(REDIRECT_TO.to_string(), json!(redirect_to.unwrap()));
  }
  // Only save to file when there is actually data.
841
  if !value_map.is_empty() {
842 843 844 845 846 847 848 849 850 851 852 853 854 855
    let _ = serde_json::to_string(&value_map).map(|s| {
      // It is possible that we need to create file
      // with parent folders not yet created.
      // (Due to .headers.json feature for redirection)
      let hd = PathBuf::from(&headers_filename);
      let _ = match hd.parent() {
        Some(ref parent) => fs::create_dir_all(parent),
        None => Ok(()),
      };
      let _ = deno_fs::write_file(&(hd.as_path()), s, 0o666);
    });
  }
}

R
Ryan Dahl 已提交
856 857 858 859 860
#[cfg(test)]
mod tests {
  use super::*;
  use tempfile::TempDir;

861
  fn test_setup() -> (TempDir, DenoDir) {
R
Ryan Dahl 已提交
862
    let temp_dir = TempDir::new().expect("tempdir fail");
863
    let deno_dir =
864
      DenoDir::new(Some(temp_dir.path().to_path_buf())).expect("setup fail");
R
Ryan Dahl 已提交
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
    (temp_dir, deno_dir)
  }

  // The `add_root` macro prepends "C:" to a string if on windows; on posix
  // systems it returns the input string untouched. This is necessary because
  // `Url::from_file_path()` fails if the input path isn't an absolute path.
  macro_rules! add_root {
    ($path:expr) => {
      if cfg!(target_os = "windows") {
        concat!("C:", $path)
      } else {
        $path
      }
    };
  }

R
Ryan Dahl 已提交
881 882 883 884 885 886 887 888 889 890
  macro_rules! file_url {
    ($path:expr) => {
      if cfg!(target_os = "windows") {
        concat!("file:///C:", $path)
      } else {
        concat!("file://", $path)
      }
    };
  }

R
Ryan Dahl 已提交
891 892 893 894 895 896 897 898 899 900 901 902 903
  #[test]
  fn test_get_cache_filename() {
    let url = Url::parse("http://example.com:1234/path/to/file.ts").unwrap();
    let basedir = Path::new("/cache/dir/");
    let cache_file = get_cache_filename(&basedir, &url);
    assert_eq!(
      cache_file,
      Path::new("/cache/dir/example.com_PORT1234/path/to/file.ts")
    );
  }

  #[test]
  fn test_cache_path() {
904
    let (temp_dir, deno_dir) = test_setup();
905
    let filename = "hello.js";
B
Bert Belder 已提交
906
    let source_code = b"1+2";
907
    let hash = source_code_hash(filename, source_code, version::DENO);
R
Ryan Dahl 已提交
908 909
    assert_eq!(
      (
910 911
        temp_dir.path().join(format!("gen/{}.js", hash)),
        temp_dir.path().join(format!("gen/{}.js.map", hash))
R
Ryan Dahl 已提交
912
      ),
913
      deno_dir.cache_path(filename, source_code)
R
Ryan Dahl 已提交
914 915 916 917 918
    );
  }

  #[test]
  fn test_code_cache() {
919
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
920 921

    let filename = "hello.js";
B
Bert Belder 已提交
922 923 924
    let source_code = b"1+2";
    let output_code = b"1+2 // output code";
    let source_map = b"{}";
925
    let hash = source_code_hash(filename, source_code, version::DENO);
R
Ryan Dahl 已提交
926 927
    let (cache_path, source_map_path) =
      deno_dir.cache_path(filename, source_code);
928 929
    assert!(cache_path.ends_with(format!("gen/{}.js", hash)));
    assert!(source_map_path.ends_with(format!("gen/{}.js.map", hash)));
R
Ryan Dahl 已提交
930

K
Kitson Kelly 已提交
931 932
    let out = ModuleMetaData {
      filename: filename.to_owned(),
B
Bert Belder 已提交
933
      source_code: source_code[..].to_owned(),
K
Kitson Kelly 已提交
934
      module_name: "hello.js".to_owned(),
935
      module_redirect_source_name: None,
K
Kitson Kelly 已提交
936
      media_type: msg::MediaType::TypeScript,
B
Bert Belder 已提交
937
      maybe_output_code: Some(output_code[..].to_owned()),
K
Kitson Kelly 已提交
938
      maybe_output_code_filename: None,
B
Bert Belder 已提交
939
      maybe_source_map: Some(source_map[..].to_owned()),
K
Kitson Kelly 已提交
940 941 942 943
      maybe_source_map_filename: None,
    };

    let r = deno_dir.code_cache(&out);
R
Ryan Dahl 已提交
944 945
    r.expect("code_cache error");
    assert!(cache_path.exists());
B
Bert Belder 已提交
946
    assert_eq!(output_code[..].to_owned(), fs::read(&cache_path).unwrap());
R
Ryan Dahl 已提交
947 948 949 950 951
  }

  #[test]
  fn test_source_code_hash() {
    assert_eq!(
952
      "7e44de2ed9e0065da09d835b76b8d70be503d276",
B
Bert Belder 已提交
953
      source_code_hash("hello.ts", b"1+2", "0.2.11")
R
Ryan Dahl 已提交
954 955 956
    );
    // Different source_code should result in different hash.
    assert_eq!(
957
      "57033366cf9db1ef93deca258cdbcd9ef5f4bde1",
B
Bert Belder 已提交
958
      source_code_hash("hello.ts", b"1", "0.2.11")
R
Ryan Dahl 已提交
959 960 961
    );
    // Different filename should result in different hash.
    assert_eq!(
962
      "19657f90b5b0540f87679e2fb362e7bd62b644b0",
B
Bert Belder 已提交
963
      source_code_hash("hi.ts", b"1+2", "0.2.11")
964 965 966 967
    );
    // Different version should result in different hash.
    assert_eq!(
      "e2b4b7162975a02bf2770f16836eb21d5bcb8be1",
B
Bert Belder 已提交
968
      source_code_hash("hi.ts", b"1+2", "0.2.0")
R
Ryan Dahl 已提交
969 970 971
    );
  }

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
  #[test]
  fn test_source_code_headers_get_and_save() {
    let (temp_dir, _deno_dir) = test_setup();
    let filename =
      deno_fs::normalize_path(temp_dir.into_path().join("f.js").as_ref());
    let headers_file_name = source_code_headers_filename(&filename);
    assert_eq!(headers_file_name, [&filename, ".headers.json"].concat());
    let _ = deno_fs::write_file(&PathBuf::from(&headers_file_name),
      "{\"mime_type\":\"text/javascript\",\"redirect_to\":\"http://example.com/a.js\"}", 0o666);
    let headers = get_source_code_headers(&filename);
    assert_eq!(headers.mime_type.clone().unwrap(), "text/javascript");
    assert_eq!(
      headers.redirect_to.clone().unwrap(),
      "http://example.com/a.js"
    );

    save_source_code_headers(
      &filename,
      Some("text/typescript".to_owned()),
      Some("http://deno.land/a.js".to_owned()),
    );
    let headers2 = get_source_code_headers(&filename);
    assert_eq!(headers2.mime_type.clone().unwrap(), "text/typescript");
    assert_eq!(
      headers2.redirect_to.clone().unwrap(),
      "http://deno.land/a.js"
    );
  }

R
Ryan Dahl 已提交
1001
  #[test]
1002
  fn test_get_source_code_1() {
1003
    let (_temp_dir, deno_dir) = test_setup();
1004 1005 1006 1007 1008 1009 1010 1011 1012
    // http_util::fetch_sync_string requires tokio
    tokio_util::init(|| {
      let module_name = "http://localhost:4545/tests/subdir/mod2.ts";
      let filename = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("localhost_PORT4545/tests/subdir/mod2.ts")
          .as_ref(),
      );
1013
      let headers_file_name = source_code_headers_filename(&filename);
1014

1015
      let result = get_source_code(&deno_dir, module_name, &filename, true);
1016 1017
      assert!(result.is_ok());
      let r = result.unwrap();
1018
      assert_eq!(
K
Kitson Kelly 已提交
1019 1020
        r.source_code,
        "export { printHello } from \"./print_hello.ts\";\n".as_bytes()
1021
      );
1022
      assert_eq!(&(r.media_type), &msg::MediaType::TypeScript);
1023 1024
      // Should not create .headers.json file due to matching ext
      assert!(fs::read_to_string(&headers_file_name).is_err());
1025

1026 1027 1028 1029
      // Modify .headers.json, write using fs write and read using save_source_code_headers
      let _ =
        fs::write(&headers_file_name, "{ \"mime_type\": \"text/javascript\" }");
      let result2 = get_source_code(&deno_dir, module_name, &filename, true);
1030 1031
      assert!(result2.is_ok());
      let r2 = result2.unwrap();
1032
      assert_eq!(
K
Kitson Kelly 已提交
1033 1034
        r2.source_code,
        "export { printHello } from \"./print_hello.ts\";\n".as_bytes()
1035
      );
1036
      // If get_source_code does not call remote, this should be JavaScript
1037
      // as we modified before! (we do not overwrite .headers.json due to no http fetch)
1038 1039
      assert_eq!(&(r2.media_type), &msg::MediaType::JavaScript);
      assert_eq!(
1040
        get_source_code_headers(&filename).mime_type.unwrap(),
1041 1042 1043
        "text/javascript"
      );

1044 1045 1046 1047 1048 1049 1050
      // Modify .headers.json again, but the other way around
      save_source_code_headers(
        &filename,
        Some("application/json".to_owned()),
        None,
      );
      let result3 = get_source_code(&deno_dir, module_name, &filename, true);
1051 1052
      assert!(result3.is_ok());
      let r3 = result3.unwrap();
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
      assert_eq!(
        r3.source_code,
        "export { printHello } from \"./print_hello.ts\";\n".as_bytes()
      );
      // If get_source_code does not call remote, this should be JavaScript
      // as we modified before! (we do not overwrite .headers.json due to no http fetch)
      assert_eq!(&(r3.media_type), &msg::MediaType::Json);
      assert!(
        fs::read_to_string(&headers_file_name)
          .unwrap()
          .contains("application/json")
      );

      // Don't use_cache
      let result4 = get_source_code(&deno_dir, module_name, &filename, false);
      assert!(result4.is_ok());
      let r4 = result4.unwrap();
      let expected4 =
K
Kitson Kelly 已提交
1071
        "export { printHello } from \"./print_hello.ts\";\n".as_bytes();
1072 1073 1074 1075
      assert_eq!(r4.source_code, expected4);
      // Now the old .headers.json file should have gone! Resolved back to TypeScript
      assert_eq!(&(r4.media_type), &msg::MediaType::TypeScript);
      assert!(fs::read_to_string(&headers_file_name).is_err());
1076 1077 1078 1079 1080
    });
  }

  #[test]
  fn test_get_source_code_2() {
1081
    let (_temp_dir, deno_dir) = test_setup();
1082 1083 1084 1085 1086 1087 1088 1089 1090
    // http_util::fetch_sync_string requires tokio
    tokio_util::init(|| {
      let module_name = "http://localhost:4545/tests/subdir/mismatch_ext.ts";
      let filename = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("localhost_PORT4545/tests/subdir/mismatch_ext.ts")
          .as_ref(),
      );
1091
      let headers_file_name = source_code_headers_filename(&filename);
1092

1093
      let result = get_source_code(&deno_dir, module_name, &filename, true);
1094 1095
      assert!(result.is_ok());
      let r = result.unwrap();
K
Kitson Kelly 已提交
1096
      let expected = "export const loaded = true;\n".as_bytes();
1097
      assert_eq!(r.source_code, expected);
1098
      // Mismatch ext with content type, create .headers.json
1099
      assert_eq!(&(r.media_type), &msg::MediaType::JavaScript);
1100
      assert_eq!(
1101
        get_source_code_headers(&filename).mime_type.unwrap(),
1102 1103 1104
        "text/javascript"
      );

1105 1106 1107 1108 1109 1110 1111
      // Modify .headers.json
      save_source_code_headers(
        &filename,
        Some("text/typescript".to_owned()),
        None,
      );
      let result2 = get_source_code(&deno_dir, module_name, &filename, true);
1112 1113
      assert!(result2.is_ok());
      let r2 = result2.unwrap();
K
Kitson Kelly 已提交
1114
      let expected2 = "export const loaded = true;\n".as_bytes();
1115 1116
      assert_eq!(r2.source_code, expected2);
      // If get_source_code does not call remote, this should be TypeScript
1117
      // as we modified before! (we do not overwrite .headers.json due to no http fetch)
1118
      assert_eq!(&(r2.media_type), &msg::MediaType::TypeScript);
1119
      assert!(fs::read_to_string(&headers_file_name).is_err());
1120

1121
      // Don't use_cache
1122
      let result3 = get_source_code(&deno_dir, module_name, &filename, false);
1123 1124
      assert!(result3.is_ok());
      let r3 = result3.unwrap();
K
Kitson Kelly 已提交
1125
      let expected3 = "export const loaded = true;\n".as_bytes();
1126
      assert_eq!(r3.source_code, expected3);
1127
      // Now the old .headers.json file should be overwritten back to JavaScript!
1128 1129 1130
      // (due to http fetch)
      assert_eq!(&(r3.media_type), &msg::MediaType::JavaScript);
      assert_eq!(
1131
        get_source_code_headers(&filename).mime_type.unwrap(),
1132
        "text/javascript"
1133 1134 1135 1136
      );
    });
  }

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
  #[test]
  fn test_get_source_code_3() {
    let (_temp_dir, deno_dir) = test_setup();
    // Test basic follow and headers recording
    tokio_util::init(|| {
      let redirect_module_name =
        "http://localhost:4546/tests/subdir/redirects/redirect1.js";
      let redirect_source_filename = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("localhost_PORT4546/tests/subdir/redirects/redirect1.js")
          .as_ref(),
      );
      let target_module_name =
        "http://localhost:4545/tests/subdir/redirects/redirect1.js";
      let redirect_target_filename = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("localhost_PORT4545/tests/subdir/redirects/redirect1.js")
          .as_ref(),
      );
      let mod_meta = get_source_code(
        &deno_dir,
        redirect_module_name,
        &redirect_source_filename,
        true,
      ).unwrap();
      // File that requires redirection is not downloaded.
      assert!(fs::read_to_string(&redirect_source_filename).is_err());
      // ... but its .headers.json is created.
      let redirect_source_headers =
        get_source_code_headers(&redirect_source_filename);
      assert_eq!(
        redirect_source_headers.redirect_to.unwrap(),
        "http://localhost:4545/tests/subdir/redirects/redirect1.js"
      );
      // The target of redirection is downloaded instead.
      assert_eq!(
        fs::read_to_string(&redirect_target_filename).unwrap(),
        "export const redirect = 1;\n"
      );
      let redirect_target_headers =
        get_source_code_headers(&redirect_target_filename);
      assert!(redirect_target_headers.redirect_to.is_none());

      // Examine the meta result.
      assert_eq!(&mod_meta.module_name, target_module_name);
      assert_eq!(
        &mod_meta.module_redirect_source_name.clone().unwrap(),
        redirect_module_name
      );
    });
  }

  #[test]
  fn test_get_source_code_4() {
    let (_temp_dir, deno_dir) = test_setup();
    // Test double redirects and headers recording
    tokio_util::init(|| {
      let redirect_module_name =
        "http://localhost:4548/tests/subdir/redirects/redirect1.js";
      let redirect_source_filename = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("localhost_PORT4548/tests/subdir/redirects/redirect1.js")
          .as_ref(),
      );
      let redirect_source_filename_intermediate = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("localhost_PORT4546/tests/subdir/redirects/redirect1.js")
          .as_ref(),
      );
      let target_module_name =
        "http://localhost:4545/tests/subdir/redirects/redirect1.js";
      let redirect_target_filename = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("localhost_PORT4545/tests/subdir/redirects/redirect1.js")
          .as_ref(),
      );
      let mod_meta = get_source_code(
        &deno_dir,
        redirect_module_name,
        &redirect_source_filename,
        true,
      ).unwrap();

      // File that requires redirection is not downloaded.
      assert!(fs::read_to_string(&redirect_source_filename).is_err());
      // ... but its .headers.json is created.
      let redirect_source_headers =
        get_source_code_headers(&redirect_source_filename);
      assert_eq!(
        redirect_source_headers.redirect_to.unwrap(),
        target_module_name
      );

      // In the intermediate redirection step, file is also not downloaded.
      assert!(
        fs::read_to_string(&redirect_source_filename_intermediate).is_err()
      );

      // The target of redirection is downloaded instead.
      assert_eq!(
        fs::read_to_string(&redirect_target_filename).unwrap(),
        "export const redirect = 1;\n"
      );
      let redirect_target_headers =
        get_source_code_headers(&redirect_target_filename);
      assert!(redirect_target_headers.redirect_to.is_none());

      // Examine the meta result.
      assert_eq!(&mod_meta.module_name, target_module_name);
      assert_eq!(
        &mod_meta.module_redirect_source_name.clone().unwrap(),
        redirect_module_name
      );
    });
  }

1258 1259 1260 1261 1262
  #[test]
  fn test_fetch_source_async_1() {
    use crate::tokio_util;
    // http_util::fetch_sync_string requires tokio
    tokio_util::init(|| {
1263
      let (_temp_dir, deno_dir) = test_setup();
1264 1265 1266 1267 1268 1269 1270 1271
      let module_name =
        "http://127.0.0.1:4545/tests/subdir/mt_video_mp2t.t3.ts".to_string();
      let filename = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("127.0.0.1_PORT4545/tests/subdir/mt_video_mp2t.t3.ts")
          .as_ref(),
      );
1272
      let headers_file_name = source_code_headers_filename(&filename);
1273 1274

      let result = tokio_util::block_on(fetch_remote_source_async(
1275
        &deno_dir,
1276 1277 1278 1279 1280 1281 1282
        &module_name,
        &filename,
      ));
      assert!(result.is_ok());
      let r = result.unwrap().unwrap();
      assert_eq!(r.source_code, b"export const loaded = true;\n");
      assert_eq!(&(r.media_type), &msg::MediaType::TypeScript);
1283 1284
      // matching ext, no .headers.json file created
      assert!(fs::read_to_string(&headers_file_name).is_err());
1285

1286 1287 1288 1289 1290 1291 1292 1293
      // Modify .headers.json, make sure read from local
      save_source_code_headers(
        &filename,
        Some("text/javascript".to_owned()),
        None,
      );
      let result2 =
        fetch_local_source(&deno_dir, &module_name, &filename, None);
1294 1295 1296
      assert!(result2.is_ok());
      let r2 = result2.unwrap().unwrap();
      assert_eq!(r2.source_code, b"export const loaded = true;\n");
1297
      // Not MediaType::TypeScript due to .headers.json modification
1298 1299 1300 1301
      assert_eq!(&(r2.media_type), &msg::MediaType::JavaScript);
    });
  }

1302 1303
  #[test]
  fn test_fetch_source_1() {
A
Andy Hayden 已提交
1304
    use crate::tokio_util;
R
Ryan Dahl 已提交
1305 1306
    // http_util::fetch_sync_string requires tokio
    tokio_util::init(|| {
1307
      let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1308 1309 1310 1311 1312 1313 1314 1315
      let module_name =
        "http://localhost:4545/tests/subdir/mt_video_mp2t.t3.ts";
      let filename = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("localhost_PORT4545/tests/subdir/mt_video_mp2t.t3.ts")
          .as_ref(),
      );
1316
      let headers_file_name = source_code_headers_filename(&filename);
R
Ryan Dahl 已提交
1317

1318
      let result = fetch_remote_source(&deno_dir, module_name, &filename);
R
Ryan Dahl 已提交
1319
      assert!(result.is_ok());
1320
      let r = result.unwrap().unwrap();
K
Kitson Kelly 已提交
1321
      assert_eq!(r.source_code, "export const loaded = true;\n".as_bytes());
1322
      assert_eq!(&(r.media_type), &msg::MediaType::TypeScript);
1323 1324
      // matching ext, no .headers.json file created
      assert!(fs::read_to_string(&headers_file_name).is_err());
R
Ryan Dahl 已提交
1325

1326 1327 1328 1329 1330 1331 1332
      // Modify .headers.json, make sure read from local
      save_source_code_headers(
        &filename,
        Some("text/javascript".to_owned()),
        None,
      );
      let result2 = fetch_local_source(&deno_dir, module_name, &filename, None);
R
Ryan Dahl 已提交
1333
      assert!(result2.is_ok());
1334
      let r2 = result2.unwrap().unwrap();
K
Kitson Kelly 已提交
1335
      assert_eq!(r2.source_code, "export const loaded = true;\n".as_bytes());
1336
      // Not MediaType::TypeScript due to .headers.json modification
1337
      assert_eq!(&(r2.media_type), &msg::MediaType::JavaScript);
R
Ryan Dahl 已提交
1338 1339 1340 1341
    });
  }

  #[test]
1342
  fn test_fetch_source_2() {
A
Andy Hayden 已提交
1343
    use crate::tokio_util;
1344 1345
    // http_util::fetch_sync_string requires tokio
    tokio_util::init(|| {
1346
      let (_temp_dir, deno_dir) = test_setup();
1347 1348 1349 1350 1351 1352 1353
      let module_name = "http://localhost:4545/tests/subdir/no_ext";
      let filename = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("localhost_PORT4545/tests/subdir/no_ext")
          .as_ref(),
      );
1354
      let result = fetch_remote_source(&deno_dir, module_name, &filename);
1355 1356
      assert!(result.is_ok());
      let r = result.unwrap().unwrap();
K
Kitson Kelly 已提交
1357
      assert_eq!(r.source_code, "export const loaded = true;\n".as_bytes());
1358
      assert_eq!(&(r.media_type), &msg::MediaType::TypeScript);
1359
      // no ext, should create .headers.json file
1360
      assert_eq!(
1361
        get_source_code_headers(&filename).mime_type.unwrap(),
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
        "text/typescript"
      );

      let module_name_2 = "http://localhost:4545/tests/subdir/mismatch_ext.ts";
      let filename_2 = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("localhost_PORT4545/tests/subdir/mismatch_ext.ts")
          .as_ref(),
      );
1372
      let result_2 = fetch_remote_source(&deno_dir, module_name_2, &filename_2);
1373 1374
      assert!(result_2.is_ok());
      let r2 = result_2.unwrap().unwrap();
K
Kitson Kelly 已提交
1375
      assert_eq!(r2.source_code, "export const loaded = true;\n".as_bytes());
1376
      assert_eq!(&(r2.media_type), &msg::MediaType::JavaScript);
1377
      // mismatch ext, should create .headers.json file
1378
      assert_eq!(
1379
        get_source_code_headers(&filename_2).mime_type.unwrap(),
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
        "text/javascript"
      );

      // test unknown extension
      let module_name_3 = "http://localhost:4545/tests/subdir/unknown_ext.deno";
      let filename_3 = deno_fs::normalize_path(
        deno_dir
          .deps_http
          .join("localhost_PORT4545/tests/subdir/unknown_ext.deno")
          .as_ref(),
      );
1391
      let result_3 = fetch_remote_source(&deno_dir, module_name_3, &filename_3);
1392 1393
      assert!(result_3.is_ok());
      let r3 = result_3.unwrap().unwrap();
K
Kitson Kelly 已提交
1394
      assert_eq!(r3.source_code, "export const loaded = true;\n".as_bytes());
1395
      assert_eq!(&(r3.media_type), &msg::MediaType::TypeScript);
1396
      // unknown ext, should create .headers.json file
1397
      assert_eq!(
1398
        get_source_code_headers(&filename_3).mime_type.unwrap(),
1399 1400 1401 1402 1403 1404 1405
        "text/typescript"
      );
    });
  }

  #[test]
  fn test_fetch_source_3() {
R
Ryan Dahl 已提交
1406
    // only local, no http_util::fetch_sync_string called
1407
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1408 1409 1410 1411 1412 1413
    let cwd = std::env::current_dir().unwrap();
    let cwd_string = cwd.to_str().unwrap();
    let module_name = "http://example.com/mt_text_typescript.t1.ts"; // not used
    let filename =
      format!("{}/tests/subdir/mt_text_typescript.t1.ts", &cwd_string);

1414
    let result = fetch_local_source(&deno_dir, module_name, &filename, None);
R
Ryan Dahl 已提交
1415
    assert!(result.is_ok());
1416
    let r = result.unwrap().unwrap();
K
Kitson Kelly 已提交
1417
    assert_eq!(r.source_code, "export const loaded = true;\n".as_bytes());
1418
    assert_eq!(&(r.media_type), &msg::MediaType::TypeScript);
R
Ryan Dahl 已提交
1419 1420 1421
  }

  #[test]
K
Kitson Kelly 已提交
1422
  fn test_fetch_module_meta_data() {
1423
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1424 1425 1426 1427

    let cwd = std::env::current_dir().unwrap();
    let cwd_string = String::from(cwd.to_str().unwrap()) + "/";

1428 1429 1430 1431
    tokio_util::init(|| {
      // Test failure case.
      let specifier = "hello.ts";
      let referrer = add_root!("/baddir/badfile.ts");
1432
      let r = deno_dir.fetch_module_meta_data(specifier, referrer, true);
1433 1434 1435 1436 1437
      assert!(r.is_err());

      // Assuming cwd is the deno repo root.
      let specifier = "./js/main.ts";
      let referrer = cwd_string.as_str();
1438
      let r = deno_dir.fetch_module_meta_data(specifier, referrer, true);
1439 1440
      assert!(r.is_ok());
    })
R
Ryan Dahl 已提交
1441 1442
  }

1443
  #[test]
K
Kitson Kelly 已提交
1444
  fn test_fetch_module_meta_data_1() {
1445
    /*recompile ts file*/
1446
    let (_temp_dir, deno_dir) = test_setup();
1447 1448 1449 1450

    let cwd = std::env::current_dir().unwrap();
    let cwd_string = String::from(cwd.to_str().unwrap()) + "/";

1451 1452 1453 1454
    tokio_util::init(|| {
      // Test failure case.
      let specifier = "hello.ts";
      let referrer = add_root!("/baddir/badfile.ts");
1455
      let r = deno_dir.fetch_module_meta_data(specifier, referrer, false);
1456 1457 1458 1459 1460
      assert!(r.is_err());

      // Assuming cwd is the deno repo root.
      let specifier = "./js/main.ts";
      let referrer = cwd_string.as_str();
1461
      let r = deno_dir.fetch_module_meta_data(specifier, referrer, false);
1462 1463
      assert!(r.is_ok());
    })
1464 1465
  }

R
Ryan Dahl 已提交
1466 1467
  #[test]
  fn test_src_file_to_url_1() {
1468
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
    assert_eq!("hello", deno_dir.src_file_to_url("hello"));
    assert_eq!("/hello", deno_dir.src_file_to_url("/hello"));
    let x = deno_dir.deps_http.join("hello/world.txt");
    assert_eq!(
      "http://hello/world.txt",
      deno_dir.src_file_to_url(x.to_str().unwrap())
    );
  }

  #[test]
  fn test_src_file_to_url_2() {
1480
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
    assert_eq!("hello", deno_dir.src_file_to_url("hello"));
    assert_eq!("/hello", deno_dir.src_file_to_url("/hello"));
    let x = deno_dir.deps_https.join("hello/world.txt");
    assert_eq!(
      "https://hello/world.txt",
      deno_dir.src_file_to_url(x.to_str().unwrap())
    );
  }

  #[test]
  fn test_src_file_to_url_3() {
1492
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1493 1494 1495 1496 1497 1498 1499 1500 1501
    let x = deno_dir.deps_http.join("localhost_PORT4545/world.txt");
    assert_eq!(
      "http://localhost:4545/world.txt",
      deno_dir.src_file_to_url(x.to_str().unwrap())
    );
  }

  #[test]
  fn test_src_file_to_url_4() {
1502
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
    let x = deno_dir.deps_https.join("localhost_PORT4545/world.txt");
    assert_eq!(
      "https://localhost:4545/world.txt",
      deno_dir.src_file_to_url(x.to_str().unwrap())
    );
  }

  // https://github.com/denoland/deno/blob/golang/os_test.go#L16-L87
  #[test]
  fn test_resolve_module_1() {
1513
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1514 1515 1516 1517

    let test_cases = [
      (
        "./subdir/print_hello.ts",
1518
        add_root!("/Users/rld/go/src/github.com/denoland/deno/testdata/006_url_imports.ts"),
R
Ryan Dahl 已提交
1519
        file_url!("/Users/rld/go/src/github.com/denoland/deno/testdata/subdir/print_hello.ts"),
1520
        add_root!("/Users/rld/go/src/github.com/denoland/deno/testdata/subdir/print_hello.ts"),
R
Ryan Dahl 已提交
1521 1522 1523 1524
      ),
      (
        "testdata/001_hello.js",
        add_root!("/Users/rld/go/src/github.com/denoland/deno/"),
R
Ryan Dahl 已提交
1525
        file_url!("/Users/rld/go/src/github.com/denoland/deno/testdata/001_hello.js"),
R
Ryan Dahl 已提交
1526 1527 1528 1529 1530
        add_root!("/Users/rld/go/src/github.com/denoland/deno/testdata/001_hello.js"),
      ),
      (
        add_root!("/Users/rld/src/deno/hello.js"),
        ".",
R
Ryan Dahl 已提交
1531
        file_url!("/Users/rld/src/deno/hello.js"),
R
Ryan Dahl 已提交
1532 1533 1534 1535 1536
        add_root!("/Users/rld/src/deno/hello.js"),
      ),
      (
        add_root!("/this/module/got/imported.js"),
        add_root!("/that/module/did/it.js"),
R
Ryan Dahl 已提交
1537
        file_url!("/this/module/got/imported.js"),
R
Ryan Dahl 已提交
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
        add_root!("/this/module/got/imported.js"),
      ),
    ];
    for &test in test_cases.iter() {
      let specifier = String::from(test.0);
      let referrer = String::from(test.1);
      let (module_name, filename) =
        deno_dir.resolve_module(&specifier, &referrer).unwrap();
      assert_eq!(module_name, test.2);
      assert_eq!(filename, test.3);
    }
  }

  #[test]
  fn test_resolve_module_2() {
1553
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574

    let specifier = "http://localhost:4545/testdata/subdir/print_hello.ts";
    let referrer = add_root!("/deno/testdata/006_url_imports.ts");

    let expected_module_name =
      "http://localhost:4545/testdata/subdir/print_hello.ts";
    let expected_filename = deno_fs::normalize_path(
      deno_dir
        .deps_http
        .join("localhost_PORT4545/testdata/subdir/print_hello.ts")
        .as_ref(),
    );

    let (module_name, filename) =
      deno_dir.resolve_module(specifier, referrer).unwrap();
    assert_eq!(module_name, expected_module_name);
    assert_eq!(filename, expected_filename);
  }

  #[test]
  fn test_resolve_module_3() {
1575
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597

    let specifier_ =
      deno_dir.deps_http.join("unpkg.com/liltest@0.0.5/index.ts");
    let specifier = specifier_.to_str().unwrap();
    let referrer = ".";

    let expected_module_name = "http://unpkg.com/liltest@0.0.5/index.ts";
    let expected_filename = deno_fs::normalize_path(
      deno_dir
        .deps_http
        .join("unpkg.com/liltest@0.0.5/index.ts")
        .as_ref(),
    );

    let (module_name, filename) =
      deno_dir.resolve_module(specifier, referrer).unwrap();
    assert_eq!(module_name, expected_module_name);
    assert_eq!(filename, expected_filename);
  }

  #[test]
  fn test_resolve_module_4() {
1598
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620

    let specifier = "./util";
    let referrer_ = deno_dir.deps_http.join("unpkg.com/liltest@0.0.5/index.ts");
    let referrer = referrer_.to_str().unwrap();

    // http containing files -> load relative import with http
    let expected_module_name = "http://unpkg.com/liltest@0.0.5/util";
    let expected_filename = deno_fs::normalize_path(
      deno_dir
        .deps_http
        .join("unpkg.com/liltest@0.0.5/util")
        .as_ref(),
    );

    let (module_name, filename) =
      deno_dir.resolve_module(specifier, referrer).unwrap();
    assert_eq!(module_name, expected_module_name);
    assert_eq!(filename, expected_filename);
  }

  #[test]
  fn test_resolve_module_5() {
1621
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644

    let specifier = "./util";
    let referrer_ =
      deno_dir.deps_https.join("unpkg.com/liltest@0.0.5/index.ts");
    let referrer = referrer_.to_str().unwrap();

    // https containing files -> load relative import with https
    let expected_module_name = "https://unpkg.com/liltest@0.0.5/util";
    let expected_filename = deno_fs::normalize_path(
      deno_dir
        .deps_https
        .join("unpkg.com/liltest@0.0.5/util")
        .as_ref(),
    );

    let (module_name, filename) =
      deno_dir.resolve_module(specifier, referrer).unwrap();
    assert_eq!(module_name, expected_module_name);
    assert_eq!(filename, expected_filename);
  }

  #[test]
  fn test_resolve_module_6() {
1645
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664

    let specifier = "http://localhost:4545/tests/subdir/mod2.ts";
    let referrer = add_root!("/deno/tests/006_url_imports.ts");
    let expected_module_name = "http://localhost:4545/tests/subdir/mod2.ts";
    let expected_filename = deno_fs::normalize_path(
      deno_dir
        .deps_http
        .join("localhost_PORT4545/tests/subdir/mod2.ts")
        .as_ref(),
    );

    let (module_name, filename) =
      deno_dir.resolve_module(specifier, referrer).unwrap();
    assert_eq!(module_name, expected_module_name);
    assert_eq!(filename, expected_filename);
  }

  #[test]
  fn test_resolve_module_7() {
1665
    let (_temp_dir, deno_dir) = test_setup();
R
Ryan Dahl 已提交
1666 1667 1668

    let specifier = "http_test.ts";
    let referrer = add_root!("/Users/rld/src/deno_net/");
1669 1670
    let expected_module_name =
      file_url!("/Users/rld/src/deno_net/http_test.ts");
R
Ryan Dahl 已提交
1671 1672 1673 1674 1675 1676 1677 1678
    let expected_filename = add_root!("/Users/rld/src/deno_net/http_test.ts");

    let (module_name, filename) =
      deno_dir.resolve_module(specifier, referrer).unwrap();
    assert_eq!(module_name, expected_module_name);
    assert_eq!(filename, expected_filename);
  }

1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
  #[test]
  fn test_resolve_module_8() {
    let (_temp_dir, deno_dir) = test_setup();

    let specifier = "/util";
    let referrer_ =
      deno_dir.deps_https.join("unpkg.com/liltest@0.0.5/index.ts");
    let referrer = referrer_.to_str().unwrap();

    let expected_module_name = "https://unpkg.com/util";
    let expected_filename = deno_fs::normalize_path(
      deno_dir.deps_https.join("unpkg.com/util").as_ref(),
    );

    let (module_name, filename) =
      deno_dir.resolve_module(specifier, referrer).unwrap();
    assert_eq!(module_name, expected_module_name);
    assert_eq!(filename, expected_filename);
  }

1699 1700
  #[test]
  fn test_resolve_module_referrer_dot() {
1701
    let (_temp_dir, deno_dir) = test_setup();
1702 1703 1704 1705 1706

    let specifier = "tests/001_hello.js";

    let cwd = std::env::current_dir().unwrap();
    let expected_path = cwd.join(specifier);
R
Ryan Dahl 已提交
1707 1708 1709
    let expected_module_name =
      Url::from_file_path(&expected_path).unwrap().to_string();
    let expected_filename = deno_fs::normalize_path(&expected_path);
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723

    let (module_name, filename) =
      deno_dir.resolve_module(specifier, ".").unwrap();
    assert_eq!(module_name, expected_module_name);
    assert_eq!(filename, expected_filename);

    let (module_name, filename) =
      deno_dir.resolve_module(specifier, "./").unwrap();
    assert_eq!(module_name, expected_module_name);
    assert_eq!(filename, expected_filename);
  }

  #[test]
  fn test_resolve_module_referrer_dotdot() {
1724
    let (_temp_dir, deno_dir) = test_setup();
1725 1726 1727 1728 1729

    let specifier = "tests/001_hello.js";

    let cwd = std::env::current_dir().unwrap();
    let expected_path = cwd.join("..").join(specifier);
R
Ryan Dahl 已提交
1730 1731 1732
    let expected_module_name =
      Url::from_file_path(&expected_path).unwrap().to_string();
    let expected_filename = deno_fs::normalize_path(&expected_path);
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744

    let (module_name, filename) =
      deno_dir.resolve_module(specifier, "..").unwrap();
    assert_eq!(module_name, expected_module_name);
    assert_eq!(filename, expected_filename);

    let (module_name, filename) =
      deno_dir.resolve_module(specifier, "../").unwrap();
    assert_eq!(module_name, expected_module_name);
    assert_eq!(filename, expected_filename);
  }

R
Ryan Dahl 已提交
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
  #[test]
  fn test_map_file_extension() {
    assert_eq!(
      map_file_extension(Path::new("foo/bar.ts")),
      msg::MediaType::TypeScript
    );
    assert_eq!(
      map_file_extension(Path::new("foo/bar.d.ts")),
      msg::MediaType::TypeScript
    );
    assert_eq!(
      map_file_extension(Path::new("foo/bar.js")),
      msg::MediaType::JavaScript
    );
    assert_eq!(
      map_file_extension(Path::new("foo/bar.json")),
      msg::MediaType::Json
    );
    assert_eq!(
      map_file_extension(Path::new("foo/bar.txt")),
      msg::MediaType::Unknown
    );
    assert_eq!(
      map_file_extension(Path::new("foo/bar")),
      msg::MediaType::Unknown
    );
  }

  #[test]
  fn test_map_content_type() {
    // Extension only
    assert_eq!(
      map_content_type(Path::new("foo/bar.ts"), None),
      msg::MediaType::TypeScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar.d.ts"), None),
      msg::MediaType::TypeScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar.js"), None),
      msg::MediaType::JavaScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar.json"), None),
      msg::MediaType::Json
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar.txt"), None),
      msg::MediaType::Unknown
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), None),
      msg::MediaType::Unknown
    );

    // Media Type
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("application/typescript")),
      msg::MediaType::TypeScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("text/typescript")),
      msg::MediaType::TypeScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("video/vnd.dlna.mpeg-tts")),
      msg::MediaType::TypeScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("video/mp2t")),
      msg::MediaType::TypeScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("application/x-typescript")),
      msg::MediaType::TypeScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("application/javascript")),
      msg::MediaType::JavaScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("text/javascript")),
      msg::MediaType::JavaScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("application/ecmascript")),
      msg::MediaType::JavaScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("text/ecmascript")),
      msg::MediaType::JavaScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("application/x-javascript")),
      msg::MediaType::JavaScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("application/json")),
      msg::MediaType::Json
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar"), Some("text/json")),
      msg::MediaType::Json
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar.ts"), Some("text/plain")),
      msg::MediaType::TypeScript
    );
    assert_eq!(
      map_content_type(Path::new("foo/bar.ts"), Some("foo/bar")),
      msg::MediaType::Unknown
    );
  }

  #[test]
  fn test_filter_shebang() {
B
Bert Belder 已提交
1862
    assert_eq!(filter_shebang(b"#!"[..].to_owned()), b"");
K
Kitson Kelly 已提交
1863 1864 1865 1866 1867 1868 1869 1870
    assert_eq!(
      filter_shebang("#!\n\n".as_bytes().to_owned()),
      "\n\n".as_bytes()
    );
    let code = "#!/usr/bin/env deno\nconsole.log('hello');\n"
      .as_bytes()
      .to_owned();
    assert_eq!(filter_shebang(code), "\nconsole.log('hello');\n".as_bytes());
R
Ryan Dahl 已提交
1871
  }
R
Ryan Dahl 已提交
1872
}