1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-03 04:48:52 -05:00

cli/msg.rs -> cli/media_type.rs

This commit is contained in:
Ryan Dahl 2020-09-15 10:33:14 -04:00
parent 68099acbc6
commit b2fa903d64
9 changed files with 147 additions and 163 deletions

View file

@ -1,6 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use crate::msg::MediaType; use crate::media_type::MediaType;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use std::error::Error; use std::error::Error;

View file

@ -5,7 +5,7 @@ use crate::http_cache::HttpCache;
use crate::http_util; use crate::http_util;
use crate::http_util::create_http_client; use crate::http_util::create_http_client;
use crate::http_util::FetchOnceResult; use crate::http_util::FetchOnceResult;
use crate::msg; use crate::media_type::MediaType;
use crate::permissions::Permissions; use crate::permissions::Permissions;
use crate::text_encoding; use crate::text_encoding;
use deno_core::error::custom_error; use deno_core::error::custom_error;
@ -79,7 +79,7 @@ pub struct SourceFile {
pub url: Url, pub url: Url,
pub filename: PathBuf, pub filename: PathBuf,
pub types_header: Option<String>, pub types_header: Option<String>,
pub media_type: msg::MediaType, pub media_type: MediaType,
pub source_code: TextDocument, pub source_code: TextDocument,
} }
@ -573,7 +573,7 @@ impl SourceFileFetcher {
fn map_content_type( fn map_content_type(
path: &Path, path: &Path,
content_type: Option<&str>, content_type: Option<&str>,
) -> (msg::MediaType, Option<String>) { ) -> (MediaType, Option<String>) {
match content_type { match content_type {
Some(content_type) => { Some(content_type) => {
// Sometimes there is additional data after the media type in // Sometimes there is additional data after the media type in
@ -587,7 +587,7 @@ fn map_content_type(
| "video/vnd.dlna.mpeg-tts" | "video/vnd.dlna.mpeg-tts"
| "video/mp2t" | "video/mp2t"
| "application/x-typescript" => { | "application/x-typescript" => {
map_js_like_extension(path, msg::MediaType::TypeScript) map_js_like_extension(path, MediaType::TypeScript)
} }
"application/javascript" "application/javascript"
| "text/javascript" | "text/javascript"
@ -595,15 +595,15 @@ fn map_content_type(
| "text/ecmascript" | "text/ecmascript"
| "application/x-javascript" | "application/x-javascript"
| "application/node" => { | "application/node" => {
map_js_like_extension(path, msg::MediaType::JavaScript) map_js_like_extension(path, MediaType::JavaScript)
} }
"application/json" | "text/json" => msg::MediaType::Json, "application/json" | "text/json" => MediaType::Json,
"application/wasm" => msg::MediaType::Wasm, "application/wasm" => MediaType::Wasm,
// Handle plain and possibly webassembly // Handle plain and possibly webassembly
"text/plain" | "application/octet-stream" => msg::MediaType::from(path), "text/plain" | "application/octet-stream" => MediaType::from(path),
_ => { _ => {
debug!("unknown content type: {}", content_type); debug!("unknown content type: {}", content_type);
msg::MediaType::Unknown MediaType::Unknown
} }
}; };
@ -614,20 +614,17 @@ fn map_content_type(
(media_type, charset) (media_type, charset)
} }
None => (msg::MediaType::from(path), None), None => (MediaType::from(path), None),
} }
} }
fn map_js_like_extension( fn map_js_like_extension(path: &Path, default: MediaType) -> MediaType {
path: &Path,
default: msg::MediaType,
) -> msg::MediaType {
match path.extension() { match path.extension() {
None => default, None => default,
Some(os_str) => match os_str.to_str() { Some(os_str) => match os_str.to_str() {
None => default, None => default,
Some("jsx") => msg::MediaType::JSX, Some("jsx") => MediaType::JSX,
Some("tsx") => msg::MediaType::TSX, Some("tsx") => MediaType::TSX,
Some(_) => default, Some(_) => default,
}, },
} }
@ -816,7 +813,7 @@ mod tests {
r.source_code.bytes, r.source_code.bytes,
&b"export { printHello } from \"./print_hello.ts\";\n"[..] &b"export { printHello } from \"./print_hello.ts\";\n"[..]
); );
assert_eq!(&(r.media_type), &msg::MediaType::TypeScript); assert_eq!(&(r.media_type), &MediaType::TypeScript);
let mut metadata = let mut metadata =
crate::http_cache::Metadata::read(&cache_filename).unwrap(); crate::http_cache::Metadata::read(&cache_filename).unwrap();
@ -847,7 +844,7 @@ mod tests {
); );
// If get_source_file does not call remote, this should be JavaScript // If get_source_file does not call remote, this should be JavaScript
// as we modified before! (we do not overwrite .headers.json due to no http fetch) // as we modified before! (we do not overwrite .headers.json due to no http fetch)
assert_eq!(&(r2.media_type), &msg::MediaType::JavaScript); assert_eq!(&(r2.media_type), &MediaType::JavaScript);
let (_, headers) = fetcher_2.http_cache.get(&module_url_1).unwrap(); let (_, headers) = fetcher_2.http_cache.get(&module_url_1).unwrap();
assert_eq!( assert_eq!(
@ -886,7 +883,7 @@ mod tests {
); );
// If get_source_file does not call remote, this should be JavaScript // If get_source_file does not call remote, this should be JavaScript
// as we modified before! (we do not overwrite .headers.json due to no http fetch) // as we modified before! (we do not overwrite .headers.json due to no http fetch)
assert_eq!(&(r3.media_type), &msg::MediaType::Json); assert_eq!(&(r3.media_type), &MediaType::Json);
let metadata = crate::http_cache::Metadata::read(&cache_filename).unwrap(); let metadata = crate::http_cache::Metadata::read(&cache_filename).unwrap();
assert_eq!( assert_eq!(
metadata metadata
@ -916,7 +913,7 @@ mod tests {
let expected4 = &b"export { printHello } from \"./print_hello.ts\";\n"[..]; let expected4 = &b"export { printHello } from \"./print_hello.ts\";\n"[..];
assert_eq!(r4.source_code.bytes, expected4); assert_eq!(r4.source_code.bytes, expected4);
// Resolved back to TypeScript // Resolved back to TypeScript
assert_eq!(&(r4.media_type), &msg::MediaType::TypeScript); assert_eq!(&(r4.media_type), &MediaType::TypeScript);
} }
#[tokio::test] #[tokio::test]
@ -943,7 +940,7 @@ mod tests {
let r = result.unwrap(); let r = result.unwrap();
let expected = b"export const loaded = true;\n"; let expected = b"export const loaded = true;\n";
assert_eq!(r.source_code.bytes, expected); assert_eq!(r.source_code.bytes, expected);
assert_eq!(&(r.media_type), &msg::MediaType::JavaScript); assert_eq!(&(r.media_type), &MediaType::JavaScript);
let (_, headers) = fetcher.http_cache.get(&module_url).unwrap(); let (_, headers) = fetcher.http_cache.get(&module_url).unwrap();
assert_eq!( assert_eq!(
headers headers
@ -982,7 +979,7 @@ mod tests {
// If get_source_file does not call remote, this should be TypeScript // If get_source_file does not call remote, this should be TypeScript
// as we modified before! (we do not overwrite .headers.json due to no http // as we modified before! (we do not overwrite .headers.json due to no http
// fetch) // fetch)
assert_eq!(&(r2.media_type), &msg::MediaType::TypeScript); assert_eq!(&(r2.media_type), &MediaType::TypeScript);
let metadata = crate::http_cache::Metadata::read(&cache_filename).unwrap(); let metadata = crate::http_cache::Metadata::read(&cache_filename).unwrap();
assert_eq!( assert_eq!(
metadata metadata
@ -1013,7 +1010,7 @@ mod tests {
assert_eq!(r3.source_code.bytes, expected3); assert_eq!(r3.source_code.bytes, expected3);
// Now the old .headers.json file should be overwritten back to JavaScript! // Now the old .headers.json file should be overwritten back to JavaScript!
// (due to http fetch) // (due to http fetch)
assert_eq!(&(r3.media_type), &msg::MediaType::JavaScript); assert_eq!(&(r3.media_type), &MediaType::JavaScript);
let (_, headers) = fetcher.http_cache.get(&module_url).unwrap(); let (_, headers) = fetcher.http_cache.get(&module_url).unwrap();
assert_eq!( assert_eq!(
headers headers
@ -1429,7 +1426,7 @@ mod tests {
assert!(result.is_ok()); assert!(result.is_ok());
let r = result.unwrap(); let r = result.unwrap();
assert_eq!(r.source_code.bytes, b"export const loaded = true;\n"); assert_eq!(r.source_code.bytes, b"export const loaded = true;\n");
assert_eq!(&(r.media_type), &msg::MediaType::TypeScript); assert_eq!(&(r.media_type), &MediaType::TypeScript);
// Modify .metadata.json, make sure read from local // Modify .metadata.json, make sure read from local
let cache_filename = fetcher.http_cache.get_cache_filename(&module_url); let cache_filename = fetcher.http_cache.get_cache_filename(&module_url);
@ -1448,7 +1445,7 @@ mod tests {
let r2 = result2.unwrap().unwrap(); let r2 = result2.unwrap().unwrap();
assert_eq!(r2.source_code.bytes, b"export const loaded = true;\n"); assert_eq!(r2.source_code.bytes, b"export const loaded = true;\n");
// Not MediaType::TypeScript due to .headers.json modification // Not MediaType::TypeScript due to .headers.json modification
assert_eq!(&(r2.media_type), &msg::MediaType::JavaScript); assert_eq!(&(r2.media_type), &MediaType::JavaScript);
} }
#[tokio::test] #[tokio::test]
@ -1469,7 +1466,7 @@ mod tests {
assert!(result.is_ok()); assert!(result.is_ok());
let r = result.unwrap(); let r = result.unwrap();
assert_eq!(r.source_code.bytes, b"export const loaded = true;\n"); assert_eq!(r.source_code.bytes, b"export const loaded = true;\n");
assert_eq!(&(r.media_type), &msg::MediaType::TypeScript); assert_eq!(&(r.media_type), &MediaType::TypeScript);
let (_, headers) = fetcher.http_cache.get(module_url).unwrap(); let (_, headers) = fetcher.http_cache.get(module_url).unwrap();
assert_eq!( assert_eq!(
headers headers
@ -1501,7 +1498,7 @@ mod tests {
assert!(result.is_ok()); assert!(result.is_ok());
let r2 = result.unwrap(); let r2 = result.unwrap();
assert_eq!(r2.source_code.bytes, b"export const loaded = true;\n"); assert_eq!(r2.source_code.bytes, b"export const loaded = true;\n");
assert_eq!(&(r2.media_type), &msg::MediaType::JavaScript); assert_eq!(&(r2.media_type), &MediaType::JavaScript);
let (_, headers) = fetcher.http_cache.get(module_url).unwrap(); let (_, headers) = fetcher.http_cache.get(module_url).unwrap();
assert_eq!( assert_eq!(
headers headers
@ -1533,7 +1530,7 @@ mod tests {
assert!(result.is_ok()); assert!(result.is_ok());
let r3 = result.unwrap(); let r3 = result.unwrap();
assert_eq!(r3.source_code.bytes, b"export const loaded = true;\n"); assert_eq!(r3.source_code.bytes, b"export const loaded = true;\n");
assert_eq!(&(r3.media_type), &msg::MediaType::TypeScript); assert_eq!(&(r3.media_type), &MediaType::TypeScript);
let (_, headers) = fetcher.http_cache.get(module_url).unwrap(); let (_, headers) = fetcher.http_cache.get(module_url).unwrap();
assert_eq!( assert_eq!(
headers headers
@ -1682,43 +1679,43 @@ mod tests {
// Extension only // Extension only
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.ts"), None).0, map_content_type(Path::new("foo/bar.ts"), None).0,
msg::MediaType::TypeScript MediaType::TypeScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.tsx"), None).0, map_content_type(Path::new("foo/bar.tsx"), None).0,
msg::MediaType::TSX MediaType::TSX
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.d.ts"), None).0, map_content_type(Path::new("foo/bar.d.ts"), None).0,
msg::MediaType::TypeScript MediaType::TypeScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.js"), None).0, map_content_type(Path::new("foo/bar.js"), None).0,
msg::MediaType::JavaScript MediaType::JavaScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.txt"), None).0, map_content_type(Path::new("foo/bar.txt"), None).0,
msg::MediaType::Unknown MediaType::Unknown
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.jsx"), None).0, map_content_type(Path::new("foo/bar.jsx"), None).0,
msg::MediaType::JSX MediaType::JSX
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.json"), None).0, map_content_type(Path::new("foo/bar.json"), None).0,
msg::MediaType::Json MediaType::Json
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.wasm"), None).0, map_content_type(Path::new("foo/bar.wasm"), None).0,
msg::MediaType::Wasm MediaType::Wasm
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.cjs"), None).0, map_content_type(Path::new("foo/bar.cjs"), None).0,
msg::MediaType::JavaScript MediaType::JavaScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), None).0, map_content_type(Path::new("foo/bar"), None).0,
msg::MediaType::Unknown MediaType::Unknown
); );
} }
@ -1727,61 +1724,61 @@ mod tests {
// Media Type // Media Type
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("application/typescript")).0, map_content_type(Path::new("foo/bar"), Some("application/typescript")).0,
msg::MediaType::TypeScript MediaType::TypeScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("text/typescript")).0, map_content_type(Path::new("foo/bar"), Some("text/typescript")).0,
msg::MediaType::TypeScript MediaType::TypeScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("video/vnd.dlna.mpeg-tts")).0, map_content_type(Path::new("foo/bar"), Some("video/vnd.dlna.mpeg-tts")).0,
msg::MediaType::TypeScript MediaType::TypeScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("video/mp2t")).0, map_content_type(Path::new("foo/bar"), Some("video/mp2t")).0,
msg::MediaType::TypeScript MediaType::TypeScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("application/x-typescript")) map_content_type(Path::new("foo/bar"), Some("application/x-typescript"))
.0, .0,
msg::MediaType::TypeScript MediaType::TypeScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("application/javascript")).0, map_content_type(Path::new("foo/bar"), Some("application/javascript")).0,
msg::MediaType::JavaScript MediaType::JavaScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("text/javascript")).0, map_content_type(Path::new("foo/bar"), Some("text/javascript")).0,
msg::MediaType::JavaScript MediaType::JavaScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("application/ecmascript")).0, map_content_type(Path::new("foo/bar"), Some("application/ecmascript")).0,
msg::MediaType::JavaScript MediaType::JavaScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("text/ecmascript")).0, map_content_type(Path::new("foo/bar"), Some("text/ecmascript")).0,
msg::MediaType::JavaScript MediaType::JavaScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("application/x-javascript")) map_content_type(Path::new("foo/bar"), Some("application/x-javascript"))
.0, .0,
msg::MediaType::JavaScript MediaType::JavaScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("application/json")).0, map_content_type(Path::new("foo/bar"), Some("application/json")).0,
msg::MediaType::Json MediaType::Json
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("application/node")).0, map_content_type(Path::new("foo/bar"), Some("application/node")).0,
msg::MediaType::JavaScript MediaType::JavaScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("text/json")).0, map_content_type(Path::new("foo/bar"), Some("text/json")).0,
msg::MediaType::Json MediaType::Json
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar"), Some("text/json; charset=utf-8 ")), map_content_type(Path::new("foo/bar"), Some("text/json; charset=utf-8 ")),
(msg::MediaType::Json, Some("utf-8".to_owned())) (MediaType::Json, Some("utf-8".to_owned()))
); );
} }
@ -1789,11 +1786,11 @@ mod tests {
fn test_map_file_extension_media_type_with_extension() { fn test_map_file_extension_media_type_with_extension() {
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.ts"), Some("text/plain")).0, map_content_type(Path::new("foo/bar.ts"), Some("text/plain")).0,
msg::MediaType::TypeScript MediaType::TypeScript
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.ts"), Some("foo/bar")).0, map_content_type(Path::new("foo/bar.ts"), Some("foo/bar")).0,
msg::MediaType::Unknown MediaType::Unknown
); );
assert_eq!( assert_eq!(
map_content_type( map_content_type(
@ -1801,7 +1798,7 @@ mod tests {
Some("application/typescript"), Some("application/typescript"),
) )
.0, .0,
msg::MediaType::TSX MediaType::TSX
); );
assert_eq!( assert_eq!(
map_content_type( map_content_type(
@ -1809,7 +1806,7 @@ mod tests {
Some("application/javascript"), Some("application/javascript"),
) )
.0, .0,
msg::MediaType::TSX MediaType::TSX
); );
assert_eq!( assert_eq!(
map_content_type( map_content_type(
@ -1817,7 +1814,7 @@ mod tests {
Some("application/x-typescript"), Some("application/x-typescript"),
) )
.0, .0,
msg::MediaType::TSX MediaType::TSX
); );
assert_eq!( assert_eq!(
map_content_type( map_content_type(
@ -1825,11 +1822,11 @@ mod tests {
Some("video/vnd.dlna.mpeg-tts"), Some("video/vnd.dlna.mpeg-tts"),
) )
.0, .0,
msg::MediaType::TSX MediaType::TSX
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.tsx"), Some("video/mp2t")).0, map_content_type(Path::new("foo/bar.tsx"), Some("video/mp2t")).0,
msg::MediaType::TSX MediaType::TSX
); );
assert_eq!( assert_eq!(
map_content_type( map_content_type(
@ -1837,7 +1834,7 @@ mod tests {
Some("application/javascript"), Some("application/javascript"),
) )
.0, .0,
msg::MediaType::JSX MediaType::JSX
); );
assert_eq!( assert_eq!(
map_content_type( map_content_type(
@ -1845,7 +1842,7 @@ mod tests {
Some("application/x-typescript"), Some("application/x-typescript"),
) )
.0, .0,
msg::MediaType::JSX MediaType::JSX
); );
assert_eq!( assert_eq!(
map_content_type( map_content_type(
@ -1853,11 +1850,11 @@ mod tests {
Some("application/ecmascript"), Some("application/ecmascript"),
) )
.0, .0,
msg::MediaType::JSX MediaType::JSX
); );
assert_eq!( assert_eq!(
map_content_type(Path::new("foo/bar.jsx"), Some("text/ecmascript")).0, map_content_type(Path::new("foo/bar.jsx"), Some("text/ecmascript")).0,
msg::MediaType::JSX MediaType::JSX
); );
assert_eq!( assert_eq!(
map_content_type( map_content_type(
@ -1865,7 +1862,7 @@ mod tests {
Some("application/x-javascript"), Some("application/x-javascript"),
) )
.0, .0,
msg::MediaType::JSX MediaType::JSX
); );
} }
@ -1896,7 +1893,7 @@ mod tests {
assert!(source.is_ok()); assert!(source.is_ok());
let source = source.unwrap(); let source = source.unwrap();
assert_eq!(source.source_code.bytes, b"console.log('etag')"); assert_eq!(source.source_code.bytes, b"console.log('etag')");
assert_eq!(&(source.media_type), &msg::MediaType::TypeScript); assert_eq!(&(source.media_type), &MediaType::TypeScript);
let (_, headers) = fetcher.http_cache.get(&module_url).unwrap(); let (_, headers) = fetcher.http_cache.get(&module_url).unwrap();
assert_eq!( assert_eq!(
@ -1951,7 +1948,7 @@ mod tests {
assert!(source.is_ok()); assert!(source.is_ok());
let source = source.unwrap(); let source = source.unwrap();
assert_eq!(source.source_code.bytes, b"export const foo = 'foo';"); assert_eq!(source.source_code.bytes, b"export const foo = 'foo';");
assert_eq!(&(source.media_type), &msg::MediaType::JavaScript); assert_eq!(&(source.media_type), &MediaType::JavaScript);
assert_eq!( assert_eq!(
source.types_header, source.types_header,
Some("./xTypeScriptTypes.d.ts".to_string()) Some("./xTypeScriptTypes.d.ts".to_string())
@ -2023,7 +2020,7 @@ mod tests {
assert_eq!(&source.source_code.charset.to_lowercase()[..], charset); assert_eq!(&source.source_code.charset.to_lowercase()[..], charset);
let text = &source.source_code.to_str().unwrap(); let text = &source.source_code.to_str().unwrap();
assert_eq!(text, expected_content); assert_eq!(text, expected_content);
assert_eq!(&(source.media_type), &msg::MediaType::TypeScript); assert_eq!(&(source.media_type), &MediaType::TypeScript);
let (_, headers) = fetcher.http_cache.get(&module_url).unwrap(); let (_, headers) = fetcher.http_cache.get(&module_url).unwrap();
assert_eq!( assert_eq!(

View file

@ -6,10 +6,9 @@ use crate::flags;
use crate::http_cache; use crate::http_cache;
use crate::import_map::ImportMap; use crate::import_map::ImportMap;
use crate::lockfile::Lockfile; use crate::lockfile::Lockfile;
use crate::media_type::MediaType;
use crate::module_graph::ModuleGraphFile; use crate::module_graph::ModuleGraphFile;
use crate::module_graph::ModuleGraphLoader; use crate::module_graph::ModuleGraphLoader;
use crate::msg;
use crate::msg::MediaType;
use crate::permissions::Permissions; use crate::permissions::Permissions;
use crate::state::exit_unstable; use crate::state::exit_unstable;
use crate::tsc::CompiledModule; use crate::tsc::CompiledModule;
@ -202,10 +201,8 @@ impl GlobalState {
// Check if we need to compile files // Check if we need to compile files
let was_compiled = match out.media_type { let was_compiled = match out.media_type {
msg::MediaType::TypeScript MediaType::TypeScript | MediaType::TSX | MediaType::JSX => true,
| msg::MediaType::TSX MediaType::JavaScript => self.ts_compiler.compile_js,
| msg::MediaType::JSX => true,
msg::MediaType::JavaScript => self.ts_compiler.compile_js,
_ => false, _ => false,
}; };
@ -288,10 +285,8 @@ fn needs_compilation(
module_graph_files: &[&ModuleGraphFile], module_graph_files: &[&ModuleGraphFile],
) -> bool { ) -> bool {
let mut needs_compilation = match media_type { let mut needs_compilation = match media_type {
msg::MediaType::TypeScript | msg::MediaType::TSX | msg::MediaType::JSX => { MediaType::TypeScript | MediaType::TSX | MediaType::JSX => true,
true MediaType::JavaScript => compile_js,
}
msg::MediaType::JavaScript => compile_js,
_ => false, _ => false,
}; };

View file

@ -1,7 +1,6 @@
use crate::colors; use crate::colors;
use crate::global_state::GlobalState; use crate::global_state::GlobalState;
use crate::module_graph::{ModuleGraph, ModuleGraphFile, ModuleGraphLoader}; use crate::module_graph::{ModuleGraph, ModuleGraphFile, ModuleGraphLoader};
use crate::msg;
use crate::ModuleSpecifier; use crate::ModuleSpecifier;
use crate::Permissions; use crate::Permissions;
use deno_core::error::AnyError; use deno_core::error::AnyError;
@ -56,7 +55,8 @@ impl ModuleDepInfo {
.get_source_map_file(&module_specifier) .get_source_map_file(&module_specifier)
.ok() .ok()
.map(|file| file.filename.to_string_lossy().to_string()); .map(|file| file.filename.to_string_lossy().to_string());
let file_type = msg::enum_name_media_type(out.media_type).to_string(); let file_type =
crate::media_type::enum_name_media_type(out.media_type).to_string();
let deps = FileInfoDepTree::new(&module_graph, &module_specifier); let deps = FileInfoDepTree::new(&module_graph, &module_specifier);
let dep_count = get_unique_dep_count(&module_graph) - 1; let dep_count = get_unique_dep_count(&module_graph) - 1;
@ -350,8 +350,8 @@ pub fn human_size(bytse: f64) -> String {
mod test { mod test {
use super::*; use super::*;
use crate::ast::Location; use crate::ast::Location;
use crate::media_type::MediaType;
use crate::module_graph::ImportDescriptor; use crate::module_graph::ImportDescriptor;
use crate::MediaType;
#[test] #[test]
fn human_size_test() { fn human_size_test() {

View file

@ -11,7 +11,7 @@ use crate::colors;
use crate::fmt::collect_files; use crate::fmt::collect_files;
use crate::fmt::run_parallelized; use crate::fmt::run_parallelized;
use crate::fmt_errors; use crate::fmt_errors;
use crate::msg; use crate::media_type::MediaType;
use deno_core::error::generic_error; use deno_core::error::generic_error;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_lint::diagnostic::LintDiagnostic; use deno_lint::diagnostic::LintDiagnostic;
@ -131,7 +131,7 @@ fn lint_file(
) -> Result<(Vec<LintDiagnostic>, String), AnyError> { ) -> Result<(Vec<LintDiagnostic>, String), AnyError> {
let file_name = file_path.to_string_lossy().to_string(); let file_name = file_path.to_string_lossy().to_string();
let source_code = fs::read_to_string(&file_path)?; let source_code = fs::read_to_string(&file_path)?;
let media_type = msg::MediaType::from(&file_path); let media_type = MediaType::from(&file_path);
let syntax = ast::get_syntax(&media_type); let syntax = ast::get_syntax(&media_type);
let lint_rules = rules::get_recommended_rules(); let lint_rules = rules::get_recommended_rules();
@ -158,7 +158,7 @@ fn lint_stdin(json: bool) -> Result<(), AnyError> {
}; };
let mut reporter = create_reporter(reporter_kind); let mut reporter = create_reporter(reporter_kind);
let lint_rules = rules::get_recommended_rules(); let lint_rules = rules::get_recommended_rules();
let syntax = ast::get_syntax(&msg::MediaType::TypeScript); let syntax = ast::get_syntax(&MediaType::TypeScript);
let mut linter = create_linter(syntax, lint_rules); let mut linter = create_linter(syntax, lint_rules);
let mut has_error = false; let mut has_error = false;
let pseudo_file_name = "_stdin.ts"; let pseudo_file_name = "_stdin.ts";

View file

@ -49,9 +49,9 @@ pub mod installer;
mod js; mod js;
mod lint; mod lint;
mod lockfile; mod lockfile;
mod media_type;
mod metrics; mod metrics;
mod module_graph; mod module_graph;
pub mod msg;
mod op_fetch_asset; mod op_fetch_asset;
pub mod ops; pub mod ops;
pub mod permissions; pub mod permissions;
@ -77,7 +77,7 @@ use crate::file_fetcher::SourceFileFetcher;
use crate::file_fetcher::TextDocument; use crate::file_fetcher::TextDocument;
use crate::fs as deno_fs; use crate::fs as deno_fs;
use crate::global_state::GlobalState; use crate::global_state::GlobalState;
use crate::msg::MediaType; use crate::media_type::MediaType;
use crate::permissions::Permissions; use crate::permissions::Permissions;
use crate::worker::MainWorker; use crate::worker::MainWorker;
use deno_core::error::AnyError; use deno_core::error::AnyError;
@ -378,7 +378,7 @@ async fn doc_command(
let doc_parser = doc::DocParser::new(loader, private); let doc_parser = doc::DocParser::new(loader, private);
let parse_result = if source_file == "--builtin" { let parse_result = if source_file == "--builtin" {
let syntax = ast::get_syntax(&msg::MediaType::Dts); let syntax = ast::get_syntax(&MediaType::Dts);
doc_parser.parse_source( doc_parser.parse_source(
"lib.deno.d.ts", "lib.deno.d.ts",
syntax, syntax,

View file

@ -117,39 +117,6 @@ pub fn enum_name_media_type(mt: MediaType) -> &'static str {
} }
} }
// Warning! The values in this enum are duplicated in js/compiler.ts
// Update carefully!
#[allow(non_camel_case_types)]
#[repr(i32)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum CompilerRequestType {
Compile = 0,
Bundle = 1,
RuntimeCompile = 2,
RuntimeBundle = 3,
RuntimeTranspile = 4,
}
impl Serialize for CompilerRequestType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let value: i32 = match self {
CompilerRequestType::Compile => 0 as i32,
CompilerRequestType::Bundle => 1 as i32,
CompilerRequestType::RuntimeCompile => 2 as i32,
CompilerRequestType::RuntimeBundle => 3 as i32,
CompilerRequestType::RuntimeTranspile => 4 as i32,
};
Serialize::serialize(&value, serializer)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test] #[test]
fn test_map_file_extension() { fn test_map_file_extension() {
assert_eq!( assert_eq!(
@ -178,4 +145,3 @@ mod tests {
); );
assert_eq!(MediaType::from(Path::new("foo/bar")), MediaType::Unknown); assert_eq!(MediaType::from(Path::new("foo/bar")), MediaType::Unknown);
} }
}

View file

@ -5,7 +5,7 @@ use crate::checksum;
use crate::file_fetcher::SourceFile; use crate::file_fetcher::SourceFile;
use crate::file_fetcher::SourceFileFetcher; use crate::file_fetcher::SourceFileFetcher;
use crate::import_map::ImportMap; use crate::import_map::ImportMap;
use crate::msg::MediaType; use crate::media_type::MediaType;
use crate::permissions::Permissions; use crate::permissions::Permissions;
use crate::tsc::pre_process_file; use crate::tsc::pre_process_file;
use crate::tsc::ImportDesc; use crate::tsc::ImportDesc;

View file

@ -12,10 +12,9 @@ use crate::flags::Flags;
use crate::fmt_errors::JsError; use crate::fmt_errors::JsError;
use crate::global_state::GlobalState; use crate::global_state::GlobalState;
use crate::js; use crate::js;
use crate::media_type::MediaType;
use crate::module_graph::ModuleGraph; use crate::module_graph::ModuleGraph;
use crate::module_graph::ModuleGraphLoader; use crate::module_graph::ModuleGraphLoader;
use crate::msg;
use crate::msg::MediaType;
use crate::ops; use crate::ops;
use crate::permissions::Permissions; use crate::permissions::Permissions;
use crate::source_maps::SourceMapGetter; use crate::source_maps::SourceMapGetter;
@ -35,6 +34,7 @@ use log::Level;
use regex::Regex; use regex::Regex;
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize; use serde::Serialize;
use serde::Serializer;
use serde_json::json; use serde_json::json;
use serde_json::Value; use serde_json::Value;
use sourcemap::SourceMap; use sourcemap::SourceMap;
@ -630,7 +630,7 @@ impl TsCompiler {
); );
let j = json!({ let j = json!({
"type": msg::CompilerRequestType::Compile, "type": CompilerRequestType::Compile,
"target": target, "target": target,
"rootNames": root_names, "rootNames": root_names,
"performance": performance, "performance": performance,
@ -751,7 +751,7 @@ impl TsCompiler {
); );
let j = json!({ let j = json!({
"type": msg::CompilerRequestType::Bundle, "type": CompilerRequestType::Bundle,
"target": target, "target": target,
"rootNames": root_names, "rootNames": root_names,
"performance": performance, "performance": performance,
@ -899,9 +899,7 @@ impl TsCompiler {
// NOTE: JavaScript files are only cached to disk if `checkJs` // NOTE: JavaScript files are only cached to disk if `checkJs`
// option in on // option in on
if source_file.media_type == msg::MediaType::JavaScript if source_file.media_type == MediaType::JavaScript && !self.compile_js {
&& !self.compile_js
{
continue; continue;
} }
@ -948,7 +946,7 @@ impl TsCompiler {
let compiled_module = SourceFile { let compiled_module = SourceFile {
url: module_url.clone(), url: module_url.clone(),
filename: compiled_code_filename, filename: compiled_code_filename,
media_type: msg::MediaType::JavaScript, media_type: MediaType::JavaScript,
source_code: compiled_code.into(), source_code: compiled_code.into(),
types_header: None, types_header: None,
}; };
@ -1005,7 +1003,7 @@ impl TsCompiler {
let source_map_file = SourceFile { let source_map_file = SourceFile {
url: module_specifier.as_url().to_owned(), url: module_specifier.as_url().to_owned(),
filename: source_map_filename, filename: source_map_filename,
media_type: msg::MediaType::JavaScript, media_type: MediaType::JavaScript,
source_code: source_code.into(), source_code: source_code.into(),
types_header: None, types_header: None,
}; };
@ -1268,7 +1266,7 @@ pub async fn runtime_compile(
serde_json::to_value(module_graph).expect("Failed to serialize data"); serde_json::to_value(module_graph).expect("Failed to serialize data");
let req_msg = json!({ let req_msg = json!({
"type": msg::CompilerRequestType::RuntimeCompile, "type": CompilerRequestType::RuntimeCompile,
"target": "runtime", "target": "runtime",
"rootNames": root_names, "rootNames": root_names,
"sourceFileMap": module_graph_json, "sourceFileMap": module_graph_json,
@ -1379,7 +1377,7 @@ pub async fn runtime_bundle(
tsc_config::json_merge(&mut compiler_options, &bundler_options); tsc_config::json_merge(&mut compiler_options, &bundler_options);
let req_msg = json!({ let req_msg = json!({
"type": msg::CompilerRequestType::RuntimeBundle, "type": CompilerRequestType::RuntimeBundle,
"target": "runtime", "target": "runtime",
"rootNames": root_names, "rootNames": root_names,
"sourceFileMap": module_graph_json, "sourceFileMap": module_graph_json,
@ -1420,7 +1418,7 @@ pub async fn runtime_transpile(
tsc_config::json_merge(&mut compiler_options, &user_options); tsc_config::json_merge(&mut compiler_options, &user_options);
let req_msg = json!({ let req_msg = json!({
"type": msg::CompilerRequestType::RuntimeTranspile, "type": CompilerRequestType::RuntimeTranspile,
"sources": sources, "sources": sources,
"compilerOptions": compiler_options, "compilerOptions": compiler_options,
}) })
@ -1561,6 +1559,34 @@ fn parse_deno_types(comment: &str) -> Option<String> {
None None
} }
// Warning! The values in this enum are duplicated in js/compiler.ts
// Update carefully!
#[repr(i32)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum CompilerRequestType {
Compile = 0,
Bundle = 1,
RuntimeCompile = 2,
RuntimeBundle = 3,
RuntimeTranspile = 4,
}
impl Serialize for CompilerRequestType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let value: i32 = match self {
CompilerRequestType::Compile => 0 as i32,
CompilerRequestType::Bundle => 1 as i32,
CompilerRequestType::RuntimeCompile => 2 as i32,
CompilerRequestType::RuntimeBundle => 3 as i32,
CompilerRequestType::RuntimeTranspile => 4 as i32,
};
Serialize::serialize(&value, serializer)
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -1640,7 +1666,7 @@ mod tests {
let out = SourceFile { let out = SourceFile {
url: specifier.as_url().clone(), url: specifier.as_url().clone(),
filename: PathBuf::from(p.to_str().unwrap().to_string()), filename: PathBuf::from(p.to_str().unwrap().to_string()),
media_type: msg::MediaType::TypeScript, media_type: MediaType::TypeScript,
source_code: include_bytes!("./tests/002_hello.ts").to_vec().into(), source_code: include_bytes!("./tests/002_hello.ts").to_vec().into(),
types_header: None, types_header: None,
}; };
@ -1716,7 +1742,7 @@ mod tests {
let out = SourceFile { let out = SourceFile {
url: specifier.as_url().clone(), url: specifier.as_url().clone(),
filename: PathBuf::from(p.to_str().unwrap().to_string()), filename: PathBuf::from(p.to_str().unwrap().to_string()),
media_type: msg::MediaType::TypeScript, media_type: MediaType::TypeScript,
source_code: include_bytes!("./tests/002_hello.ts").to_vec().into(), source_code: include_bytes!("./tests/002_hello.ts").to_vec().into(),
types_header: None, types_header: None,
}; };