1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-25 15:29:32 -05:00

feat(cli/compile): Support data uri dynamic imports in deno compile (#9936)

This commit is contained in:
Divy Srivastava 2021-06-05 19:54:17 +05:30 committed by GitHub
parent 4b3d55b449
commit e67010b5e2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 71 additions and 8 deletions

View file

@ -191,7 +191,7 @@ pub fn map_content_type(
} }
/// Remove shebangs from the start of source code strings /// Remove shebangs from the start of source code strings
fn strip_shebang(mut value: String) -> String { pub fn strip_shebang(mut value: String) -> String {
if value.starts_with("#!") { if value.starts_with("#!") {
if let Some(mid) = value.find('\n') { if let Some(mid) = value.find('\n') {
let (_, rest) = value.split_at(mid); let (_, rest) = value.split_at(mid);

View file

@ -1,8 +1,12 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::colors; use crate::colors;
use crate::file_fetcher::get_source_from_bytes;
use crate::file_fetcher::strip_shebang;
use crate::version; use crate::version;
use data_url::DataUrl;
use deno_core::error::type_error; use deno_core::error::type_error;
use deno_core::error::uri_error;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::error::Context; use deno_core::error::Context;
use deno_core::futures::FutureExt; use deno_core::futures::FutureExt;
@ -109,6 +113,19 @@ fn read_string_slice(
Ok(string) Ok(string)
} }
fn get_source_from_data_url(
specifier: &ModuleSpecifier,
) -> Result<String, AnyError> {
let data_url = DataUrl::process(specifier.as_str())
.map_err(|e| uri_error(format!("{:?}", e)))?;
let mime = data_url.mime_type();
let charset = mime.get_parameter("charset").map(|v| v.to_string());
let (bytes, _) = data_url
.decode_to_vec()
.map_err(|e| uri_error(format!("{:?}", e)))?;
Ok(strip_shebang(get_source_from_bytes(bytes, charset)?))
}
const SPECIFIER: &str = "file://$deno$/bundle.js"; const SPECIFIER: &str = "file://$deno$/bundle.js";
struct EmbeddedModuleLoader(String); struct EmbeddedModuleLoader(String);
@ -121,12 +138,16 @@ impl ModuleLoader for EmbeddedModuleLoader {
_referrer: &str, _referrer: &str,
_is_main: bool, _is_main: bool,
) -> Result<ModuleSpecifier, AnyError> { ) -> Result<ModuleSpecifier, AnyError> {
if specifier != SPECIFIER { if let Ok(module_specifier) = resolve_url(&specifier) {
return Err(type_error( if get_source_from_data_url(&module_specifier).is_ok()
"Self-contained binaries don't support module loading", || specifier == SPECIFIER
)); {
return Ok(module_specifier);
} }
Ok(resolve_url(specifier)?) }
Err(type_error(
"Self-contained binaries don't support module loading",
))
} }
fn load( fn load(
@ -137,13 +158,19 @@ impl ModuleLoader for EmbeddedModuleLoader {
_is_dynamic: bool, _is_dynamic: bool,
) -> Pin<Box<deno_core::ModuleSourceFuture>> { ) -> Pin<Box<deno_core::ModuleSourceFuture>> {
let module_specifier = module_specifier.clone(); let module_specifier = module_specifier.clone();
let code = self.0.to_string(); let is_data_uri = get_source_from_data_url(&module_specifier).ok();
let code = if let Some(ref source) = is_data_uri {
source.to_string()
} else {
self.0.to_string()
};
async move { async move {
if module_specifier.to_string() != SPECIFIER { if is_data_uri.is_none() && module_specifier.to_string() != SPECIFIER {
return Err(type_error( return Err(type_error(
"Self-contained binaries don't support module loading", "Self-contained binaries don't support module loading",
)); ));
} }
Ok(deno_core::ModuleSource { Ok(deno_core::ModuleSource {
code, code,
module_url_specified: module_specifier.to_string(), module_url_specified: module_specifier.to_string(),

View file

@ -5844,6 +5844,38 @@ console.log("finish");
.contains("Self-contained binaries don't support module loading")); .contains("Self-contained binaries don't support module loading"));
} }
#[test]
fn standalone_load_datauri() {
let dir = TempDir::new().expect("tempdir fail");
let exe = if cfg!(windows) {
dir.path().join("load_datauri.exe")
} else {
dir.path().join("load_datauri")
};
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("./cli/tests/standalone_import_datauri.ts")
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
let output = Command::new(exe)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
assert_eq!(output.stdout, b"Hello Deno!\n");
}
#[test] #[test]
fn compile_with_directory_exists_error() { fn compile_with_directory_exists_error() {
let dir = TempDir::new().expect("tempdir fail"); let dir = TempDir::new().expect("tempdir fail");

View file

@ -0,0 +1,4 @@
const c = await import(
"data:text/javascript;base64,ZXhwb3J0IGRlZmF1bHQgJ0hlbGxvIERlbm8hJw=="
);
console.log(c.default); // Output: "Hello Deno!"