Skip to content

Commit

Permalink
feat: Add --location and globalThis.location
Browse files Browse the repository at this point in the history
  • Loading branch information
nayeemrmn committed Jan 7, 2021
1 parent adc2f08 commit dc1a668
Show file tree
Hide file tree
Showing 34 changed files with 734 additions and 193 deletions.
279 changes: 135 additions & 144 deletions cli/flags.rs

Large diffs are not rendered by default.

26 changes: 19 additions & 7 deletions cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ pub fn create_main_worker(
ts_version: version::TYPESCRIPT.to_string(),
no_color: !colors::use_color(),
get_error_class_fn: Some(&crate::errors::get_error_class_name),
location: program_state.flags.location.clone(),
};

let mut worker = MainWorker::from_options(main_module, permissions, &options);
Expand Down Expand Up @@ -1221,6 +1222,21 @@ fn get_subcommand(
}
}

fn unwrap_or_exit<T>(result: Result<T, AnyError>) -> T {
match result {
Ok(value) => value,
Err(error) => {
let msg = format!(
"{}: {}",
colors::red_bold("error"),
error.to_string().trim()
);
eprintln!("{}", msg);
std::process::exit(1);
}
}
}

pub fn main() {
#[cfg(windows)]
colors::enable_ansi(); // For Windows 10
Expand All @@ -1231,16 +1247,12 @@ pub fn main() {
std::process::exit(1);
}

let flags = flags::flags_from_vec(args);
let flags =
unwrap_or_exit(flags::flags_from_vec(args).map_err(AnyError::from));
if !flags.v8_flags.is_empty() {
init_v8_flags(&*flags.v8_flags);
}
init_logger(flags.log_level);

let subcommand_future = get_subcommand(flags);
let result = tokio_util::run_basic(subcommand_future);
if let Err(err) = result {
eprintln!("{}: {}", colors::red_bold("error"), err.to_string());
std::process::exit(1);
}
unwrap_or_exit(tokio_util::run_basic(get_subcommand(flags)));
}
4 changes: 3 additions & 1 deletion cli/standalone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ async fn run(source_code: String, metadata: Metadata) -> Result<(), AnyError> {
// TODO(nayeemrmn): Unify this Flags -> WorkerOptions mapping with `deno run`.
let options = WorkerOptions {
apply_source_maps: false,
args: flags.argv.clone(),
args: flags.argv,
debug_flag: flags.log_level.map_or(false, |l| l == log::Level::Debug),
user_agent: crate::http_util::get_user_agent(),
unstable: flags.unstable,
Expand All @@ -183,6 +183,7 @@ async fn run(source_code: String, metadata: Metadata) -> Result<(), AnyError> {
ts_version: version::TYPESCRIPT.to_string(),
no_color: !colors::use_color(),
get_error_class_fn: Some(&crate::errors::get_error_class_name),
location: flags.location,
};
let mut worker =
MainWorker::from_options(main_module.clone(), permissions, &options);
Expand Down Expand Up @@ -297,6 +298,7 @@ pub fn compile_to_runtime_flags(
import_map_path: None,
inspect: None,
inspect_brk: None,
location: flags.location,
lock: None,
lock_write: false,
log_level: flags.log_level,
Expand Down
10 changes: 10 additions & 0 deletions cli/tests/070_location.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// TODO(nayeemrmn): Add `Location` and `location` to `dlint`'s globals.
// deno-lint-ignore-file no-undef
console.log(Location);
console.log(Location.prototype);
console.log(location);
try {
location.hostname = "bar";
} catch (error) {
console.log(error);
}
22 changes: 22 additions & 0 deletions cli/tests/070_location.ts.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[WILDCARD][Function: Location]
Location { [Symbol(Symbol.toStringTag)]: "Location" }
Location {
hash: [Getter/Setter],
host: [Getter/Setter],
hostname: [Getter/Setter],
href: [Getter/Setter],
origin: [Getter],
password: [Getter/Setter],
pathname: [Getter/Setter],
port: [Getter/Setter],
protocol: [Getter/Setter],
search: [Getter/Setter],
username: [Getter/Setter],
ancestorOrigins: [Getter],
assign: [Function: assign],
reload: [Function: reload],
replace: [Function: replace],
toString: [Function: toString]
}
NotSupportedError: Cannot set "location.hostname".
[WILDCARD]
5 changes: 5 additions & 0 deletions cli/tests/071_location_unset.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// TODO(nayeemrmn): Add `Location` and `location` to `dlint`'s globals.
// deno-lint-ignore-file no-undef
console.log(Location);
console.log(Location.prototype);
console.log(location);
4 changes: 4 additions & 0 deletions cli/tests/071_location_unset.ts.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[WILDCARD][Function: Location]
Location { [Symbol(Symbol.toStringTag)]: "Location" }
error: Uncaught ReferenceError: Access to "location", run again with --location <href>.
[WILDCARD]
2 changes: 2 additions & 0 deletions cli/tests/072_location_relative_fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const response = await fetch("fetch/hello.txt");
console.log(await response.text());
2 changes: 2 additions & 0 deletions cli/tests/072_location_relative_fetch.ts.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[WILDCARD]Hello, world!

1 change: 1 addition & 0 deletions cli/tests/077_fetch_empty.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
await fetch("");
2 changes: 2 additions & 0 deletions cli/tests/077_fetch_empty.ts.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[WILDCARD]error: Uncaught (in promise) URIError: relative URL without a base
[WILDCARD]
4 changes: 2 additions & 2 deletions cli/tests/complex_permissions_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ const test: { [key: string]: (...args: any[]) => void | Promise<void> } = {
Deno.writeFileSync(file, new Uint8Array(0), { append: true })
);
},
netFetch(hosts: string[]): void {
hosts.forEach((host) => fetch(host));
netFetch(urls: string[]): void {
urls.forEach((url) => fetch(url));
},
netListen(endpoints: string[]): void {
endpoints.forEach((endpoint) => {
Expand Down
1 change: 1 addition & 0 deletions cli/tests/fetch/hello.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello, world!
39 changes: 31 additions & 8 deletions cli/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1246,7 +1246,7 @@ fn bundle_import_map_no_check() {
.current_dir(util::root_path())
.arg("bundle")
.arg("--no-check")
.arg("--importmap")
.arg("--import-map")
.arg(import_map_path)
.arg("--unstable")
.arg(import)
Expand Down Expand Up @@ -1689,7 +1689,7 @@ fn repl_test_pty_bad_input() {

#[test]
#[ignore]
fn run_watch_with_importmap_and_relative_paths() {
fn run_watch_with_import_map_and_relative_paths() {
fn create_relative_tmp_file(
directory: &TempDir,
filename: &'static str,
Expand Down Expand Up @@ -1722,7 +1722,7 @@ fn run_watch_with_importmap_and_relative_paths() {
.arg("run")
.arg("--unstable")
.arg("--watch")
.arg("--importmap")
.arg("--import-map")
.arg(&import_map_path)
.arg(&file_to_watch)
.env("NO_COLOR", "1")
Expand Down Expand Up @@ -2307,6 +2307,8 @@ fn workers() {
.current_dir(util::tests_path())
.arg("test")
.arg("--reload")
.arg("--location")
.arg("http://127.0.0.1:4545/cli/tests/")
.arg("--allow-net")
.arg("--allow-read")
.arg("--unstable")
Expand Down Expand Up @@ -2548,6 +2550,23 @@ itest!(_067_test_no_run_type_error {
exit_code: 1,
});

itest!(_070_location {
args: "run --location https://foo/bar?baz#bat 070_location.ts",
output: "070_location.ts.out",
});

itest!(_071_location_unset {
args: "run 071_location_unset.ts",
output: "071_location_unset.ts.out",
exit_code: 1,
});

itest!(_072_location_relative_fetch {
args: "run --location http://127.0.0.1:4545/cli/tests/ --allow-net 072_location_relative_fetch.ts",
output: "072_location_relative_fetch.ts.out",
http_server: true,
});

itest!(_073_worker_error {
args: "run -A 073_worker_error.ts",
output: "073_worker_error.ts.out",
Expand All @@ -2570,6 +2589,12 @@ itest!(_076_info_json_deps_order {
output: "076_info_json_deps_order.out",
});

itest!(_077_fetch_empty {
args: "run -A 077_fetch_empty.ts",
output: "077_fetch_empty.ts.out",
exit_code: 1,
});

itest!(js_import_detect {
args: "run --quiet --reload js_import_detect.ts",
output: "js_import_detect.ts.out",
Expand Down Expand Up @@ -5177,16 +5202,14 @@ fn web_platform_tests() {
.tempfile()
.unwrap();

let bundle = concat_bundle(
files,
file.path(),
format!("window.location = {{search: \"{}\"}};\n", variant),
);
let bundle = concat_bundle(files, file.path(), "".to_string());
file.write_all(bundle.as_bytes()).unwrap();

let child = util::deno_cmd()
.current_dir(test_file_path.parent().unwrap())
.arg("run")
.arg("--location")
.arg(&format!("http://web-platform-tests/?{}", variant))
.arg("-A")
.arg(file.path())
.arg(deno_core::serde_json::to_string(&expect_fail).unwrap())
Expand Down
4 changes: 4 additions & 0 deletions cli/tests/subdir/worker_location.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
onmessage = function (): void {
postMessage(self.location.href);
close();
};
11 changes: 0 additions & 11 deletions cli/tests/unit/fetch_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,17 +221,6 @@ unitTest({ perms: { net: true } }, async function responseClone(): Promise<
}
});

unitTest({ perms: { net: true } }, async function fetchEmptyInvalid(): Promise<
void
> {
await assertThrowsAsync(
async () => {
await fetch("");
},
URIError,
);
});

unitTest(
{ perms: { net: true } },
async function fetchMultipartFormDataSuccess(): Promise<void> {
Expand Down
8 changes: 5 additions & 3 deletions cli/tests/unit/request_test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert, assertEquals, assertThrows, unitTest } from "./test_util.ts";
import { assert, assertEquals, unitTest } from "./test_util.ts";

unitTest(function fromInit(): void {
const req = new Request("http://foo/", {
Expand Down Expand Up @@ -46,8 +46,10 @@ unitTest(function methodNonString(): void {
});

unitTest(function requestRelativeUrl(): void {
// TODO(nayeemrmn): Base from `--location` when implemented and set.
assertThrows(() => new Request("relative-url"), TypeError, "Invalid URL.");
assertEquals(
new Request("relative-url").url,
"http://js-unit-tests/foo/relative-url",
);
});

unitTest(async function cloneRequestBodyStream(): Promise<void> {
Expand Down
1 change: 1 addition & 0 deletions cli/tests/unit/unit_test_runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ function spawnWorkerRunner(
Deno.execPath(),
"run",
"--unstable", // TODO(ry) be able to test stable vs unstable
"--location=http://js-unit-tests/foo/bar",
"-A",
"cli/tests/unit/unit_test_runner.ts",
"--worker",
Expand Down
38 changes: 38 additions & 0 deletions cli/tests/workers_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -614,3 +614,41 @@ Deno.test("Worker with disabled permissions", async function () {
await promise;
worker.terminate();
});

Deno.test({
name: "worker location",
fn: async function (): Promise<void> {
const promise = deferred();
const workerModuleHref =
new URL("subdir/worker_location.ts", import.meta.url).href;
const w = new Worker(workerModuleHref, { type: "module" });
w.onmessage = (e): void => {
assertEquals(e.data, workerModuleHref);
promise.resolve();
};
w.postMessage("Hello, world!");
await promise;
w.terminate();
},
});

Deno.test({
name: "worker with relative specifier",
fn: async function (): Promise<void> {
// TODO(nayeemrmn): Add `Location` and `location` to `dlint`'s globals.
// deno-lint-ignore no-undef
assertEquals(location.href, "http://127.0.0.1:4545/cli/tests/");
const promise = deferred();
const w = new Worker(
"./subdir/test_worker.ts",
{ type: "module", name: "tsWorker" },
);
w.onmessage = (e): void => {
assertEquals(e.data, "Hello, world!");
promise.resolve();
};
w.postMessage("Hello, world!");
await promise;
w.terminate();
},
});
4 changes: 4 additions & 0 deletions cli/tools/installer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,10 @@ pub fn install(

let mut executable_args = vec!["run".to_string()];
executable_args.extend_from_slice(&flags.to_permission_args());
if let Some(url) = flags.location.as_ref() {
executable_args.push("--location".to_string());
executable_args.push(url.to_string());
}
if let Some(ca_file) = flags.ca_file {
executable_args.push("--cert".to_string());
executable_args.push(ca_file)
Expand Down
Loading

0 comments on commit dc1a668

Please sign in to comment.