hints_text stringlengths 0 100k | created_at stringlengths 20 20 | repo stringclasses 1 value | instance_id stringlengths 18 20 | issue_numbers sequencelengths 1 3 | base_commit stringlengths 40 40 | problem_statement stringlengths 24 195k | version stringclasses 89 values | patch stringlengths 236 1.56M | pull_number int64 338 27.4k | test_patch stringlengths 206 10M | environment_setup_commit stringclasses 90 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
@satyarohith Isn't this expected behavior on command line?
```shell
echo 'hello' | 404
echo "Exit code:" $?
deno eval "console.log('hello')" | 404
echo "Exit code:" $?
# Expected output:
#
# bash: 404: command not found
# Exit code: 127
# bash: 404: command not found
# thread 'main' panicked at 'failed printing to stdout: The pipe is being closed. (os error 232)', library\std\src\io\stdio.rs:940:9
# note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
# Exit code: 127
```
It shouldn't panic. For comparison, the behavior of node:
```
➜ ~ cat script.js
console.log("hello");
➜ ~ node script.js | 404
zsh: command not found: 404
``` | 2021-06-18T16:59:27Z | denoland/deno | denoland__deno-11039 | [
"10764"
] | 0cbaeca026a7d79a57c859e5e395f0d998fab5d1 | cli: panics when the output is piped to a non-existent executable
Steps to reproduce:
```
➜ cat log.ts
console.log("hello");
➜ deno run log.ts | 404
zsh: command not found: 404
thread 'main' panicked at 'failed printing to stdout: Broken pipe (os error 32)', library/std/src/io/stdio.rs:940:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
fatal runtime error: failed to initiate panic, error 5
[1] 52032 abort deno run log.ts |
52033 exit 127 404
```
| 1.11 | diff --git a/core/ops_builtin.rs b/core/ops_builtin.rs
--- a/core/ops_builtin.rs
+++ b/core/ops_builtin.rs
@@ -61,10 +61,10 @@ pub fn op_print(
is_err: bool,
) -> Result<(), AnyError> {
if is_err {
- eprint!("{}", msg);
+ stderr().write_all(msg.as_bytes())?;
stderr().flush().unwrap();
} else {
- print!("{}", msg);
+ stdout().write_all(msg.as_bytes())?;
stdout().flush().unwrap();
}
Ok(())
| 11,039 | diff --git a/cli/tests/integration_tests.rs b/cli/tests/integration_tests.rs
--- a/cli/tests/integration_tests.rs
+++ b/cli/tests/integration_tests.rs
@@ -3158,6 +3158,29 @@ console.log("finish");
util::test_pty(args, output, input);
}
+ #[test]
+ fn broken_stdout() {
+ let (reader, writer) = os_pipe::pipe().unwrap();
+ // drop the reader to create a broken pipe
+ drop(reader);
+
+ let output = util::deno_cmd()
+ .current_dir(util::root_path())
+ .arg("eval")
+ .arg("console.log(3.14)")
+ .stdout(writer)
+ .stderr(std::process::Stdio::piped())
+ .spawn()
+ .unwrap()
+ .wait_with_output()
+ .unwrap();
+
+ assert!(!output.status.success());
+ let stderr = std::str::from_utf8(output.stderr.as_ref()).unwrap().trim();
+ assert!(stderr.contains("Uncaught BrokenPipe"));
+ assert!(!stderr.contains("panic"));
+ }
+
itest!(_091_use_define_for_class_fields {
args: "run 091_use_define_for_class_fields.ts",
output: "091_use_define_for_class_fields.ts.out",
| 67c9937e6658c2be9b54cd95132a1055756e433b |
2021-06-17T17:34:01Z | denoland/deno | denoland__deno-11023 | [
"11019"
] | 2a66d5de01b584b7138084eb427c9ac09c254986 | `deno lsp` should exit when the editor process no longer exists
When launching `deno lsp` it should check for the existence of the editor process every X seconds. If the editor process no longer exists, then it should exit.
This could be achieved reliably via a CLI flag:
```
deno lsp --parent-pid <pid>
```
The reason for a flag is because getting the parent pid without the flag is is not always reliable and using a CLI flag requires less platform specific code.
Refs:
https://github.com/denoland/vscode_deno/issues/374
| 1.11 | diff --git a/cli/flags.rs b/cli/flags.rs
--- a/cli/flags.rs
+++ b/cli/flags.rs
@@ -84,7 +84,9 @@ pub enum DenoSubcommand {
root: Option<PathBuf>,
force: bool,
},
- Lsp,
+ Lsp {
+ parent_pid: Option<u32>,
+ },
Lint {
files: Vec<PathBuf>,
ignore: Vec<PathBuf>,
diff --git a/cli/flags.rs b/cli/flags.rs
--- a/cli/flags.rs
+++ b/cli/flags.rs
@@ -876,6 +878,16 @@ go-to-definition support and automatic code formatting.
How to connect various editors and IDEs to 'deno lsp':
https://deno.land/manual/getting_started/setup_your_environment#editors-and-ides")
+ .arg(
+ Arg::with_name("parent-pid")
+ .long("parent-pid")
+ .help("The parent process id to periodically check for the existence of or exit")
+ .takes_value(true)
+ .validator(|val: String| match val.parse::<usize>() {
+ Ok(_) => Ok(()),
+ Err(_) => Err("parent-pid should be a number".to_string()),
+ }),
+ )
}
fn lint_subcommand<'a, 'b>() -> App<'a, 'b> {
diff --git a/cli/flags.rs b/cli/flags.rs
--- a/cli/flags.rs
+++ b/cli/flags.rs
@@ -1621,8 +1633,11 @@ fn install_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
};
}
-fn lsp_parse(flags: &mut Flags, _matches: &clap::ArgMatches) {
- flags.subcommand = DenoSubcommand::Lsp;
+fn lsp_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
+ let parent_pid = matches
+ .value_of("parent-pid")
+ .map(|val| val.parse().unwrap());
+ flags.subcommand = DenoSubcommand::Lsp { parent_pid };
}
fn lint_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
diff --git a/cli/lsp/mod.rs b/cli/lsp/mod.rs
--- a/cli/lsp/mod.rs
+++ b/cli/lsp/mod.rs
@@ -13,6 +13,7 @@ mod diagnostics;
mod documents;
pub(crate) mod language_server;
mod lsp_custom;
+mod parent_process_checker;
mod path_to_regex;
mod performance;
mod registries;
diff --git a/cli/lsp/mod.rs b/cli/lsp/mod.rs
--- a/cli/lsp/mod.rs
+++ b/cli/lsp/mod.rs
@@ -22,10 +23,14 @@ mod text;
mod tsc;
mod urls;
-pub async fn start() -> Result<(), AnyError> {
+pub async fn start(parent_pid: Option<u32>) -> Result<(), AnyError> {
let stdin = tokio::io::stdin();
let stdout = tokio::io::stdout();
+ if let Some(parent_pid) = parent_pid {
+ parent_process_checker::start(parent_pid);
+ }
+
let (service, messages) =
LspService::new(language_server::LanguageServer::new);
Server::new(stdin, stdout)
diff --git a/cli/main.rs b/cli/main.rs
--- a/cli/main.rs
+++ b/cli/main.rs
@@ -470,8 +470,8 @@ async fn install_command(
tools::installer::install(flags, &module_url, args, name, root, force)
}
-async fn lsp_command() -> Result<(), AnyError> {
- lsp::start().await
+async fn lsp_command(parent_pid: Option<u32>) -> Result<(), AnyError> {
+ lsp::start(parent_pid).await
}
async fn lint_command(
diff --git a/cli/main.rs b/cli/main.rs
--- a/cli/main.rs
+++ b/cli/main.rs
@@ -1264,7 +1264,7 @@ fn get_subcommand(
} => {
install_command(flags, module_url, args, name, root, force).boxed_local()
}
- DenoSubcommand::Lsp => lsp_command().boxed_local(),
+ DenoSubcommand::Lsp { parent_pid } => lsp_command(parent_pid).boxed_local(),
DenoSubcommand::Lint {
files,
rules,
| 11,023 | diff --git a/cli/flags.rs b/cli/flags.rs
--- a/cli/flags.rs
+++ b/cli/flags.rs
@@ -2308,10 +2323,24 @@ mod tests {
assert_eq!(
r.unwrap(),
Flags {
- subcommand: DenoSubcommand::Lsp,
+ subcommand: DenoSubcommand::Lsp { parent_pid: None },
..Flags::default()
}
);
+
+ let r = flags_from_vec(svec!["deno", "lsp", "--parent-pid", "5"]);
+ assert_eq!(
+ r.unwrap(),
+ Flags {
+ subcommand: DenoSubcommand::Lsp {
+ parent_pid: Some(5),
+ },
+ ..Flags::default()
+ }
+ );
+
+ let r = flags_from_vec(svec!["deno", "lsp", "--parent-pid", "invalid-arg"]);
+ assert!(r.is_err());
}
#[test]
diff --git /dev/null b/cli/lsp/parent_process_checker.rs
new file mode 100644
--- /dev/null
+++ b/cli/lsp/parent_process_checker.rs
@@ -0,0 +1,70 @@
+// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
+
+use tokio::time::sleep;
+use tokio::time::Duration;
+
+/// Starts a task that will check for the existence of the
+/// provided process id. Once that process no longer exists
+/// it will terminate the current process.
+pub fn start(parent_process_id: u32) {
+ tokio::task::spawn(async move {
+ loop {
+ sleep(Duration::from_secs(30)).await;
+
+ if !is_process_active(parent_process_id) {
+ eprintln!("Parent process lost. Exiting.");
+ std::process::exit(1);
+ }
+ }
+ });
+}
+
+#[cfg(unix)]
+fn is_process_active(process_id: u32) -> bool {
+ unsafe {
+ // signal of 0 checks for the existence of the process id
+ libc::kill(process_id as i32, 0) == 0
+ }
+}
+
+#[cfg(windows)]
+fn is_process_active(process_id: u32) -> bool {
+ use winapi::shared::minwindef::DWORD;
+ use winapi::shared::minwindef::FALSE;
+ use winapi::shared::ntdef::NULL;
+ use winapi::shared::winerror::WAIT_TIMEOUT;
+ use winapi::um::handleapi::CloseHandle;
+ use winapi::um::processthreadsapi::OpenProcess;
+ use winapi::um::synchapi::WaitForSingleObject;
+ use winapi::um::winnt::SYNCHRONIZE;
+
+ unsafe {
+ let process = OpenProcess(SYNCHRONIZE, FALSE, process_id as DWORD);
+ let result = if process == NULL {
+ false
+ } else {
+ WaitForSingleObject(process, 0) == WAIT_TIMEOUT
+ };
+ CloseHandle(process);
+ result
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::is_process_active;
+ use std::process::Command;
+ use test_util::deno_exe_path;
+
+ #[test]
+ fn process_active() {
+ // launch a long running process
+ let mut child = Command::new(deno_exe_path()).arg("lsp").spawn().unwrap();
+
+ let pid = child.id();
+ assert_eq!(is_process_active(pid), true);
+ child.kill().unwrap();
+ child.wait().unwrap();
+ assert_eq!(is_process_active(pid), false);
+ }
+}
| 67c9937e6658c2be9b54cd95132a1055756e433b | |
2021-06-17T14:55:19Z | denoland/deno | denoland__deno-11020 | [
"11017"
] | 9105892ec8b454571c56883eace557eee25b3301 | Users can set "Host" header for `fetch`
The `host` header should not be able to be set by the user. It should always be populated by `reqwest` / `hyper`.
| 1.11 | diff --git a/extensions/fetch/lib.rs b/extensions/fetch/lib.rs
--- a/extensions/fetch/lib.rs
+++ b/extensions/fetch/lib.rs
@@ -29,6 +29,7 @@ use deno_web::BlobUrlStore;
use reqwest::header::HeaderMap;
use reqwest::header::HeaderName;
use reqwest::header::HeaderValue;
+use reqwest::header::HOST;
use reqwest::header::USER_AGENT;
use reqwest::redirect::Policy;
use reqwest::Body;
diff --git a/extensions/fetch/lib.rs b/extensions/fetch/lib.rs
--- a/extensions/fetch/lib.rs
+++ b/extensions/fetch/lib.rs
@@ -193,7 +194,9 @@ where
for (key, value) in args.headers {
let name = HeaderName::from_bytes(key.as_bytes()).unwrap();
let v = HeaderValue::from_str(&value).unwrap();
- request = request.header(name, v);
+ if name != HOST {
+ request = request.header(name, v);
+ }
}
let cancel_handle = CancelHandle::new_rc();
| 11,020 | diff --git a/cli/tests/unit/fetch_test.ts b/cli/tests/unit/fetch_test.ts
--- a/cli/tests/unit/fetch_test.ts
+++ b/cli/tests/unit/fetch_test.ts
@@ -1149,3 +1149,49 @@ unitTest({}, function fetchWritableRespProps(): void {
assertEquals(original.status, new_.status);
assertEquals(new_.headers.get("x-deno"), "foo");
});
+
+function returnHostHeaderServer(addr: string): Deno.Listener {
+ const [hostname, port] = addr.split(":");
+ const listener = Deno.listen({
+ hostname,
+ port: Number(port),
+ }) as Deno.Listener;
+
+ listener.accept().then(async (conn: Deno.Conn) => {
+ const httpConn = Deno.serveHttp(conn);
+
+ await httpConn.nextRequest()
+ .then(async (requestEvent: Deno.RequestEvent | null) => {
+ const hostHeader = requestEvent?.request.headers.get("Host");
+ const headersToReturn = hostHeader ? { "Host": hostHeader } : undefined;
+
+ await requestEvent?.respondWith(
+ new Response("", {
+ status: 200,
+ headers: headersToReturn,
+ }),
+ );
+ });
+
+ httpConn.close();
+ });
+
+ return listener;
+}
+
+unitTest(
+ { perms: { net: true } },
+ async function fetchFilterOutCustomHostHeader(): Promise<
+ void
+ > {
+ const addr = "127.0.0.1:4502";
+ const listener = returnHostHeaderServer(addr);
+ const response = await fetch(`http://${addr}/`, {
+ headers: { "Host": "example.com" },
+ });
+ await response.text();
+ listener.close();
+
+ assertEquals(response.headers.get("Host"), addr);
+ },
+);
| 67c9937e6658c2be9b54cd95132a1055756e433b | |
2021-06-17T07:44:30Z | denoland/deno | denoland__deno-11015 | [
"11014"
] | 419fe2e6b4b77fbc97dee67eaa32a420accb8cfc | Redundant re-checking of dynamic imports

You can cause the module to be type-checked again by changing the file between repeated dynamic imports, but the module is already loaded so this should not happen.
_Fully_ short-circuiting a repeated dynamic import is quite hard, but we can easily skip the `load_prepare()` step under certain conditions. Fix coming.
This is unrelated to #9802.
| 1.11 | diff --git a/cli/main.rs b/cli/main.rs
--- a/cli/main.rs
+++ b/cli/main.rs
@@ -598,6 +598,7 @@ async fn create_module_graph_and_maybe_check(
lib,
maybe_config_file: program_state.maybe_config_file.clone(),
reload: program_state.flags.reload,
+ ..Default::default()
})?;
debug!("{}", result_info.stats);
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -624,6 +624,10 @@ pub struct CheckOptions {
/// Ignore any previously emits and ensure that all files are emitted from
/// source.
pub reload: bool,
+ /// A set of module specifiers to be excluded from the effect of
+ /// `CheckOptions::reload` if it is `true`. Perhaps because they have already
+ /// reloaded once in this process.
+ pub reload_exclusions: HashSet<ModuleSpecifier>,
}
#[derive(Debug, Eq, PartialEq)]
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -673,6 +677,10 @@ pub struct TranspileOptions {
/// Ignore any previously emits and ensure that all files are emitted from
/// source.
pub reload: bool,
+ /// A set of module specifiers to be excluded from the effect of
+ /// `CheckOptions::reload` if it is `true`. Perhaps because they have already
+ /// reloaded once in this process.
+ pub reload_exclusions: HashSet<ModuleSpecifier>,
}
#[derive(Debug, Clone)]
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -851,15 +859,14 @@ impl Graph {
let maybe_ignored_options = config
.merge_tsconfig_from_config_file(options.maybe_config_file.as_ref())?;
+ let needs_reload = options.reload
+ && !self
+ .roots
+ .iter()
+ .all(|u| options.reload_exclusions.contains(u));
// Short circuit if none of the modules require an emit, or all of the
- // modules that require an emit have a valid emit. There is also an edge
- // case where there are multiple imports of a dynamic module during a
- // single invocation, if that is the case, even if there is a reload, we
- // will simply look at if the emit is invalid, to avoid two checks for the
- // same programme.
- if !self.needs_emit(&config)
- || (self.is_emit_valid(&config)
- && (!options.reload || self.roots_dynamic))
+ // modules that require an emit have a valid emit.
+ if !self.needs_emit(&config) || self.is_emit_valid(&config) && !needs_reload
{
debug!("graph does not need to be checked or emitted.");
return Ok(ResultInfo {
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -1673,7 +1680,7 @@ impl Graph {
let check_js = ts_config.get_check_js();
let emit_options: ast::EmitOptions = ts_config.into();
let mut emit_count = 0_u32;
- for (_, module_slot) in self.modules.iter_mut() {
+ for (specifier, module_slot) in self.modules.iter_mut() {
if let ModuleSlot::Module(module) = module_slot {
// TODO(kitsonk) a lot of this logic should be refactored into `Module` as
// we start to support other methods on the graph. Especially managing
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -1692,8 +1699,11 @@ impl Graph {
{
continue;
}
+
+ let needs_reload =
+ options.reload && !options.reload_exclusions.contains(specifier);
// skip modules that already have a valid emit
- if !options.reload && module.is_emit_valid(&config) {
+ if module.is_emit_valid(&config) && !needs_reload {
continue;
}
let parsed_module = module.parse()?;
diff --git a/cli/program_state.rs b/cli/program_state.rs
--- a/cli/program_state.rs
+++ b/cli/program_state.rs
@@ -31,6 +31,7 @@ use deno_core::ModuleSpecifier;
use log::debug;
use log::warn;
use std::collections::HashMap;
+use std::collections::HashSet;
use std::env;
use std::fs::read;
use std::sync::Arc;
diff --git a/cli/program_state.rs b/cli/program_state.rs
--- a/cli/program_state.rs
+++ b/cli/program_state.rs
@@ -177,12 +178,17 @@ impl ProgramState {
let mut graph = builder.get_graph();
let debug = self.flags.log_level == Some(log::Level::Debug);
let maybe_config_file = self.maybe_config_file.clone();
+ let reload_exclusions = {
+ let modules = self.modules.lock().unwrap();
+ modules.keys().cloned().collect::<HashSet<_>>()
+ };
let result_modules = if self.flags.no_check {
let result_info = graph.transpile(TranspileOptions {
debug,
maybe_config_file,
reload: self.flags.reload,
+ reload_exclusions,
})?;
debug!("{}", result_info.stats);
if let Some(ignored_options) = result_info.maybe_ignored_options {
diff --git a/cli/program_state.rs b/cli/program_state.rs
--- a/cli/program_state.rs
+++ b/cli/program_state.rs
@@ -196,6 +202,7 @@ impl ProgramState {
lib,
maybe_config_file,
reload: self.flags.reload,
+ reload_exclusions,
})?;
debug!("{}", result_info.stats);
diff --git a/cli/program_state.rs b/cli/program_state.rs
--- a/cli/program_state.rs
+++ b/cli/program_state.rs
@@ -244,12 +251,17 @@ impl ProgramState {
let mut graph = builder.get_graph();
let debug = self.flags.log_level == Some(log::Level::Debug);
let maybe_config_file = self.maybe_config_file.clone();
+ let reload_exclusions = {
+ let modules = self.modules.lock().unwrap();
+ modules.keys().cloned().collect::<HashSet<_>>()
+ };
let result_modules = if self.flags.no_check {
let result_info = graph.transpile(TranspileOptions {
debug,
maybe_config_file,
reload: self.flags.reload,
+ reload_exclusions,
})?;
debug!("{}", result_info.stats);
if let Some(ignored_options) = result_info.maybe_ignored_options {
diff --git a/cli/program_state.rs b/cli/program_state.rs
--- a/cli/program_state.rs
+++ b/cli/program_state.rs
@@ -263,6 +275,7 @@ impl ProgramState {
lib,
maybe_config_file,
reload: self.flags.reload,
+ reload_exclusions,
})?;
debug!("{}", result_info.stats);
diff --git a/core/modules.rs b/core/modules.rs
--- a/core/modules.rs
+++ b/core/modules.rs
@@ -180,16 +180,21 @@ impl ModuleLoader for FsModuleLoader {
}
}
-#[derive(Debug, Eq, PartialEq)]
-enum Kind {
- Main,
- DynamicImport,
+/// Describes the entrypoint of a recursive module load.
+#[derive(Debug)]
+enum LoadInit {
+ /// Main module specifier.
+ Main(String),
+ /// Main module specifier with synthetic code for that module which bypasses
+ /// the loader.
+ MainWithCode(String, String),
+ /// Dynamic import specifier with referrer.
+ DynamicImport(String, String),
}
#[derive(Debug, Eq, PartialEq)]
pub enum LoadState {
- ResolveMain(String, Option<String>),
- ResolveImport(String, String),
+ Init,
LoadingRoot,
LoadingImports,
Done,
diff --git a/core/modules.rs b/core/modules.rs
--- a/core/modules.rs
+++ b/core/modules.rs
@@ -198,7 +203,7 @@ pub enum LoadState {
/// This future is used to implement parallel async module loading.
pub struct RecursiveModuleLoad {
op_state: Rc<RefCell<OpState>>,
- kind: Kind,
+ init: LoadInit,
// TODO(bartlomieju): in future this value should
// be randomized
pub id: ModuleLoadId,
diff --git a/core/modules.rs b/core/modules.rs
--- a/core/modules.rs
+++ b/core/modules.rs
@@ -217,9 +222,12 @@ impl RecursiveModuleLoad {
code: Option<String>,
loader: Rc<dyn ModuleLoader>,
) -> Self {
- let kind = Kind::Main;
- let state = LoadState::ResolveMain(specifier.to_owned(), code);
- Self::new(op_state, kind, state, loader)
+ let init = if let Some(code) = code {
+ LoadInit::MainWithCode(specifier.to_string(), code)
+ } else {
+ LoadInit::Main(specifier.to_string())
+ };
+ Self::new(op_state, init, loader)
}
pub fn dynamic_import(
diff --git a/core/modules.rs b/core/modules.rs
--- a/core/modules.rs
+++ b/core/modules.rs
@@ -228,63 +236,54 @@ impl RecursiveModuleLoad {
referrer: &str,
loader: Rc<dyn ModuleLoader>,
) -> Self {
- let kind = Kind::DynamicImport;
- let state =
- LoadState::ResolveImport(specifier.to_owned(), referrer.to_owned());
- Self::new(op_state, kind, state, loader)
+ let init =
+ LoadInit::DynamicImport(specifier.to_string(), referrer.to_string());
+ Self::new(op_state, init, loader)
}
pub fn is_dynamic_import(&self) -> bool {
- self.kind != Kind::Main
+ matches!(self.init, LoadInit::DynamicImport(..))
}
fn new(
op_state: Rc<RefCell<OpState>>,
- kind: Kind,
- state: LoadState,
+ init: LoadInit,
loader: Rc<dyn ModuleLoader>,
) -> Self {
Self {
id: NEXT_LOAD_ID.fetch_add(1, Ordering::SeqCst),
root_module_id: None,
op_state,
- kind,
- state,
+ init,
+ state: LoadState::Init,
loader,
pending: FuturesUnordered::new(),
is_pending: HashSet::new(),
}
}
- pub async fn prepare(self) -> (ModuleLoadId, Result<Self, AnyError>) {
- let (module_specifier, maybe_referrer) = match self.state {
- LoadState::ResolveMain(ref specifier, _) => {
+ pub async fn prepare(&self) -> Result<(), AnyError> {
+ let (module_specifier, maybe_referrer) = match self.init {
+ LoadInit::Main(ref specifier)
+ | LoadInit::MainWithCode(ref specifier, _) => {
let spec =
- match self
+ self
.loader
- .resolve(self.op_state.clone(), specifier, ".", true)
- {
- Ok(spec) => spec,
- Err(e) => return (self.id, Err(e)),
- };
+ .resolve(self.op_state.clone(), specifier, ".", true)?;
(spec, None)
}
- LoadState::ResolveImport(ref specifier, ref referrer) => {
- let spec = match self.loader.resolve(
+ LoadInit::DynamicImport(ref specifier, ref referrer) => {
+ let spec = self.loader.resolve(
self.op_state.clone(),
specifier,
referrer,
false,
- ) {
- Ok(spec) => spec,
- Err(e) => return (self.id, Err(e)),
- };
+ )?;
(spec, Some(referrer.to_string()))
}
- _ => unreachable!(),
};
- let prepare_result = self
+ self
.loader
.prepare_load(
self.op_state.clone(),
diff --git a/core/modules.rs b/core/modules.rs
--- a/core/modules.rs
+++ b/core/modules.rs
@@ -293,52 +292,7 @@ impl RecursiveModuleLoad {
maybe_referrer,
self.is_dynamic_import(),
)
- .await;
-
- match prepare_result {
- Ok(()) => (self.id, Ok(self)),
- Err(e) => (self.id, Err(e)),
- }
- }
-
- fn add_root(&mut self) -> Result<(), AnyError> {
- let module_specifier = match self.state {
- LoadState::ResolveMain(ref specifier, _) => {
- self
- .loader
- .resolve(self.op_state.clone(), specifier, ".", true)?
- }
- LoadState::ResolveImport(ref specifier, ref referrer) => self
- .loader
- .resolve(self.op_state.clone(), specifier, referrer, false)?,
-
- _ => unreachable!(),
- };
-
- let load_fut = match &self.state {
- LoadState::ResolveMain(_, Some(code)) => {
- futures::future::ok(ModuleSource {
- code: code.to_owned(),
- module_url_specified: module_specifier.to_string(),
- module_url_found: module_specifier.to_string(),
- })
- .boxed()
- }
- _ => self
- .loader
- .load(
- self.op_state.clone(),
- &module_specifier,
- None,
- self.is_dynamic_import(),
- )
- .boxed_local(),
- };
-
- self.pending.push(load_fut);
-
- self.state = LoadState::LoadingRoot;
- Ok(())
+ .await
}
pub fn is_currently_loading_main_module(&self) -> bool {
diff --git a/core/modules.rs b/core/modules.rs
--- a/core/modules.rs
+++ b/core/modules.rs
@@ -390,10 +344,38 @@ impl Stream for RecursiveModuleLoad {
) -> Poll<Option<Self::Item>> {
let inner = self.get_mut();
match inner.state {
- LoadState::ResolveMain(..) | LoadState::ResolveImport(..) => {
- if let Err(e) = inner.add_root() {
- return Poll::Ready(Some(Err(e)));
- }
+ LoadState::Init => {
+ let resolve_result = match inner.init {
+ LoadInit::Main(ref specifier)
+ | LoadInit::MainWithCode(ref specifier, _) => {
+ inner
+ .loader
+ .resolve(inner.op_state.clone(), specifier, ".", true)
+ }
+ LoadInit::DynamicImport(ref specifier, ref referrer) => inner
+ .loader
+ .resolve(inner.op_state.clone(), specifier, referrer, false),
+ };
+ let module_specifier = match resolve_result {
+ Ok(url) => url,
+ Err(error) => return Poll::Ready(Some(Err(error))),
+ };
+ let load_fut = match inner.init {
+ LoadInit::MainWithCode(_, ref code) => {
+ futures::future::ok(ModuleSource {
+ code: code.clone(),
+ module_url_specified: module_specifier.to_string(),
+ module_url_found: module_specifier.to_string(),
+ })
+ .boxed()
+ }
+ LoadInit::Main(..) | LoadInit::DynamicImport(..) => inner
+ .loader
+ .load(inner.op_state.clone(), &module_specifier, None, false)
+ .boxed_local(),
+ };
+ inner.pending.push(load_fut);
+ inner.state = LoadState::LoadingRoot;
inner.try_poll_next_unpin(cx)
}
LoadState::LoadingRoot | LoadState::LoadingImports => {
diff --git a/core/modules.rs b/core/modules.rs
--- a/core/modules.rs
+++ b/core/modules.rs
@@ -648,17 +630,19 @@ impl ModuleMap {
self.info.get(id)
}
- pub fn load_main(
+ pub async fn load_main(
&self,
specifier: &str,
code: Option<String>,
- ) -> RecursiveModuleLoad {
- RecursiveModuleLoad::main(
+ ) -> Result<RecursiveModuleLoad, AnyError> {
+ let load = RecursiveModuleLoad::main(
self.op_state.clone(),
specifier,
code,
self.loader.clone(),
- )
+ );
+ load.prepare().await?;
+ Ok(load)
}
// Initiate loading of a module graph imported using `import()`.
diff --git a/core/modules.rs b/core/modules.rs
--- a/core/modules.rs
+++ b/core/modules.rs
@@ -675,7 +659,21 @@ impl ModuleMap {
self.loader.clone(),
);
self.dynamic_import_map.insert(load.id, resolver_handle);
- let fut = load.prepare().boxed_local();
+ let resolve_result =
+ load
+ .loader
+ .resolve(load.op_state.clone(), specifier, referrer, false);
+ let fut = match resolve_result {
+ Ok(module_specifier) => {
+ if self.is_registered(&module_specifier) {
+ async move { (load.id, Ok(load)) }.boxed_local()
+ } else {
+ async move { (load.id, load.prepare().await.map(|()| load)) }
+ .boxed_local()
+ }
+ }
+ Err(error) => async move { (load.id, Err(error)) }.boxed_local(),
+ };
self.preparing_dynamic_imports.push(fut);
}
diff --git a/core/runtime.rs b/core/runtime.rs
--- a/core/runtime.rs
+++ b/core/runtime.rs
@@ -1253,11 +1253,10 @@ impl JsRuntime {
) -> Result<ModuleId, AnyError> {
let module_map_rc = Self::module_map(self.v8_isolate());
- let load = module_map_rc.borrow().load_main(specifier.as_str(), code);
-
- let (_load_id, prepare_result) = load.prepare().await;
-
- let mut load = prepare_result?;
+ let mut load = module_map_rc
+ .borrow()
+ .load_main(specifier.as_str(), code)
+ .await?;
while let Some(info_result) = load.next().await {
let info = info_result?;
diff --git a/core/runtime.rs b/core/runtime.rs
--- a/core/runtime.rs
+++ b/core/runtime.rs
@@ -1268,7 +1267,8 @@ impl JsRuntime {
}
let root_id = load.expect_finished();
- self.instantiate_module(root_id).map(|_| root_id)
+ self.instantiate_module(root_id)?;
+ Ok(root_id)
}
fn poll_pending_ops(
| 11,015 | diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -2255,6 +2265,7 @@ pub mod tests {
lib: TypeLib::DenoWindow,
maybe_config_file: None,
reload: false,
+ ..Default::default()
})
.expect("should have checked");
assert!(result_info.maybe_ignored_options.is_none());
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -2277,6 +2288,7 @@ pub mod tests {
lib: TypeLib::DenoWindow,
maybe_config_file: None,
reload: false,
+ ..Default::default()
})
.expect("should have checked");
assert!(result_info.diagnostics.is_empty());
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -2294,6 +2306,7 @@ pub mod tests {
lib: TypeLib::DenoWindow,
maybe_config_file: None,
reload: false,
+ ..Default::default()
})
.expect("should have checked");
assert!(result_info.maybe_ignored_options.is_none());
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -2318,6 +2331,7 @@ pub mod tests {
lib: TypeLib::DenoWindow,
maybe_config_file: None,
reload: false,
+ ..Default::default()
})
.expect("should have checked");
assert!(result_info.maybe_ignored_options.is_none());
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -2340,6 +2354,7 @@ pub mod tests {
lib: TypeLib::DenoWindow,
maybe_config_file: None,
reload: false,
+ ..Default::default()
})
.expect("should have checked");
assert!(result_info.maybe_ignored_options.is_none());
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -2361,6 +2376,7 @@ pub mod tests {
lib: TypeLib::DenoWindow,
maybe_config_file: None,
reload: false,
+ ..Default::default()
})
.expect("should have checked");
assert!(result_info.diagnostics.is_empty());
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -2380,6 +2396,7 @@ pub mod tests {
lib: TypeLib::DenoWindow,
maybe_config_file: Some(config_file),
reload: true,
+ ..Default::default()
})
.expect("should have checked");
assert!(result_info.maybe_ignored_options.is_none());
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -2401,6 +2418,7 @@ pub mod tests {
lib: TypeLib::DenoWindow,
maybe_config_file: Some(config_file),
reload: true,
+ ..Default::default()
})
.expect("should have checked");
assert!(result_info.maybe_ignored_options.is_none());
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -2628,6 +2646,7 @@ pub mod tests {
debug: false,
maybe_config_file: Some(config_file),
reload: false,
+ ..Default::default()
})
.unwrap();
assert_eq!(
diff --git a/cli/tests/single_compile_with_reload.ts b/cli/tests/single_compile_with_reload.ts
--- a/cli/tests/single_compile_with_reload.ts
+++ b/cli/tests/single_compile_with_reload.ts
@@ -2,3 +2,17 @@ await import("./single_compile_with_reload_dyn.ts");
console.log("1");
await import("./single_compile_with_reload_dyn.ts");
console.log("2");
+await new Promise((r) =>
+ new Worker(
+ new URL("single_compile_with_reload_worker.ts", import.meta.url).href,
+ { type: "module" },
+ ).onmessage = r
+);
+console.log("3");
+await new Promise((r) =>
+ new Worker(
+ new URL("single_compile_with_reload_worker.ts", import.meta.url).href,
+ { type: "module" },
+ ).onmessage = r
+);
+console.log("4");
diff --git a/cli/tests/single_compile_with_reload.ts.out b/cli/tests/single_compile_with_reload.ts.out
--- a/cli/tests/single_compile_with_reload.ts.out
+++ b/cli/tests/single_compile_with_reload.ts.out
@@ -2,3 +2,8 @@ Check [WILDCARD]single_compile_with_reload.ts
Hello
1
2
+Check [WILDCARD]single_compile_with_reload_worker.ts
+Hello from worker
+3
+Hello from worker
+4
diff --git /dev/null b/cli/tests/single_compile_with_reload_worker.ts
new file mode 100644
--- /dev/null
+++ b/cli/tests/single_compile_with_reload_worker.ts
@@ -0,0 +1,3 @@
+console.log("Hello from worker");
+postMessage(null);
+close();
diff --git a/core/modules.rs b/core/modules.rs
--- a/core/modules.rs
+++ b/core/modules.rs
@@ -1128,13 +1126,12 @@ mod tests {
)
.unwrap();
- assert_eq!(count.load(Ordering::Relaxed), 0);
// We should get an error here.
let result = runtime.poll_event_loop(cx, false);
if let Poll::Ready(Ok(_)) = result {
unreachable!();
}
- assert_eq!(count.load(Ordering::Relaxed), 2);
+ assert_eq!(count.load(Ordering::Relaxed), 3);
})
}
diff --git a/core/modules.rs b/core/modules.rs
--- a/core/modules.rs
+++ b/core/modules.rs
@@ -1154,7 +1151,7 @@ mod tests {
_is_main: bool,
) -> Result<ModuleSpecifier, AnyError> {
let c = self.resolve_count.fetch_add(1, Ordering::Relaxed);
- assert!(c < 4);
+ assert!(c < 5);
assert_eq!(specifier, "./b.js");
assert_eq!(referrer, "file:///dyn_import3.js");
let s = crate::resolve_import(specifier, referrer).unwrap();
diff --git a/core/modules.rs b/core/modules.rs
--- a/core/modules.rs
+++ b/core/modules.rs
@@ -1231,13 +1228,13 @@ mod tests {
runtime.poll_event_loop(cx, false),
Poll::Ready(Ok(_))
));
- assert_eq!(resolve_count.load(Ordering::Relaxed), 4);
+ assert_eq!(resolve_count.load(Ordering::Relaxed), 5);
assert_eq!(load_count.load(Ordering::Relaxed), 2);
assert!(matches!(
runtime.poll_event_loop(cx, false),
Poll::Ready(Ok(_))
));
- assert_eq!(resolve_count.load(Ordering::Relaxed), 4);
+ assert_eq!(resolve_count.load(Ordering::Relaxed), 5);
assert_eq!(load_count.load(Ordering::Relaxed), 2);
})
}
| 67c9937e6658c2be9b54cd95132a1055756e433b | |
Input file(s) can be found here: https://github.com/mustakimur/crash_report/tree/main/deno/10927 | 2021-06-16T12:39:13Z | denoland/deno | denoland__deno-11007 | [
"10927"
] | 4f1b1903cfadeeba24e1b0448879fe12682effb9 | 'attempt to multiply with overflow' in swc_ecma_parser crate
Input that causes the overflow:
```
\u{cccccccccsccccccQcXt[uc(~).const[uctor().const[uctor())tbr())
```
The error reported:
```
thread 'main' panicked at 'attempt to multiply with overflow', /home/diane/.cargo/registry/src/github.com-1ecc6299db9ec823/swc_ecma_parser-0.57.3/src/lexer/number.rs:277:29
```
Backtrace:
```
thread 'main' panicked at 'attempt to multiply with overflow', /home/diane/.cargo/registry/src/github.com-1ecc6299db9ec823/swc_ecma_parser-0.57.3/src/lexer/number.rs:277:29
stack backtrace:
0: rust_begin_unwind
at /rustc/9bc8c42bb2f19e745a63f3445f1ac248fb015e53/library/std/src/panicking.rs:493:5
1: core::panicking::panic_fmt
at /rustc/9bc8c42bb2f19e745a63f3445f1ac248fb015e53/library/core/src/panicking.rs:92:14
2: core::panicking::panic
at /rustc/9bc8c42bb2f19e745a63f3445f1ac248fb015e53/library/core/src/panicking.rs:50:5
3: swc_ecma_parser::lexer::number::<impl swc_ecma_parser::lexer::Lexer<I>>::read_int_u32::{{closure}}
at /home/diane/.cargo/registry/src/github.com-1ecc6299db9ec823/swc_ecma_parser-0.57.3/src/lexer/number.rs:277:29
```
The swc code with the overflow:
```rust
pub(super) fn read_int_u32(
&mut self,
radix: u8,
len: u8,
raw: &mut Raw,
) -> LexResult<Option<u32>> {
let mut count = 0;
let v = self.read_digits(
radix,
|opt: Option<u32>, radix, val| {
count += 1;
let total = opt.unwrap_or_default() * radix as u32 + val as u32; // line causing the overflow
(Some(total), count != len)
},
raw,
true,
)?;
if len != 0 && count != len {
Ok(None)
} else {
Ok(v)
}
}
```
| 1.11 | diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -652,9 +652,9 @@ dependencies = [
[[package]]
name = "deno_doc"
-version = "0.5.0"
+version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b22f258ef461d9f5b04703d1510137fa9c09f128a5b4fb51fc665d9dd841c57b"
+checksum = "f543d8cfd09d98c9c0beb81a1ff67b719764fb8023ed2d218d6b7cc7a1035774"
dependencies = [
"futures",
"lazy_static",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -684,9 +684,9 @@ dependencies = [
[[package]]
name = "deno_lint"
-version = "0.6.1"
+version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "08a749e74bfdc6dd0ce058d32ce3ff91c326ac649a7d28a648afc2ddc126434f"
+checksum = "26bcb80ab1f4ff9bf87ec4fe161790a56e017cc07f7e91ee8c01bc0ceabe59a7"
dependencies = [
"anyhow",
"derive_more",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -913,9 +913,9 @@ dependencies = [
[[package]]
name = "dprint-plugin-typescript"
-version = "0.46.0"
+version = "0.46.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "920f97045333dc153ed59632fa7b0af2b78c7296f592b1a05d1b9412ee06b915"
+checksum = "a2415a2015399b9f5343f1f3401c20c415d0fe7cb16000c7e001c8038d618899"
dependencies = [
"dprint-core",
"dprint-swc-ecma-ast-view",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -927,9 +927,9 @@ dependencies = [
[[package]]
name = "dprint-swc-ecma-ast-view"
-version = "0.20.0"
+version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8f7bf11acc08943f260b14467774a77e23f47727b8189768c9ecd283fb4d671"
+checksum = "77d3e8cf5128933adc5b3b9955730c4ebda2335fdbb24da4f53f004ee7764a10"
dependencies = [
"bumpalo",
"fnv",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3128,9 +3128,9 @@ dependencies = [
[[package]]
name = "swc_bundler"
-version = "0.37.4"
+version = "0.40.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ec0d9a12ece4dcde5e3d565eb97365fed0eee333e683887199971aaab82180f4"
+checksum = "3dd60349986e0667631776547a5818a26e00a707eef653c51454d19a6b463c7c"
dependencies = [
"ahash 0.7.2",
"anyhow",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3180,9 +3180,9 @@ dependencies = [
[[package]]
name = "swc_ecma_ast"
-version = "0.45.0"
+version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "acd752f1785f4dc4c9597464c4079e1f25e90dc1c533d026188e2666a83e9863"
+checksum = "f9e64e7a5db16d1a3887291e149bfe0603cd8886c64ca0e210519a879eada926"
dependencies = [
"is-macro",
"num-bigint",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3194,9 +3194,9 @@ dependencies = [
[[package]]
name = "swc_ecma_codegen"
-version = "0.55.4"
+version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fe9bb47bc7d667a841c2b5ce3b254cc6a8f6115554245f1fe666b404a7ec5bf3"
+checksum = "f463acd9d19f52b051dfd99179c9ee6d75298e3ed3064bc4e03996f88c656d42"
dependencies = [
"bitflags",
"num-bigint",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3223,9 +3223,9 @@ dependencies = [
[[package]]
name = "swc_ecma_dep_graph"
-version = "0.25.0"
+version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7dec309a2d96796cf28795c70458ae7b00ae02d9c789cd68a743494e7d2d77a5"
+checksum = "59eaae350a3ccaa0e1d9cda09f02c4cdd7cda7d55fed8af1480b72a471bd0914"
dependencies = [
"swc_atoms",
"swc_common",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3235,9 +3235,9 @@ dependencies = [
[[package]]
name = "swc_ecma_parser"
-version = "0.57.4"
+version = "0.60.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "99a1faddea4db217e04beccd709dab0421a1b3bebc753490311c98625d5de5ab"
+checksum = "5118746b81e7b0cab2d9920383a384567647c623f8a7b73aa87a553fadc572e5"
dependencies = [
"either",
"enum_kind",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3256,9 +3256,9 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms"
-version = "0.50.2"
+version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cf023d414024c3980d7d78f9cc982595947127a34cf5ff9efa123905b453853a"
+checksum = "d112414d2ab2e46ca0a8bf2e09febe8bf2ecc9c4ca082b0a40894de16a59e261"
dependencies = [
"swc_atoms",
"swc_common",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3276,9 +3276,9 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms_base"
-version = "0.15.7"
+version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50b919b52ccd38ecd37a99eb957814e1ad24ad3ef06c32865cde72728a75fb83"
+checksum = "7320ce4841ee0f81341bd2534fb82389c9b0e4c7caad5a0b7e4b83fcc09e5da9"
dependencies = [
"fxhash",
"once_cell",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3295,9 +3295,9 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms_classes"
-version = "0.1.1"
+version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f5eb507162252215ed481130b99c9e7338a43b1b090823bc4940eaa87e1f0d96"
+checksum = "b2d01cc813f01bf4a971df476d3e1def0008aa3d8a93e41c4099517167a1554c"
dependencies = [
"swc_atoms",
"swc_common",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3309,9 +3309,9 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms_optimization"
-version = "0.20.3"
+version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5e7f43630327fef5d4a5f07219dac1b6ff6ac61a7cac9f26fd3fad652719bb40"
+checksum = "143301f9738d3bd909ac83c6fdf845bce1471faf8c91d986af8bf91f118f976f"
dependencies = [
"dashmap",
"fxhash",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3331,9 +3331,9 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms_proposal"
-version = "0.17.1"
+version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2d859a71009d6d034d238e7ab61043f582ed8bf017dfb80ed640ebc1e9274005"
+checksum = "4f74a1fd2b73e7cc36cba6a178721e194363f9cd0b1be56177431bb4ff8f8be8"
dependencies = [
"either",
"fxhash",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3374,9 +3374,9 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms_typescript"
-version = "0.19.4"
+version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b579b104e2a2e6d6336bd6c6c5d288ac1c57aa99b2aec95ef8a8e201fc86a774"
+checksum = "ff5f628a95bb61902da6956a89bd236c0106e8f283834bce3a842c9aa45db0e8"
dependencies = [
"fxhash",
"serde",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3391,9 +3391,9 @@ dependencies = [
[[package]]
name = "swc_ecma_utils"
-version = "0.36.0"
+version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ed66fe08869ff26c45be7de0bf73d3d4fedd839446797404cedea9e12065281"
+checksum = "e4aead4054e4789500228dff53c4f776ea5ab2aae705955497520cb1e3a40940"
dependencies = [
"once_cell",
"scoped-tls",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3406,9 +3406,9 @@ dependencies = [
[[package]]
name = "swc_ecma_visit"
-version = "0.31.0"
+version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c32efec33fd514574cac43c9172861ac4e85eaced6afbf8483114ffbeef78a87"
+checksum = "3d52f36a7e74c2895c97c1d86e61fd74b50027ec838b5c6d0b44485f6cbde868"
dependencies = [
"num-bigint",
"swc_atoms",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3419,9 +3419,9 @@ dependencies = [
[[package]]
name = "swc_ecmascript"
-version = "0.36.3"
+version = "0.39.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fe1b0c92f51a9009ee4265248777df8f5610225fb172c09f2b3a108f403cf7b"
+checksum = "3366daf79ec1a0820dc307fd7cf50536106e2fab11cdeffdf84c0b2a9c9204bb"
dependencies = [
"swc_ecma_ast",
"swc_ecma_codegen",
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -41,8 +41,8 @@ winres = "0.1.11"
[dependencies]
deno_core = { version = "0.91.0", path = "../core" }
-deno_doc = "0.5.0"
-deno_lint = "0.6.1"
+deno_doc = "0.6.0"
+deno_lint = "0.7.0"
deno_runtime = { version = "0.18.0", path = "../runtime" }
atty = "0.2.14"
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -53,7 +53,7 @@ data-url = "0.1.0"
dissimilar = "1.0.2"
dprint-plugin-json = "0.12.0"
dprint-plugin-markdown = "0.8.0"
-dprint-plugin-typescript = "0.46.0"
+dprint-plugin-typescript = "0.46.1"
encoding_rs = "0.8.28"
env_logger = "0.8.3"
fancy-regex = "0.5.0"
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -77,9 +77,9 @@ semver-parser = "0.10.2"
serde = { version = "1.0.125", features = ["derive"] }
shell-escape = "0.1.5"
sourcemap = "6.0.1"
-swc_bundler = "0.37.4"
+swc_bundler = "0.40.0"
swc_common = { version = "0.10.20", features = ["sourcemap"] }
-swc_ecmascript = { version = "0.36.3", features = ["codegen", "dep_graph", "parser", "proposal", "react", "transforms", "typescript", "visit"] }
+swc_ecmascript = { version = "0.39.0", features = ["codegen", "dep_graph", "parser", "proposal", "react", "transforms", "typescript", "visit"] }
tempfile = "3.2.0"
termcolor = "1.1.2"
text-size = "1.1.0"
| 11,007 | diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3351,9 +3351,9 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms_react"
-version = "0.18.2"
+version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a54a3a2942b8a0031ee5f40695553a6096273803bf1f0b655ec5548cfce0474e"
+checksum = "1d165dc9ce3308168b0496e2717cbfbe2eff6b82cd88d0988ad1176ca53e8d22"
dependencies = [
"base64 0.13.0",
"dashmap",
| 67c9937e6658c2be9b54cd95132a1055756e433b |
Will fix this in an upcoming PR. | 2021-06-16T12:35:40Z | denoland/deno | denoland__deno-11006 | [
"11004"
] | 8e4a70c7e9e495ca425bb29cafe1f426ad29c406 | Style guide should encourage code example in comments
With support for running type checking on code block examples in Jsdoc comments, we should upgrade the style guide accordingly.
| 1.11 | diff --git a/docs/contributing/style_guide.md b/docs/contributing/style_guide.md
--- a/docs/contributing/style_guide.md
+++ b/docs/contributing/style_guide.md
@@ -49,8 +49,7 @@ Follow Rust conventions and be consistent with existing code.
## TypeScript
-The TypeScript portions of the codebase include `cli/js` for the built-ins and
-the standard library `std`.
+The TypeScript portion of the code base is the standard library `std`.
### Use TypeScript instead of JavaScript.
diff --git a/docs/contributing/style_guide.md b/docs/contributing/style_guide.md
--- a/docs/contributing/style_guide.md
+++ b/docs/contributing/style_guide.md
@@ -198,9 +197,9 @@ export type { Person } from "./my_file.ts";
### Minimize dependencies; do not make circular imports.
-Although `cli/js` and `std` have no external dependencies, we must still be
-careful to keep internal dependencies simple and manageable. In particular, be
-careful not to introduce circular imports.
+Although `std` has no external dependencies, we must still be careful to keep
+internal dependencies simple and manageable. In particular, be careful not to
+introduce circular imports.
### If a filename starts with an underscore: `_foo.ts`, do not link to it.
diff --git a/docs/contributing/style_guide.md b/docs/contributing/style_guide.md
--- a/docs/contributing/style_guide.md
+++ b/docs/contributing/style_guide.md
@@ -263,21 +262,20 @@ And not:
*/
```
-Code examples should not utilise the triple-back tick (\`\`\`) notation or tags.
-They should just be marked by indentation, which requires a break before the
-block and 6 additional spaces for each line of the example. This is 4 more than
-the first column of the comment. For example:
+Code examples should utilize markdown format, like so:
-```ts
+````ts
/** A straight forward comment and an example:
- *
- * import { foo } from "deno";
- * foo("bar");
+ * ```ts
+ * import { foo } from "deno";
+ * foo("bar");
+ * ```
*/
-```
+````
-Code examples should not contain additional comments. It is already inside a
-comment. If it needs further comments it is not a good example.
+Code examples should not contain additional comments and must not be indented.
+It is already inside a comment. If it needs further comments it is not a good
+example.
### Resolve linting problems using directives
| 11,006 | diff --git a/docs/contributing/style_guide.md b/docs/contributing/style_guide.md
--- a/docs/contributing/style_guide.md
+++ b/docs/contributing/style_guide.md
@@ -296,9 +294,8 @@ problems, but it should be used scarcely.
### Each module should come with a test module.
Every module with public functionality `foo.ts` should come with a test module
-`foo_test.ts`. A test for a `cli/js` module should go in `cli/js/tests` due to
-their different contexts, otherwise it should just be a sibling to the tested
-module.
+`foo_test.ts`. A test for a `std` module should go in `std/tests` due to their
+different contexts, otherwise it should just be a sibling to the tested module.
### Unit Tests should be explicit.
| 67c9937e6658c2be9b54cd95132a1055756e433b |
Would love to see this too, right now it’s a jack approach to get global declarations
I will be raising a PR soon that delivers this feature using the `compilerOptions.types` across all different forms of type checking we support (`Deno.emit` and the `--config tsconfig.json` forms). | 2021-06-16T03:42:42Z | denoland/deno | denoland__deno-10999 | [
"10677"
] | 952caa79b32e6c249977281ed494d4b1f98ed451 | Deno.emit: Add option for ambient type declarations
This is a follow up to the discussion at https://github.com/denoland/deno/discussions/10549
I see that I can supply predefined environment enums in the emit options `compilerOptions.lib` array (e.g. `ES2017`, `DOM.Iterable`, etc.), but I don't see a way to provide other environment types (e.g. paths to declaration files) because properties like `compilerOptions.typeRoots` aren't supported.
@kitsonk [suggested](https://github.com/denoland/deno/discussions/10549#discussioncomment-716399) using the [`compilerOptions.types`](https://doc.deno.land/builtin/unstable#Deno.CompilerOptions) property, but that doesn't seem to work (it produces another error).
If I include
```ts
import "./types/mod.d.ts";
```
at the top of every source file then it compiles without errors, but that is not a maintainable approach.
If I want to compile for other [custom] runtime environments, do I really have to import the types into every source file or is there a configuration alternative?
I'm attaching a simple example for demonstration and reproduction:
[example.zip](https://github.com/denoland/deno/files/6497380/example.zip)
```
example % cat run
deno --unstable run --allow-read=. --allow-write=. main.ts
example % ./run
TS2688 [ERROR]: Cannot find type definition file for './types/shared-node-browser.d.ts'.
The file is in the program because:
Entry point of type library './types/shared-node-browser.d.ts' specified in compilerOptions
TS2584 [ERROR]: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.
console.log('hello world');
~~~~~~~
at file:///Users/jesse/Downloads/example/mod.ts:5:3
Found 2 errors.
"mod.bundle.cjs" written
```
| 1.11 | diff --git a/cli/build.rs b/cli/build.rs
--- a/cli/build.rs
+++ b/cli/build.rs
@@ -163,6 +163,10 @@ fn create_compiler_snapshot(
}))
}),
);
+ js_runtime.register_op(
+ "op_cwd",
+ op_sync(move |_state, _args: Value, _: ()| Ok(json!("cache:///"))),
+ );
// using the same op that is used in `tsc.rs` for loading modules and reading
// files, but a slightly different implementation at build time.
js_runtime.register_op(
diff --git a/cli/config_file.rs b/cli/config_file.rs
--- a/cli/config_file.rs
+++ b/cli/config_file.rs
@@ -31,6 +31,14 @@ pub struct EmitConfigOptions {
pub jsx_fragment_factory: String,
}
+/// There are certain compiler options that can impact what modules are part of
+/// a module graph, which need to be deserialized into a structure for analysis.
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CompilerOptions {
+ pub types: Option<Vec<String>>,
+}
+
/// A structure that represents a set of options that were ignored and the
/// path those options came from.
#[derive(Debug, Clone, PartialEq)]
diff --git a/cli/config_file.rs b/cli/config_file.rs
--- a/cli/config_file.rs
+++ b/cli/config_file.rs
@@ -90,7 +98,6 @@ pub const IGNORED_COMPILER_OPTIONS: &[&str] = &[
"sourceMap",
"sourceRoot",
"target",
- "types",
"useDefineForClassFields",
];
diff --git a/cli/dts/lib.deno.unstable.d.ts b/cli/dts/lib.deno.unstable.d.ts
--- a/cli/dts/lib.deno.unstable.d.ts
+++ b/cli/dts/lib.deno.unstable.d.ts
@@ -421,11 +421,25 @@ declare namespace Deno {
| "es2019"
| "es2020"
| "esnext";
- /** List of names of type definitions to include. Defaults to `undefined`.
+ /** List of names of type definitions to include when type checking.
+ * Defaults to `undefined`.
*
* The type definitions are resolved according to the normal Deno resolution
- * irrespective of if sources are provided on the call. Like other Deno
- * modules, there is no "magical" resolution. For example:
+ * irrespective of if sources are provided on the call. In addition, unlike
+ * passing the `--config` option on startup, there is no base to resolve
+ * relative specifiers, so the specifiers here have to be fully qualified
+ * URLs or paths. For example:
+ *
+ * ```ts
+ * Deno.emit("./a.ts", {
+ * compilerOptions: {
+ * types: [
+ * "https://deno.land/x/pkg/types.d.ts",
+ * "/Users/me/pkg/types.d.ts",
+ * ]
+ * }
+ * });
+ * ```
*/
types?: string[];
/** Emit class fields with ECMAScript-standard semantics. Defaults to
diff --git a/cli/lsp/config.rs b/cli/lsp/config.rs
--- a/cli/lsp/config.rs
+++ b/cli/lsp/config.rs
@@ -10,6 +10,7 @@ use deno_core::serde_json::Value;
use deno_core::url::Url;
use deno_core::ModuleSpecifier;
use log::error;
+use lsp::WorkspaceFolder;
use lspower::lsp;
use std::collections::BTreeMap;
use std::collections::HashMap;
diff --git a/cli/lsp/config.rs b/cli/lsp/config.rs
--- a/cli/lsp/config.rs
+++ b/cli/lsp/config.rs
@@ -188,6 +189,7 @@ pub struct ConfigSnapshot {
pub client_capabilities: ClientCapabilities,
pub root_uri: Option<Url>,
pub settings: Settings,
+ pub workspace_folders: Option<Vec<lsp::WorkspaceFolder>>,
}
impl ConfigSnapshot {
diff --git a/cli/lsp/config.rs b/cli/lsp/config.rs
--- a/cli/lsp/config.rs
+++ b/cli/lsp/config.rs
@@ -218,6 +220,7 @@ pub struct Config {
pub root_uri: Option<Url>,
settings: Arc<RwLock<Settings>>,
tx: mpsc::Sender<ConfigRequest>,
+ pub workspace_folders: Option<Vec<WorkspaceFolder>>,
}
impl Config {
diff --git a/cli/lsp/config.rs b/cli/lsp/config.rs
--- a/cli/lsp/config.rs
+++ b/cli/lsp/config.rs
@@ -319,6 +322,7 @@ impl Config {
root_uri: None,
settings,
tx,
+ workspace_folders: None,
}
}
diff --git a/cli/lsp/config.rs b/cli/lsp/config.rs
--- a/cli/lsp/config.rs
+++ b/cli/lsp/config.rs
@@ -343,6 +347,7 @@ impl Config {
.try_read()
.map_err(|_| anyhow!("Error reading settings."))?
.clone(),
+ workspace_folders: self.workspace_folders.clone(),
})
}
diff --git a/cli/lsp/language_server.rs b/cli/lsp/language_server.rs
--- a/cli/lsp/language_server.rs
+++ b/cli/lsp/language_server.rs
@@ -70,6 +70,7 @@ pub struct StateSnapshot {
pub assets: Assets,
pub config: ConfigSnapshot,
pub documents: DocumentCache,
+ pub maybe_config_uri: Option<ModuleSpecifier>,
pub module_registries: registries::ModuleRegistry,
pub performance: Performance,
pub sources: Sources,
diff --git a/cli/lsp/language_server.rs b/cli/lsp/language_server.rs
--- a/cli/lsp/language_server.rs
+++ b/cli/lsp/language_server.rs
@@ -92,6 +93,9 @@ pub(crate) struct Inner {
module_registries: registries::ModuleRegistry,
/// The path to the module registries cache
module_registries_location: PathBuf,
+ /// An optional configuration file which has been specified in the client
+ /// options.
+ maybe_config_file: Option<ConfigFile>,
/// An optional URL which provides the location of a TypeScript configuration
/// file which will be used by the Deno LSP.
maybe_config_uri: Option<Url>,
diff --git a/cli/lsp/language_server.rs b/cli/lsp/language_server.rs
--- a/cli/lsp/language_server.rs
+++ b/cli/lsp/language_server.rs
@@ -138,6 +142,7 @@ impl Inner {
config,
diagnostics_server,
documents: Default::default(),
+ maybe_config_file: Default::default(),
maybe_config_uri: Default::default(),
maybe_import_map: Default::default(),
maybe_import_map_uri: Default::default(),
diff --git a/cli/lsp/language_server.rs b/cli/lsp/language_server.rs
--- a/cli/lsp/language_server.rs
+++ b/cli/lsp/language_server.rs
@@ -326,6 +331,7 @@ impl Inner {
LspError::internal_error()
})?,
documents: self.documents.clone(),
+ maybe_config_uri: self.maybe_config_uri.clone(),
module_registries: self.module_registries.clone(),
performance: self.performance.clone(),
sources: self.sources.clone(),
diff --git a/cli/lsp/language_server.rs b/cli/lsp/language_server.rs
--- a/cli/lsp/language_server.rs
+++ b/cli/lsp/language_server.rs
@@ -477,6 +483,7 @@ impl Inner {
};
let (value, maybe_ignored_options) = config_file.as_compiler_options()?;
tsconfig.merge(&value);
+ self.maybe_config_file = Some(config_file);
self.maybe_config_uri = Some(config_url);
if let Some(ignored_options) = maybe_ignored_options {
// TODO(@kitsonk) turn these into diagnostics that can be sent to the
diff --git a/cli/lsp/language_server.rs b/cli/lsp/language_server.rs
--- a/cli/lsp/language_server.rs
+++ b/cli/lsp/language_server.rs
@@ -2281,20 +2288,28 @@ impl Inner {
if !params.uris.is_empty() {
for identifier in ¶ms.uris {
let specifier = self.url_map.normalize_url(&identifier.uri);
- sources::cache(&specifier, &self.maybe_import_map)
- .await
- .map_err(|err| {
- error!("{}", err);
- LspError::internal_error()
- })?;
- }
- } else {
- sources::cache(&referrer, &self.maybe_import_map)
+ sources::cache(
+ &specifier,
+ &self.maybe_import_map,
+ &self.maybe_config_file,
+ )
.await
.map_err(|err| {
error!("{}", err);
LspError::internal_error()
})?;
+ }
+ } else {
+ sources::cache(
+ &referrer,
+ &self.maybe_import_map,
+ &self.maybe_config_file,
+ )
+ .await
+ .map_err(|err| {
+ error!("{}", err);
+ LspError::internal_error()
+ })?;
}
// now that we have dependencies loaded, we need to re-analyze them and
// invalidate some diagnostics
diff --git a/cli/lsp/sources.rs b/cli/lsp/sources.rs
--- a/cli/lsp/sources.rs
+++ b/cli/lsp/sources.rs
@@ -4,6 +4,7 @@ use super::analysis;
use super::text::LineIndex;
use super::tsc;
+use crate::config_file::ConfigFile;
use crate::file_fetcher::get_source_from_bytes;
use crate::file_fetcher::map_content_type;
use crate::file_fetcher::SUPPORTED_SCHEMES;
diff --git a/cli/lsp/sources.rs b/cli/lsp/sources.rs
--- a/cli/lsp/sources.rs
+++ b/cli/lsp/sources.rs
@@ -33,6 +34,7 @@ use tsc::NavigationTree;
pub async fn cache(
specifier: &ModuleSpecifier,
maybe_import_map: &Option<ImportMap>,
+ maybe_config_file: &Option<ConfigFile>,
) -> Result<(), AnyError> {
let program_state = Arc::new(ProgramState::build(Default::default()).await?);
let handler = Arc::new(Mutex::new(FetchHandler::new(
diff --git a/cli/lsp/sources.rs b/cli/lsp/sources.rs
--- a/cli/lsp/sources.rs
+++ b/cli/lsp/sources.rs
@@ -41,6 +43,7 @@ pub async fn cache(
Permissions::allow_all(),
)?));
let mut builder = GraphBuilder::new(handler, maybe_import_map.clone(), None);
+ builder.analyze_config_file(maybe_config_file).await?;
builder.add(specifier, false).await
}
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -61,14 +61,18 @@ impl TsServer {
pub fn new() -> Self {
let (tx, mut rx) = mpsc::unbounded_channel::<Request>();
let _join_handle = thread::spawn(move || {
- // TODO(@kitsonk) we need to allow displaying diagnostics here, but the
- // current compiler snapshot sends them to stdio which would totally break
- // the language server...
- let mut ts_runtime = start(false).expect("could not start tsc");
+ let mut ts_runtime = load().expect("could not load tsc");
let runtime = create_basic_runtime();
runtime.block_on(async {
+ let mut started = false;
while let Some((req, state_snapshot, tx)) = rx.recv().await {
+ if !started {
+ // TODO(@kitsonk) need to reflect the debug state of the lsp here
+ start(&mut ts_runtime, false, &state_snapshot)
+ .expect("could not start tsc");
+ started = true;
+ }
let value = request(&mut ts_runtime, state_snapshot, req);
if tx.send(value).is_err() {
warn!("Unable to send result to client.");
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -572,7 +576,7 @@ impl DocumentSpan {
line_index: &LineIndex,
language_server: &mut language_server::Inner,
) -> Option<lsp::LocationLink> {
- let target_specifier = resolve_url(&self.file_name).unwrap();
+ let target_specifier = normalize_specifier(&self.file_name).unwrap();
let target_line_index = language_server
.get_line_index(target_specifier.clone())
.await
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -773,7 +777,7 @@ impl ImplementationLocation {
line_index: &LineIndex,
language_server: &mut language_server::Inner,
) -> lsp::Location {
- let specifier = resolve_url(&self.document_span.file_name).unwrap();
+ let specifier = normalize_specifier(&self.document_span.file_name).unwrap();
let uri = language_server
.url_map
.normalize_specifier(&specifier)
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -819,7 +823,7 @@ impl RenameLocations {
let mut text_document_edit_map: HashMap<Url, lsp::TextDocumentEdit> =
HashMap::new();
for location in self.locations.iter() {
- let specifier = resolve_url(&location.document_span.file_name)?;
+ let specifier = normalize_specifier(&location.document_span.file_name)?;
let uri = language_server.url_map.normalize_specifier(&specifier)?;
// ensure TextDocumentEdit for `location.file_name`.
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -982,7 +986,7 @@ impl FileTextChanges {
&self,
language_server: &mut language_server::Inner,
) -> Result<lsp::TextDocumentEdit, AnyError> {
- let specifier = resolve_url(&self.file_name)?;
+ let specifier = normalize_specifier(&self.file_name)?;
let line_index = language_server.get_line_index(specifier.clone()).await?;
let edits = self
.text_changes
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1102,7 +1106,7 @@ impl ReferenceEntry {
line_index: &LineIndex,
language_server: &mut language_server::Inner,
) -> lsp::Location {
- let specifier = resolve_url(&self.document_span.file_name).unwrap();
+ let specifier = normalize_specifier(&self.document_span.file_name).unwrap();
let uri = language_server
.url_map
.normalize_specifier(&specifier)
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1134,7 +1138,7 @@ impl CallHierarchyItem {
language_server: &mut language_server::Inner,
maybe_root_path: Option<&Path>,
) -> Option<lsp::CallHierarchyItem> {
- let target_specifier = resolve_url(&self.file).unwrap();
+ let target_specifier = normalize_specifier(&self.file).unwrap();
let target_line_index = language_server
.get_line_index(target_specifier)
.await
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1153,7 +1157,7 @@ impl CallHierarchyItem {
language_server: &mut language_server::Inner,
maybe_root_path: Option<&Path>,
) -> lsp::CallHierarchyItem {
- let target_specifier = resolve_url(&self.file).unwrap();
+ let target_specifier = normalize_specifier(&self.file).unwrap();
let uri = language_server
.url_map
.normalize_specifier(&target_specifier)
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1234,7 +1238,7 @@ impl CallHierarchyIncomingCall {
language_server: &mut language_server::Inner,
maybe_root_path: Option<&Path>,
) -> Option<lsp::CallHierarchyIncomingCall> {
- let target_specifier = resolve_url(&self.from.file).unwrap();
+ let target_specifier = normalize_specifier(&self.from.file).unwrap();
let target_line_index = language_server
.get_line_index(target_specifier)
.await
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1269,7 +1273,7 @@ impl CallHierarchyOutgoingCall {
language_server: &mut language_server::Inner,
maybe_root_path: Option<&Path>,
) -> Option<lsp::CallHierarchyOutgoingCall> {
- let target_specifier = resolve_url(&self.to.file).unwrap();
+ let target_specifier = normalize_specifier(&self.to.file).unwrap();
let target_line_index = language_server
.get_line_index(target_specifier)
.await
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1803,6 +1807,7 @@ struct State<'a> {
response: Option<Response>,
state_snapshot: StateSnapshot,
snapshots: HashMap<(ModuleSpecifier, Cow<'a, str>), String>,
+ specifiers: HashMap<String, String>,
}
impl<'a> State<'a> {
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1812,8 +1817,36 @@ impl<'a> State<'a> {
response: None,
state_snapshot,
snapshots: HashMap::default(),
+ specifiers: HashMap::default(),
}
}
+
+ /// If a normalized version of the specifier has been stored for tsc, this
+ /// will "restore" it for communicating back to the tsc language server,
+ /// otherwise it will just convert the specifier to a string.
+ fn denormalize_specifier(&self, specifier: &ModuleSpecifier) -> String {
+ let specifier_str = specifier.to_string();
+ self
+ .specifiers
+ .get(&specifier_str)
+ .unwrap_or(&specifier_str)
+ .to_string()
+ }
+
+ /// In certain situations, tsc can request "invalid" specifiers and this will
+ /// normalize and memoize the specifier.
+ fn normalize_specifier<S: AsRef<str>>(
+ &mut self,
+ specifier: S,
+ ) -> Result<ModuleSpecifier, AnyError> {
+ let specifier_str = specifier.as_ref().replace(".d.ts.d.ts", ".d.ts");
+ if specifier_str != specifier.as_ref() {
+ self
+ .specifiers
+ .insert(specifier_str.clone(), specifier.as_ref().to_string());
+ }
+ ModuleSpecifier::parse(&specifier_str).map_err(|err| err.into())
+ }
}
/// If a snapshot is missing from the state cache, add it.
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1846,6 +1879,13 @@ fn cache_snapshot(
Ok(())
}
+fn normalize_specifier<S: AsRef<str>>(
+ specifier: S,
+) -> Result<ModuleSpecifier, AnyError> {
+ resolve_url(specifier.as_ref().replace(".d.ts.d.ts", ".d.ts").as_str())
+ .map_err(|err| err.into())
+}
+
// buffer-less json_sync ops
fn op<F, V, R>(op_fn: F) -> Box<OpFn>
where
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1876,12 +1916,29 @@ fn op_dispose(
.state_snapshot
.performance
.mark("op_dispose", Some(&args));
- let specifier = resolve_url(&args.specifier)?;
+ let specifier = state.normalize_specifier(&args.specifier)?;
state.snapshots.remove(&(specifier, args.version.into()));
state.state_snapshot.performance.measure(mark);
Ok(true)
}
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct SpecifierArgs {
+ specifier: String,
+}
+
+fn op_exists(state: &mut State, args: SpecifierArgs) -> Result<bool, AnyError> {
+ let mark = state
+ .state_snapshot
+ .performance
+ .mark("op_exists", Some(&args));
+ let specifier = state.normalize_specifier(args.specifier)?;
+ let result = state.state_snapshot.sources.contains_key(&specifier);
+ state.state_snapshot.performance.measure(mark);
+ Ok(result)
+}
+
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct GetChangeRangeArgs {
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1901,7 +1958,7 @@ fn op_get_change_range(
.state_snapshot
.performance
.mark("op_get_change_range", Some(&args));
- let specifier = resolve_url(&args.specifier)?;
+ let specifier = state.normalize_specifier(&args.specifier)?;
cache_snapshot(state, &specifier, args.version.clone())?;
let r = if let Some(current) = state
.snapshots
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1948,7 +2005,7 @@ fn op_get_length(
.state_snapshot
.performance
.mark("op_get_length", Some(&args));
- let specifier = resolve_url(&args.specifier)?;
+ let specifier = state.normalize_specifier(args.specifier)?;
let r = if let Some(Some(asset)) = state.state_snapshot.assets.get(&specifier)
{
Ok(asset.length)
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1981,7 +2038,7 @@ fn op_get_text(
.state_snapshot
.performance
.mark("op_get_text", Some(&args));
- let specifier = resolve_url(&args.specifier)?;
+ let specifier = state.normalize_specifier(args.specifier)?;
let content =
if let Some(Some(content)) = state.state_snapshot.assets.get(&specifier) {
content.text.clone()
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -1997,6 +2054,20 @@ fn op_get_text(
Ok(text::slice(&content, args.start..args.end).to_string())
}
+fn op_load(
+ state: &mut State,
+ args: SpecifierArgs,
+) -> Result<Option<String>, AnyError> {
+ let mark = state
+ .state_snapshot
+ .performance
+ .mark("op_load", Some(&args));
+ let specifier = state.normalize_specifier(args.specifier)?;
+ let result = state.state_snapshot.sources.get_source(&specifier);
+ state.state_snapshot.performance.measure(mark);
+ Ok(result)
+}
+
fn op_resolve(
state: &mut State,
args: ResolveArgs,
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2006,7 +2077,7 @@ fn op_resolve(
.performance
.mark("op_resolve", Some(&args));
let mut resolved = Vec::new();
- let referrer = resolve_url(&args.base)?;
+ let referrer = state.normalize_specifier(&args.base)?;
let sources = &mut state.state_snapshot.sources;
if state.state_snapshot.documents.contains_key(&referrer) {
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2124,7 +2195,7 @@ fn op_script_version(
.state_snapshot
.performance
.mark("op_script_version", Some(&args));
- let specifier = resolve_url(&args.specifier)?;
+ let specifier = state.normalize_specifier(args.specifier)?;
let r = if specifier.scheme() == "asset" {
if state.state_snapshot.assets.contains_key(&specifier) {
Ok(Some("1".to_string()))
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2151,7 +2222,7 @@ fn op_script_version(
/// Create and setup a JsRuntime based on a snapshot. It is expected that the
/// supplied snapshot is an isolate that contains the TypeScript language
/// server.
-pub fn start(debug: bool) -> Result<JsRuntime, AnyError> {
+fn load() -> Result<JsRuntime, AnyError> {
let mut runtime = JsRuntime::new(RuntimeOptions {
startup_snapshot: Some(tsc::compiler_snapshot()),
..Default::default()
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2164,20 +2235,36 @@ pub fn start(debug: bool) -> Result<JsRuntime, AnyError> {
}
runtime.register_op("op_dispose", op(op_dispose));
+ runtime.register_op("op_exists", op(op_exists));
runtime.register_op("op_get_change_range", op(op_get_change_range));
runtime.register_op("op_get_length", op(op_get_length));
runtime.register_op("op_get_text", op(op_get_text));
+ runtime.register_op("op_load", op(op_load));
runtime.register_op("op_resolve", op(op_resolve));
runtime.register_op("op_respond", op(op_respond));
runtime.register_op("op_script_names", op(op_script_names));
runtime.register_op("op_script_version", op(op_script_version));
runtime.sync_ops_cache();
- let init_config = json!({ "debug": debug });
+ Ok(runtime)
+}
+
+/// Instruct a language server runtime to start the language server and provide
+/// it with a minimal bootstrap configuration.
+fn start(
+ runtime: &mut JsRuntime,
+ debug: bool,
+ state_snapshot: &StateSnapshot,
+) -> Result<(), AnyError> {
+ let root_uri = state_snapshot
+ .config
+ .root_uri
+ .clone()
+ .unwrap_or_else(|| Url::parse("cache:///").unwrap());
+ let init_config = json!({ "debug": debug, "rootUri": root_uri });
let init_src = format!("globalThis.serverInit({});", init_config);
- runtime.execute("[native code]", &init_src)?;
- Ok(runtime)
+ runtime.execute("[native code]", &init_src)
}
#[derive(Debug, Serialize)]
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2369,7 +2456,7 @@ pub enum RequestMethod {
}
impl RequestMethod {
- pub fn to_value(&self, id: usize) -> Value {
+ fn to_value(&self, state: &State, id: usize) -> Value {
match self {
RequestMethod::Configure(config) => json!({
"id": id,
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2386,7 +2473,7 @@ impl RequestMethod {
json!({
"id": id,
"method": "findRenameLocations",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position,
"findInStrings": find_in_strings,
"findInComments": find_in_comments,
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2406,7 +2493,7 @@ impl RequestMethod {
)) => json!({
"id": id,
"method": "getCodeFixes",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"startPosition": start_pos,
"endPosition": end_pos,
"errorCodes": error_codes,
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2414,7 +2501,7 @@ impl RequestMethod {
RequestMethod::GetCombinedCodeFix((specifier, fix_id)) => json!({
"id": id,
"method": "getCombinedCodeFix",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"fixId": fix_id,
}),
RequestMethod::GetCompletionDetails(args) => json!({
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2426,7 +2513,7 @@ impl RequestMethod {
json!({
"id": id,
"method": "getCompletions",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position,
"preferences": preferences,
})
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2434,13 +2521,13 @@ impl RequestMethod {
RequestMethod::GetDefinition((specifier, position)) => json!({
"id": id,
"method": "getDefinition",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position,
}),
RequestMethod::GetDiagnostics(specifiers) => json!({
"id": id,
"method": "getDiagnostics",
- "specifiers": specifiers,
+ "specifiers": specifiers.iter().map(|s| state.denormalize_specifier(s)).collect::<Vec<String>>(),
}),
RequestMethod::GetDocumentHighlights((
specifier,
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2449,7 +2536,7 @@ impl RequestMethod {
)) => json!({
"id": id,
"method": "getDocumentHighlights",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position,
"filesToSearch": files_to_search,
}),
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2457,43 +2544,43 @@ impl RequestMethod {
json!({
"id": id,
"method": "getEncodedSemanticClassifications",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"span": span,
})
}
RequestMethod::GetImplementation((specifier, position)) => json!({
"id": id,
"method": "getImplementation",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position,
}),
RequestMethod::GetNavigationTree(specifier) => json!({
"id": id,
"method": "getNavigationTree",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
}),
RequestMethod::GetOutliningSpans(specifier) => json!({
"id": id,
"method": "getOutliningSpans",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
}),
RequestMethod::GetQuickInfo((specifier, position)) => json!({
"id": id,
"method": "getQuickInfo",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position,
}),
RequestMethod::GetReferences((specifier, position)) => json!({
"id": id,
"method": "getReferences",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position,
}),
RequestMethod::GetSignatureHelpItems((specifier, position, options)) => {
json!({
"id": id,
"method": "getSignatureHelpItems",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position,
"options": options,
})
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2502,7 +2589,7 @@ impl RequestMethod {
json!({
"id": id,
"method": "getSmartSelectionRange",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position
})
}
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2514,7 +2601,7 @@ impl RequestMethod {
json!({
"id": id,
"method": "prepareCallHierarchy",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position
})
}
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2525,7 +2612,7 @@ impl RequestMethod {
json!({
"id": id,
"method": "provideCallHierarchyIncomingCalls",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position
})
}
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2536,7 +2623,7 @@ impl RequestMethod {
json!({
"id": id,
"method": "provideCallHierarchyOutgoingCalls",
- "specifier": specifier,
+ "specifier": state.denormalize_specifier(specifier),
"position": position
})
}
diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2551,15 +2638,15 @@ pub fn request(
method: RequestMethod,
) -> Result<Value, AnyError> {
let performance = state_snapshot.performance.clone();
- let id = {
+ let request_params = {
let op_state = runtime.op_state();
let mut op_state = op_state.borrow_mut();
let state = op_state.borrow_mut::<State>();
state.state_snapshot = state_snapshot;
state.last_id += 1;
- state.last_id
+ let id = state.last_id;
+ method.to_value(state, id)
};
- let request_params = method.to_value(id);
let mark = performance.mark("request", Some(request_params.clone()));
let request_src = format!("globalThis.serverRequest({});", request_params);
runtime.execute("[native_code]", &request_src)?;
diff --git a/cli/main.rs b/cli/main.rs
--- a/cli/main.rs
+++ b/cli/main.rs
@@ -434,6 +434,9 @@ async fn info_command(
program_state.lockfile.clone(),
);
builder.add(&specifier, false).await?;
+ builder
+ .analyze_config_file(&program_state.maybe_config_file)
+ .await?;
let graph = builder.get_graph();
let info = graph.info()?;
diff --git a/cli/main.rs b/cli/main.rs
--- a/cli/main.rs
+++ b/cli/main.rs
@@ -582,6 +585,9 @@ async fn create_module_graph_and_maybe_check(
program_state.lockfile.clone(),
);
builder.add(&module_specifier, false).await?;
+ builder
+ .analyze_config_file(&program_state.maybe_config_file)
+ .await?;
let module_graph = builder.get_graph();
if !program_state.flags.no_check {
diff --git a/cli/main.rs b/cli/main.rs
--- a/cli/main.rs
+++ b/cli/main.rs
@@ -820,6 +826,9 @@ async fn run_with_watch(flags: Flags, script: String) -> Result<(), AnyError> {
program_state.lockfile.clone(),
);
builder.add(&main_module, false).await?;
+ builder
+ .analyze_config_file(&program_state.maybe_config_file)
+ .await?;
let module_graph = builder.get_graph();
// Find all local files in graph
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -7,6 +7,7 @@ use crate::ast::Location;
use crate::ast::ParsedModule;
use crate::checksum;
use crate::colors;
+use crate::config_file::CompilerOptions;
use crate::config_file::ConfigFile;
use crate::config_file::IgnoredCompilerOptions;
use crate::config_file::TsConfig;
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -31,11 +32,13 @@ use deno_core::error::AnyError;
use deno_core::error::Context;
use deno_core::futures::stream::FuturesUnordered;
use deno_core::futures::stream::StreamExt;
+use deno_core::resolve_import;
use deno_core::resolve_url_or_path;
use deno_core::serde::Deserialize;
use deno_core::serde::Deserializer;
use deno_core::serde::Serialize;
use deno_core::serde::Serializer;
+use deno_core::serde_json;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::url::Url;
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -890,11 +893,20 @@ impl Graph {
vec![config.as_bytes(), version::deno().as_bytes().to_owned()];
let graph = Arc::new(Mutex::new(self));
+ let maybe_config_specifier =
+ if let Some(config_file) = &options.maybe_config_file {
+ ModuleSpecifier::from_file_path(&config_file.path).ok()
+ } else {
+ None
+ };
+ debug!("maybe_config_specifier: {:?}", maybe_config_specifier);
+
let response = tsc::exec(tsc::Request {
config: config.clone(),
debug: options.debug,
graph: graph.clone(),
hash_data,
+ maybe_config_specifier,
maybe_tsbuildinfo,
root_names,
})?;
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -958,6 +970,11 @@ impl Graph {
})
}
+ /// Indicates if the module graph contains the supplied specifier or not.
+ pub fn contains(&self, specifier: &ModuleSpecifier) -> bool {
+ matches!(self.get_module(specifier), ModuleSlot::Module(_))
+ }
+
/// Emit the module graph in a specific format. This is specifically designed
/// to be an "all-in-one" API for access by the runtime, allowing both
/// emitting single modules as well as bundles, using Deno module resolution
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -1025,6 +1042,7 @@ impl Graph {
debug: options.debug,
graph: graph.clone(),
hash_data,
+ maybe_config_specifier: None,
maybe_tsbuildinfo: None,
root_names,
})?;
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -1829,26 +1847,7 @@ impl GraphBuilder {
specifier: &ModuleSpecifier,
is_dynamic: bool,
) -> Result<(), AnyError> {
- self.fetch(specifier, &None, is_dynamic);
-
- loop {
- match self.pending.next().await {
- Some(Err((specifier, err))) => {
- self
- .graph
- .modules
- .insert(specifier, ModuleSlot::Err(Arc::new(err)));
- }
- Some(Ok(cached_module)) => {
- let is_root = &cached_module.specifier == specifier;
- self.visit(cached_module, is_root, is_dynamic)?;
- }
- _ => {}
- }
- if self.pending.is_empty() {
- break;
- }
- }
+ self.insert(specifier, is_dynamic).await?;
if !self.graph.roots.contains(specifier) {
self.graph.roots.push(specifier.clone());
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -1862,6 +1861,53 @@ impl GraphBuilder {
Ok(())
}
+ /// Analyze compiler options, identifying any specifiers that need to be
+ /// resolved and added to the graph.
+ pub async fn analyze_compiler_options(
+ &mut self,
+ maybe_compiler_options: &Option<HashMap<String, Value>>,
+ ) -> Result<(), AnyError> {
+ if let Some(user_config) = maybe_compiler_options {
+ if let Some(value) = user_config.get("types") {
+ let types: Vec<String> = serde_json::from_value(value.clone())?;
+ for specifier in types {
+ if let Ok(specifier) = resolve_url_or_path(&specifier) {
+ self.insert(&specifier, false).await?;
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+
+ /// Analyze a config file, identifying any specifiers that need to be resolved
+ /// and added to the graph.
+ pub async fn analyze_config_file(
+ &mut self,
+ maybe_config_file: &Option<ConfigFile>,
+ ) -> Result<(), AnyError> {
+ if let Some(config_file) = maybe_config_file {
+ let referrer = ModuleSpecifier::from_file_path(&config_file.path)
+ .map_err(|_| {
+ anyhow!("Could not convert file path: \"{:?}\"", config_file.path)
+ })?;
+ if let Some(compiler_options) = &config_file.json.compiler_options {
+ let compiler_options: CompilerOptions =
+ serde_json::from_value(compiler_options.clone())?;
+ if let Some(types) = compiler_options.types {
+ for specifier in types {
+ if let Ok(specifier) =
+ resolve_import(&specifier, &referrer.to_string())
+ {
+ self.insert(&specifier, false).await?;
+ }
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+
/// Request a module to be fetched from the handler and queue up its future
/// to be awaited to be resolved.
fn fetch(
diff --git a/cli/module_graph.rs b/cli/module_graph.rs
--- a/cli/module_graph.rs
+++ b/cli/module_graph.rs
@@ -1882,6 +1928,37 @@ impl GraphBuilder {
}
}
+ /// An internal method that fetches the specifier and recursively fetches any
+ /// of the dependencies, adding them to the graph.
+ async fn insert(
+ &mut self,
+ specifier: &ModuleSpecifier,
+ is_dynamic: bool,
+ ) -> Result<(), AnyError> {
+ self.fetch(specifier, &None, is_dynamic);
+
+ loop {
+ match self.pending.next().await {
+ Some(Err((specifier, err))) => {
+ self
+ .graph
+ .modules
+ .insert(specifier, ModuleSlot::Err(Arc::new(err)));
+ }
+ Some(Ok(cached_module)) => {
+ let is_root = &cached_module.specifier == specifier;
+ self.visit(cached_module, is_root, is_dynamic)?;
+ }
+ _ => {}
+ }
+ if self.pending.is_empty() {
+ break;
+ }
+ }
+
+ Ok(())
+ }
+
/// Visit a module that has been fetched, hydrating the module, analyzing its
/// dependencies if required, fetching those dependencies, and inserting the
/// module into the graph.
diff --git a/cli/ops/runtime_compiler.rs b/cli/ops/runtime_compiler.rs
--- a/cli/ops/runtime_compiler.rs
+++ b/cli/ops/runtime_compiler.rs
@@ -108,6 +108,9 @@ async fn op_emit(
&root_specifier
))
})?;
+ builder
+ .analyze_compiler_options(&args.compiler_options)
+ .await?;
let bundle_type = match args.bundle {
Some(RuntimeBundleType::Module) => BundleType::Module,
Some(RuntimeBundleType::Classic) => BundleType::Classic,
diff --git a/cli/program_state.rs b/cli/program_state.rs
--- a/cli/program_state.rs
+++ b/cli/program_state.rs
@@ -174,6 +174,7 @@ impl ProgramState {
for specifier in specifiers {
builder.add(&specifier, false).await?;
}
+ builder.analyze_config_file(&self.maybe_config_file).await?;
let mut graph = builder.get_graph();
let debug = self.flags.log_level == Some(log::Level::Debug);
diff --git a/cli/program_state.rs b/cli/program_state.rs
--- a/cli/program_state.rs
+++ b/cli/program_state.rs
@@ -248,6 +249,7 @@ impl ProgramState {
let mut builder =
GraphBuilder::new(handler, maybe_import_map, self.lockfile.clone());
builder.add(&specifier, is_dynamic).await?;
+ builder.analyze_config_file(&self.maybe_config_file).await?;
let mut graph = builder.get_graph();
let debug = self.flags.log_level == Some(log::Level::Debug);
let maybe_config_file = self.maybe_config_file.clone();
diff --git a/cli/tools/doc.rs b/cli/tools/doc.rs
--- a/cli/tools/doc.rs
+++ b/cli/tools/doc.rs
@@ -125,6 +125,9 @@ pub async fn print_docs(
program_state.lockfile.clone(),
);
builder.add(&root_specifier, false).await?;
+ builder
+ .analyze_config_file(&program_state.maybe_config_file)
+ .await?;
let graph = builder.get_graph();
let doc_parser = doc::DocParser::new(Box::new(graph), private);
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -12,6 +12,7 @@ use deno_core::error::AnyError;
use deno_core::error::Context;
use deno_core::op_sync;
use deno_core::resolve_url_or_path;
+use deno_core::serde::de;
use deno_core::serde::Deserialize;
use deno_core::serde::Serialize;
use deno_core::serde_json;
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -179,6 +180,7 @@ pub struct Request {
pub debug: bool,
pub graph: Arc<Mutex<Graph>>,
pub hash_data: Vec<Vec<u8>>,
+ pub maybe_config_specifier: Option<ModuleSpecifier>,
pub maybe_tsbuildinfo: Option<String>,
/// A vector of strings that represent the root/entry point modules for the
/// program.
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -203,6 +205,7 @@ struct State {
hash_data: Vec<Vec<u8>>,
emitted_files: Vec<EmittedFile>,
graph: Arc<Mutex<Graph>>,
+ maybe_config_specifier: Option<ModuleSpecifier>,
maybe_tsbuildinfo: Option<String>,
maybe_response: Option<RespondArgs>,
root_map: HashMap<String, ModuleSpecifier>,
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -212,6 +215,7 @@ impl State {
pub fn new(
graph: Arc<Mutex<Graph>>,
hash_data: Vec<Vec<u8>>,
+ maybe_config_specifier: Option<ModuleSpecifier>,
maybe_tsbuildinfo: Option<String>,
root_map: HashMap<String, ModuleSpecifier>,
data_url_map: HashMap<String, ModuleSpecifier>,
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -221,6 +225,7 @@ impl State {
hash_data,
emitted_files: Default::default(),
graph,
+ maybe_config_specifier,
maybe_tsbuildinfo,
maybe_response: None,
root_map,
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -228,9 +233,16 @@ impl State {
}
}
-fn op<F>(op_fn: F) -> Box<OpFn>
+fn normalize_specifier(specifier: &str) -> Result<ModuleSpecifier, AnyError> {
+ resolve_url_or_path(&specifier.replace(".d.ts.d.ts", ".d.ts"))
+ .map_err(|err| err.into())
+}
+
+fn op<F, V, R>(op_fn: F) -> Box<OpFn>
where
- F: Fn(&mut State, Value) -> Result<Value, AnyError> + 'static,
+ F: Fn(&mut State, V) -> Result<R, AnyError> + 'static,
+ V: de::DeserializeOwned,
+ R: Serialize + 'static,
{
op_sync(move |s, args, _: ()| {
let state = s.borrow_mut::<State>();
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -255,6 +267,15 @@ fn op_create_hash(state: &mut State, args: Value) -> Result<Value, AnyError> {
Ok(json!({ "hash": hash }))
}
+fn op_cwd(state: &mut State, _args: Value) -> Result<String, AnyError> {
+ if let Some(config_specifier) = &state.maybe_config_specifier {
+ let cwd = config_specifier.join("./")?;
+ Ok(cwd.to_string())
+ } else {
+ Ok("cache:///".to_string())
+ }
+}
+
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct EmitArgs {
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -285,7 +306,7 @@ fn op_emit(state: &mut State, args: Value) -> Result<Value, AnyError> {
} else if let Some(remapped_specifier) = state.root_map.get(s) {
remapped_specifier.clone()
} else {
- resolve_url_or_path(s).unwrap()
+ normalize_specifier(s).unwrap()
}
})
.collect();
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -300,6 +321,25 @@ fn op_emit(state: &mut State, args: Value) -> Result<Value, AnyError> {
Ok(json!(true))
}
+#[derive(Debug, Deserialize)]
+struct ExistsArgs {
+ /// The fully qualified specifier that should be loaded.
+ specifier: String,
+}
+
+fn op_exists(state: &mut State, args: ExistsArgs) -> Result<bool, AnyError> {
+ if let Ok(specifier) = normalize_specifier(&args.specifier) {
+ if specifier.scheme() == "asset" || specifier.scheme() == "data" {
+ Ok(true)
+ } else {
+ let graph = state.graph.lock().unwrap();
+ Ok(graph.contains(&specifier))
+ }
+ } else {
+ Ok(false)
+ }
+}
+
#[derive(Debug, Deserialize)]
struct LoadArgs {
/// The fully qualified specifier that should be loaded.
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -309,7 +349,7 @@ struct LoadArgs {
fn op_load(state: &mut State, args: Value) -> Result<Value, AnyError> {
let v: LoadArgs = serde_json::from_value(args)
.context("Invalid request from JavaScript for \"op_load\".")?;
- let specifier = resolve_url_or_path(&v.specifier)
+ let specifier = normalize_specifier(&v.specifier)
.context("Error converting a string module specifier for \"op_load\".")?;
let mut hash: Option<String> = None;
let mut media_type = MediaType::Unknown;
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -372,7 +412,7 @@ fn op_resolve(state: &mut State, args: Value) -> Result<Value, AnyError> {
} else if let Some(remapped_base) = state.root_map.get(&v.base) {
remapped_base.clone()
} else {
- resolve_url_or_path(&v.base).context(
+ normalize_specifier(&v.base).context(
"Error converting a string module specifier for \"op_resolve\".",
)?
};
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -490,14 +530,17 @@ pub fn exec(request: Request) -> Result<Response, AnyError> {
op_state.put(State::new(
request.graph.clone(),
request.hash_data.clone(),
+ request.maybe_config_specifier.clone(),
request.maybe_tsbuildinfo.clone(),
root_map,
data_url_map,
));
}
+ runtime.register_op("op_cwd", op(op_cwd));
runtime.register_op("op_create_hash", op(op_create_hash));
runtime.register_op("op_emit", op(op_emit));
+ runtime.register_op("op_exists", op(op_exists));
runtime.register_op("op_load", op(op_load));
runtime.register_op("op_resolve", op(op_resolve));
runtime.register_op("op_respond", op(op_respond));
diff --git a/cli/tsc/99_main_compiler.js b/cli/tsc/99_main_compiler.js
--- a/cli/tsc/99_main_compiler.js
+++ b/cli/tsc/99_main_compiler.js
@@ -19,6 +19,9 @@ delete Object.prototype.__proto__;
let logDebug = false;
let logSource = "JS";
+ /** @type {string=} */
+ let cwd;
+
// The map from the normalized specifier to the original.
// TypeScript normalizes the specifier in its internal processing,
// but the original specifier is needed when looking up the source from the runtime.
diff --git a/cli/tsc/99_main_compiler.js b/cli/tsc/99_main_compiler.js
--- a/cli/tsc/99_main_compiler.js
+++ b/cli/tsc/99_main_compiler.js
@@ -130,7 +133,6 @@ delete Object.prototype.__proto__;
// analysis in Rust operates on fully resolved URLs,
// it makes sense to use the same scheme here.
const ASSETS = "asset:///";
- const CACHE = "cache:///";
/** Diagnostics that are intentionally ignored when compiling TypeScript in
* Deno, as they provide misleading or incorrect information. */
diff --git a/cli/tsc/99_main_compiler.js b/cli/tsc/99_main_compiler.js
--- a/cli/tsc/99_main_compiler.js
+++ b/cli/tsc/99_main_compiler.js
@@ -251,9 +253,10 @@ delete Object.prototype.__proto__;
*
* @type {ts.CompilerHost & ts.LanguageServiceHost} */
const host = {
- fileExists(fileName) {
- debug(`host.fileExists("${fileName}")`);
- return false;
+ fileExists(specifier) {
+ debug(`host.fileExists("${specifier}")`);
+ specifier = normalizedToOriginalMap.get(specifier) ?? specifier;
+ return core.opSync("op_exists", { specifier });
},
readFile(specifier) {
debug(`host.readFile("${specifier}")`);
diff --git a/cli/tsc/99_main_compiler.js b/cli/tsc/99_main_compiler.js
--- a/cli/tsc/99_main_compiler.js
+++ b/cli/tsc/99_main_compiler.js
@@ -317,7 +320,8 @@ delete Object.prototype.__proto__;
);
},
getCurrentDirectory() {
- return CACHE;
+ debug(`host.getCurrentDirectory()`);
+ return cwd ?? core.opSync("op_cwd", null);
},
getCanonicalFileName(fileName) {
return fileName;
diff --git a/cli/tsc/99_main_compiler.js b/cli/tsc/99_main_compiler.js
--- a/cli/tsc/99_main_compiler.js
+++ b/cli/tsc/99_main_compiler.js
@@ -787,12 +791,13 @@ delete Object.prototype.__proto__;
}
}
- /** @param {{ debug: boolean; }} init */
- function serverInit({ debug: debugFlag }) {
+ /** @param {{ debug: boolean; rootUri?: string; }} init */
+ function serverInit({ debug: debugFlag, rootUri }) {
if (hasStarted) {
throw new Error("The language server has already been initialized.");
}
hasStarted = true;
+ cwd = rootUri;
languageService = ts.createLanguageService(host);
setLogDebug(debugFlag, "TSLS");
debug("serverInit()");
diff --git a/docs/typescript/configuration.md b/docs/typescript/configuration.md
--- a/docs/typescript/configuration.md
+++ b/docs/typescript/configuration.md
@@ -197,3 +197,10 @@ The biggest "danger" when doing something like this, is that the type checking
is significantly looser, and there is no way to validate that you are doing
sufficient and effective feature detection in your code, which may lead to what
could be trivial errors becoming runtime errors.
+
+### Using the "types" property
+
+The `"types"` property in `"compilerOptions"` can be used to specify arbitrary
+type definitions to include when type checking a programme. For more information
+on this see
+[Using ambient or global types](./types#using-ambient-or-global-types).
diff --git a/docs/typescript/types.md b/docs/typescript/types.md
--- a/docs/typescript/types.md
+++ b/docs/typescript/types.md
@@ -101,6 +101,67 @@ When seeing this header, Deno would attempt to retrieve
`https://example.com/coolLib.d.ts` and use that when type checking the original
module.
+### Using ambient or global types
+
+Overall it is better to use module/UMD type definitions with Deno, where a
+module expressly imports the types it depends upon. Modular type definitions can
+express
+[augmentation of the global scope](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html)
+via the `declare global` in the type definition. For example:
+
+```ts
+declare global {
+ var AGlobalString: string;
+}
+```
+
+This would make `AGlobalString` available in the global namespace when importing
+the type definition.
+
+In some cases though, when leveraging other existing type libraries, it may not
+be possible to leverage modular type definitions. Therefore there are ways to
+include arbitrary type definitions when type checking programmes.
+
+#### Using a triple-slash directive
+
+This option couples the type definitions to the code itself. By adding a
+triple-slash `types` directive near the type of a module, type checking the file
+will include the type definition. For example:
+
+```ts
+/// <reference types="./types.d.ts" />
+```
+
+The specifier provided is resolved just like any other specifier in Deno, which
+means it requires an extension, and is relative to the module referencing it. It
+can be a fully qualified URL as well:
+
+```ts
+/// <reference types="https://deno.land/x/pkg@1.0.0/types.d.ts" />
+```
+
+#### Using a `tsconfig.json` file
+
+Another option is to use a `tsconfig.json` file that is configured to include
+the type definitions, by supplying a `"types"` value to the `"compilerOptions"`.
+For example:
+
+```json
+{
+ "compilerOptions": {
+ "types": [
+ "./types.d.ts",
+ "https://deno.land/x/pkg@1.0.0/types.d.ts",
+ "/Users/me/pkg/types.d.ts"
+ ]
+ }
+}
+```
+
+Like the triple-slash reference above, the specifier supplied in the `"types"`
+array will be resolved like other specifiers in Deno. In the case of relative
+specifiers, it will be resolved relative to the path to the `tsconfig.json`.
+
### Type Checking Web Workers
When Deno loads a TypeScript module in a web worker, it will automatically type
| 10,999 | diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs
--- a/cli/lsp/tsc.rs
+++ b/cli/lsp/tsc.rs
@@ -2632,7 +2719,9 @@ mod tests {
let temp_dir = TempDir::new().expect("could not create temp dir");
let location = temp_dir.path().join("deps");
let state_snapshot = mock_state_snapshot(sources, &location);
- let mut runtime = start(debug).expect("could not start server");
+ let mut runtime = load().expect("could not start server");
+ start(&mut runtime, debug, &state_snapshot)
+ .expect("could not start server");
let ts_config = TsConfig::new(config);
assert_eq!(
request(
diff --git a/cli/main.rs b/cli/main.rs
--- a/cli/main.rs
+++ b/cli/main.rs
@@ -1031,6 +1040,9 @@ async fn test_command(
for specifier in test_modules.iter() {
builder.add(specifier, false).await?;
}
+ builder
+ .analyze_config_file(&program_state.maybe_config_file)
+ .await?;
let graph = builder.get_graph();
for specifier in doc_modules {
diff --git a/cli/tests/compiler_api_test.ts b/cli/tests/compiler_api_test.ts
--- a/cli/tests/compiler_api_test.ts
+++ b/cli/tests/compiler_api_test.ts
@@ -92,6 +92,56 @@ Deno.test({
},
});
+Deno.test({
+ name: "Deno.emit() - type references can be loaded",
+ async fn() {
+ const { diagnostics, files, ignoredOptions, stats } = await Deno.emit(
+ "file:///a.ts",
+ {
+ sources: {
+ "file:///a.ts": `/// <reference types="./b.d.ts" />
+ const b = new B();
+ console.log(b.b);`,
+ "file:///b.d.ts": `declare class B {
+ b: string;
+ }`,
+ },
+ },
+ );
+ assertEquals(diagnostics.length, 0);
+ assert(!ignoredOptions);
+ assertEquals(stats.length, 12);
+ const keys = Object.keys(files).sort();
+ assertEquals(keys, ["file:///a.ts.js", "file:///a.ts.js.map"]);
+ },
+});
+
+Deno.test({
+ name: "Deno.emit() - compilerOptions.types",
+ async fn() {
+ const { diagnostics, files, ignoredOptions, stats } = await Deno.emit(
+ "file:///a.ts",
+ {
+ compilerOptions: {
+ types: ["file:///b.d.ts"],
+ },
+ sources: {
+ "file:///a.ts": `const b = new B();
+ console.log(b.b);`,
+ "file:///b.d.ts": `declare class B {
+ b: string;
+ }`,
+ },
+ },
+ );
+ assertEquals(diagnostics.length, 0);
+ assert(!ignoredOptions);
+ assertEquals(stats.length, 12);
+ const keys = Object.keys(files).sort();
+ assertEquals(keys, ["file:///a.ts.js", "file:///a.ts.js.map"]);
+ },
+});
+
Deno.test({
name: "Deno.emit() - import maps",
async fn() {
diff --git /dev/null b/cli/tests/config_types.ts
new file mode 100644
--- /dev/null
+++ b/cli/tests/config_types.ts
@@ -0,0 +1,1 @@
+console.log(globalThis.a);
diff --git /dev/null b/cli/tests/config_types.ts.out
new file mode 100644
--- /dev/null
+++ b/cli/tests/config_types.ts.out
@@ -0,0 +1,1 @@
+undefined
diff --git /dev/null b/cli/tests/config_types.tsconfig.json
new file mode 100644
--- /dev/null
+++ b/cli/tests/config_types.tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "compilerOptions": {
+ "types": [
+ "./subdir/types.d.ts"
+ ]
+ }
+}
diff --git /dev/null b/cli/tests/config_types_remote.tsconfig.json
new file mode 100644
--- /dev/null
+++ b/cli/tests/config_types_remote.tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "compilerOptions": {
+ "types": [
+ "http://localhost:4545/cli/tests/subdir/types.d.ts"
+ ]
+ }
+}
diff --git a/cli/tests/integration_tests.rs b/cli/tests/integration_tests.rs
--- a/cli/tests/integration_tests.rs
+++ b/cli/tests/integration_tests.rs
@@ -3349,7 +3349,19 @@ console.log("finish");
output: "config.ts.out",
});
- itest!(emtpy_typescript {
+ itest!(config_types {
+ args:
+ "run --reload --quiet --config config_types.tsconfig.json config_types.ts",
+ output: "config_types.ts.out",
+ });
+
+ itest!(config_types_remote {
+ http_server: true,
+ args: "run --reload --quiet --config config_types_remote.tsconfig.json config_types.ts",
+ output: "config_types.ts.out",
+ });
+
+ itest!(empty_typescript {
args: "run --reload subdir/empty.ts",
output_str: Some("Check file:[WILDCARD]tests/subdir/empty.ts\n"),
});
diff --git a/cli/tests/integration_tests.rs b/cli/tests/integration_tests.rs
--- a/cli/tests/integration_tests.rs
+++ b/cli/tests/integration_tests.rs
@@ -4051,6 +4063,17 @@ console.log("finish");
output: "redirect_cache.out",
});
+ itest!(reference_types {
+ args: "run --reload --quiet reference_types.ts",
+ output: "reference_types.ts.out",
+ });
+
+ itest!(references_types_remote {
+ http_server: true,
+ args: "run --reload --quiet reference_types_remote.ts",
+ output: "reference_types_remote.ts.out",
+ });
+
itest!(deno_doc_types_header_direct {
args: "doc --reload http://127.0.0.1:4545/xTypeScriptTypes.js",
output: "doc/types_header.out",
diff --git a/cli/tests/integration_tests_lsp.rs b/cli/tests/integration_tests_lsp.rs
--- a/cli/tests/integration_tests_lsp.rs
+++ b/cli/tests/integration_tests_lsp.rs
@@ -21,6 +21,12 @@ fn load_fixture(path: &str) -> Value {
serde_json::from_str(&fixture_str).unwrap()
}
+fn load_fixture_str(path: &str) -> String {
+ let fixtures_path = root_path().join("cli/tests/lsp");
+ let path = fixtures_path.join(path);
+ fs::read_to_string(path).unwrap()
+}
+
fn init(init_path: &str) -> LspClient {
let deno_exe = deno_exe_path();
let mut client = LspClient::new(&deno_exe).unwrap();
diff --git a/cli/tests/integration_tests_lsp.rs b/cli/tests/integration_tests_lsp.rs
--- a/cli/tests/integration_tests_lsp.rs
+++ b/cli/tests/integration_tests_lsp.rs
@@ -122,6 +128,85 @@ fn lsp_init_tsconfig() {
shutdown(&mut client);
}
+#[test]
+fn lsp_tsconfig_types() {
+ let mut params: lsp::InitializeParams =
+ serde_json::from_value(load_fixture("initialize_params.json")).unwrap();
+ let temp_dir = TempDir::new().expect("could not create temp dir");
+ let tsconfig =
+ serde_json::to_vec_pretty(&load_fixture("types.tsconfig.json")).unwrap();
+ fs::write(temp_dir.path().join("types.tsconfig.json"), tsconfig).unwrap();
+ let a_dts = load_fixture_str("a.d.ts");
+ fs::write(temp_dir.path().join("a.d.ts"), a_dts).unwrap();
+
+ params.root_uri = Some(Url::from_file_path(temp_dir.path()).unwrap());
+ if let Some(Value::Object(mut map)) = params.initialization_options {
+ map.insert("config".to_string(), json!("./types.tsconfig.json"));
+ params.initialization_options = Some(Value::Object(map));
+ }
+
+ let deno_exe = deno_exe_path();
+ let mut client = LspClient::new(&deno_exe).unwrap();
+ client
+ .write_request::<_, _, Value>("initialize", params)
+ .unwrap();
+
+ client.write_notification("initialized", json!({})).unwrap();
+
+ let diagnostics = did_open(
+ &mut client,
+ json!({
+ "textDocument": {
+ "uri": Url::from_file_path(temp_dir.path().join("test.ts")).unwrap(),
+ "languageId": "typescript",
+ "version": 1,
+ "text": "console.log(a);\n"
+ }
+ }),
+ );
+
+ let diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics);
+ assert_eq!(diagnostics.count(), 0);
+
+ shutdown(&mut client);
+}
+
+#[test]
+fn lsp_triple_slash_types() {
+ let mut params: lsp::InitializeParams =
+ serde_json::from_value(load_fixture("initialize_params.json")).unwrap();
+ let temp_dir = TempDir::new().expect("could not create temp dir");
+ let a_dts = load_fixture_str("a.d.ts");
+ fs::write(temp_dir.path().join("a.d.ts"), a_dts).unwrap();
+
+ params.root_uri = Some(Url::from_file_path(temp_dir.path()).unwrap());
+
+ let deno_exe = deno_exe_path();
+ let mut client = LspClient::new(&deno_exe).unwrap();
+ client
+ .write_request::<_, _, Value>("initialize", params)
+ .unwrap();
+
+ client.write_notification("initialized", json!({})).unwrap();
+
+ let diagnostics = did_open(
+ &mut client,
+ json!({
+ "textDocument": {
+ "uri": Url::from_file_path(temp_dir.path().join("test.ts")).unwrap(),
+ "languageId": "typescript",
+ "version": 1,
+ "text": "/// <reference types=\"./a.d.ts\" />\n\nconsole.log(a);\n"
+ }
+ }),
+ );
+
+ let diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics);
+ assert_eq!(diagnostics.count(), 0);
+
+ shutdown(&mut client);
+}
+
#[test]
fn lsp_hover() {
let mut client = init("initialize_params.json");
diff --git /dev/null b/cli/tests/lsp/a.d.ts
new file mode 100644
--- /dev/null
+++ b/cli/tests/lsp/a.d.ts
@@ -0,0 +1,1 @@
+declare var a: string;
diff --git /dev/null b/cli/tests/lsp/b.d.ts
new file mode 100644
--- /dev/null
+++ b/cli/tests/lsp/b.d.ts
@@ -0,0 +1,1 @@
+declare var b: string;
diff --git /dev/null b/cli/tests/lsp/types.tsconfig.json
new file mode 100644
--- /dev/null
+++ b/cli/tests/lsp/types.tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "compilerOptions": {
+ "types": [
+ "./a.d.ts"
+ ]
+ }
+}
diff --git /dev/null b/cli/tests/reference_types.ts
new file mode 100644
--- /dev/null
+++ b/cli/tests/reference_types.ts
@@ -0,0 +1,3 @@
+/// <reference types="./subdir/types.d.ts" />
+
+console.log(globalThis.a);
diff --git /dev/null b/cli/tests/reference_types.ts.out
new file mode 100644
--- /dev/null
+++ b/cli/tests/reference_types.ts.out
@@ -0,0 +1,1 @@
+undefined
diff --git /dev/null b/cli/tests/reference_types_remote.ts
new file mode 100644
--- /dev/null
+++ b/cli/tests/reference_types_remote.ts
@@ -0,0 +1,3 @@
+/// <reference types="http://localhost:4545/cli/tests/subdir/types.d.ts" />
+
+console.log(globalThis.a);
diff --git /dev/null b/cli/tests/reference_types_remote.ts.out
new file mode 100644
--- /dev/null
+++ b/cli/tests/reference_types_remote.ts.out
@@ -0,0 +1,1 @@
+undefined
diff --git /dev/null b/cli/tests/subdir/types.d.ts
new file mode 100644
--- /dev/null
+++ b/cli/tests/subdir/types.d.ts
@@ -0,0 +1,1 @@
+declare var a: string;
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -573,6 +616,7 @@ mod tests {
State::new(
graph,
hash_data,
+ None,
maybe_tsbuildinfo,
HashMap::new(),
HashMap::new(),
diff --git a/cli/tsc.rs b/cli/tsc.rs
--- a/cli/tsc.rs
+++ b/cli/tsc.rs
@@ -614,6 +658,7 @@ mod tests {
debug: false,
graph,
hash_data,
+ maybe_config_specifier: None,
maybe_tsbuildinfo: None,
root_names: vec![(specifier.clone(), MediaType::TypeScript)],
};
| 67c9937e6658c2be9b54cd95132a1055756e433b |
This can actually be reproduced by just running the expression `Event.prototype` (issue is that it inspects getters that will throw an error). Will fix it soon. | 2021-06-15T19:50:21Z | denoland/deno | denoland__deno-10979 | [
"9880"
] | 5bf4a88aa494073abd57838a60e9140062ac4e41 | `Object.defineProperty` on `Event` prototype panics in repl
running `Object.defineProperty(Event.prototype, 0, {})` in repl will panic with `thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', cli/tools/repl.rs:564:49`
| 1.11 | diff --git a/extensions/web/02_event.js b/extensions/web/02_event.js
--- a/extensions/web/02_event.js
+++ b/extensions/web/02_event.js
@@ -144,7 +144,7 @@
}
[Symbol.for("Deno.customInspect")](inspect) {
- return buildCustomInspectOutput(this, EVENT_PROPS, inspect);
+ return inspect(buildFilteredPropertyInspectObject(this, EVENT_PROPS));
}
get type() {
diff --git a/extensions/web/02_event.js b/extensions/web/02_event.js
--- a/extensions/web/02_event.js
+++ b/extensions/web/02_event.js
@@ -395,9 +395,41 @@
}
}
- function buildCustomInspectOutput(object, keys, inspect) {
- const inspectObject = Object.fromEntries(keys.map((k) => [k, object[k]]));
- return `${object.constructor.name} ${inspect(inspectObject)}`;
+ function buildFilteredPropertyInspectObject(object, keys) {
+ // forward the subset of properties from `object` without evaluating
+ // as evaluation could lead to an error, which is better handled
+ // in the inspect code
+ return new Proxy({}, {
+ get(_target, key) {
+ if (key === Symbol.toStringTag) {
+ return object.constructor?.name;
+ } else if (keys.includes(key)) {
+ return Reflect.get(object, key);
+ } else {
+ return undefined;
+ }
+ },
+ getOwnPropertyDescriptor(_target, key) {
+ if (!keys.includes(key)) {
+ return undefined;
+ }
+
+ return Reflect.getOwnPropertyDescriptor(object, key) ??
+ (object.prototype &&
+ Reflect.getOwnPropertyDescriptor(object.prototype, key)) ??
+ {
+ configurable: true,
+ enumerable: true,
+ value: object[key],
+ };
+ },
+ has(_target, key) {
+ return keys.includes(key);
+ },
+ ownKeys() {
+ return keys;
+ },
+ });
}
function defineEnumerableProps(
diff --git a/extensions/web/02_event.js b/extensions/web/02_event.js
--- a/extensions/web/02_event.js
+++ b/extensions/web/02_event.js
@@ -1053,14 +1085,14 @@
}
[Symbol.for("Deno.customInspect")](inspect) {
- return buildCustomInspectOutput(this, [
+ return inspect(buildFilteredPropertyInspectObject(this, [
...EVENT_PROPS,
"message",
"filename",
"lineno",
"colno",
"error",
- ], inspect);
+ ]));
}
}
diff --git a/extensions/web/02_event.js b/extensions/web/02_event.js
--- a/extensions/web/02_event.js
+++ b/extensions/web/02_event.js
@@ -1107,12 +1139,12 @@
}
[Symbol.for("Deno.customInspect")](inspect) {
- return buildCustomInspectOutput(this, [
+ return inspect(buildFilteredPropertyInspectObject(this, [
...EVENT_PROPS,
"wasClean",
"code",
"reason",
- ], inspect);
+ ]));
}
}
diff --git a/extensions/web/02_event.js b/extensions/web/02_event.js
--- a/extensions/web/02_event.js
+++ b/extensions/web/02_event.js
@@ -1134,12 +1166,12 @@
}
[Symbol.for("Deno.customInspect")](inspect) {
- return buildCustomInspectOutput(this, [
+ return inspect(buildFilteredPropertyInspectObject(this, [
...EVENT_PROPS,
"data",
"origin",
"lastEventId",
- ], inspect);
+ ]));
}
}
diff --git a/extensions/web/02_event.js b/extensions/web/02_event.js
--- a/extensions/web/02_event.js
+++ b/extensions/web/02_event.js
@@ -1164,10 +1196,10 @@
}
[Symbol.for("Deno.customInspect")](inspect) {
- return buildCustomInspectOutput(this, [
+ return inspect(buildFilteredPropertyInspectObject(this, [
...EVENT_PROPS,
"detail",
- ], inspect);
+ ]));
}
}
diff --git a/extensions/web/02_event.js b/extensions/web/02_event.js
--- a/extensions/web/02_event.js
+++ b/extensions/web/02_event.js
@@ -1187,12 +1219,12 @@
}
[Symbol.for("Deno.customInspect")](inspect) {
- return buildCustomInspectOutput(this, [
+ return inspect(buildFilteredPropertyInspectObject(this, [
...EVENT_PROPS,
"lengthComputable",
"loaded",
"total",
- ], inspect);
+ ]));
}
}
| 10,979 | diff --git a/cli/tests/unit/event_test.ts b/cli/tests/unit/event_test.ts
--- a/cli/tests/unit/event_test.ts
+++ b/cli/tests/unit/event_test.ts
@@ -1,5 +1,10 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
-import { assert, assertEquals, unitTest } from "./test_util.ts";
+import {
+ assert,
+ assertEquals,
+ assertStringIncludes,
+ unitTest,
+} from "./test_util.ts";
unitTest(function eventInitializedWithType(): void {
const type = "click";
diff --git a/cli/tests/unit/event_test.ts b/cli/tests/unit/event_test.ts
--- a/cli/tests/unit/event_test.ts
+++ b/cli/tests/unit/event_test.ts
@@ -127,3 +132,30 @@ unitTest(function eventInspectOutput(): void {
assertEquals(Deno.inspect(event), outputProvider(event));
}
});
+
+unitTest(function inspectEvent(): void {
+ // has a customInspect implementation that previously would throw on a getter
+ assertEquals(
+ Deno.inspect(Event.prototype),
+ `Event {
+ bubbles: [Getter/Setter],
+ cancelable: [Getter/Setter],
+ composed: [Getter/Setter],
+ currentTarget: [Getter/Setter],
+ defaultPrevented: [Getter/Setter],
+ eventPhase: [Getter/Setter],
+ srcElement: [Getter/Setter],
+ target: [Getter/Setter],
+ returnValue: [Getter/Setter],
+ timeStamp: [Getter/Setter],
+ type: [Getter/Setter]
+}`,
+ );
+
+ // ensure this still works
+ assertStringIncludes(
+ Deno.inspect(new Event("test")),
+ // check a substring because one property is a timestamp
+ `Event {\n bubbles: false,\n cancelable: false,`,
+ );
+});
| 67c9937e6658c2be9b54cd95132a1055756e433b |
2021-06-15T18:44:55Z | denoland/deno | denoland__deno-10977 | [
"10975"
] | 0c0058f1181d1fd6590f760a0375ead706043d32 | Inspecting a proxy with `showProxy: false` incorrectly inspects the target
The code in 02_console.js does not seem to properly inspect any object that's a proxy when `showProxy: false` (default) and instead inspects the target of the proxy.
For example:
```ts
const myObject = new Proxy({}, {
get(_target, key) {
if (key === Symbol.toStringTag) {
return "MyProxy";
} else {
return 5;
}
},
getOwnPropertyDescriptor() {
return {
enumerable: true,
configurable: true,
value: 5,
};
},
ownKeys() {
return ["prop1", "prop2"];
},
});
console.log(Object.keys(myObject)); // [ "prop1", "prop2" ]
console.log(Deno.inspect(myObject)); // {}
```
Expected output:
```
MyProxy { prop1: 5, prop2: 5 }
```
Actual output:
```
{}
```
Affects Deno 1.11.0.
| 1.11 | diff --git a/extensions/console/02_console.js b/extensions/console/02_console.js
--- a/extensions/console/02_console.js
+++ b/extensions/console/02_console.js
@@ -429,10 +429,8 @@
inspectOptions,
) {
const proxyDetails = core.getProxyDetails(value);
- if (proxyDetails != null) {
- return inspectOptions.showProxy
- ? inspectProxy(proxyDetails, level, inspectOptions)
- : inspectValue(proxyDetails[0], level, inspectOptions);
+ if (proxyDetails != null && inspectOptions.showProxy) {
+ return inspectProxy(proxyDetails, level, inspectOptions);
}
const green = maybeColor(colors.green, inspectOptions);
| 10,977 | diff --git a/cli/tests/unit/console_test.ts b/cli/tests/unit/console_test.ts
--- a/cli/tests/unit/console_test.ts
+++ b/cli/tests/unit/console_test.ts
@@ -1737,16 +1737,40 @@ unitTest(function inspectIterableLimit(): void {
unitTest(function inspectProxy(): void {
assertEquals(
stripColor(Deno.inspect(
- new Proxy([1, 2, 3], { get(): void {} }),
+ new Proxy([1, 2, 3], {}),
)),
"[ 1, 2, 3 ]",
);
assertEquals(
stripColor(Deno.inspect(
- new Proxy({ key: "value" }, { get(): void {} }),
+ new Proxy({ key: "value" }, {}),
)),
`{ key: "value" }`,
);
+ assertEquals(
+ stripColor(Deno.inspect(
+ new Proxy({}, {
+ get(_target, key) {
+ if (key === Symbol.toStringTag) {
+ return "MyProxy";
+ } else {
+ return 5;
+ }
+ },
+ getOwnPropertyDescriptor() {
+ return {
+ enumerable: true,
+ configurable: true,
+ value: 5,
+ };
+ },
+ ownKeys() {
+ return ["prop1", "prop2"];
+ },
+ }),
+ )),
+ `MyProxy { prop1: 5, prop2: 5 }`,
+ );
assertEquals(
stripColor(Deno.inspect(
new Proxy([1, 2, 3], { get(): void {} }),
| 67c9937e6658c2be9b54cd95132a1055756e433b | |
2021-06-14T18:36:23Z | denoland/deno | denoland__deno-10963 | [
"10962"
] | c651757fb7a1f6cec94c3857973d3316129bccb8 | REPL does not complete declarations
For example...
```
> const myVar = {};
undefined
> my<TAB>
```
...does nothing.
I'm not sure if this is a bug or a feature that just hasn't been done so please categorize accordingly.
| 1.11 | diff --git a/cli/tools/repl.rs b/cli/tools/repl.rs
--- a/cli/tools/repl.rs
+++ b/cli/tools/repl.rs
@@ -50,47 +50,34 @@ impl EditorHelper {
self.message_tx.send((method.to_string(), params))?;
self.response_rx.recv()?
}
-}
-
-fn is_word_boundary(c: char) -> bool {
- if c == '.' {
- false
- } else {
- char::is_ascii_whitespace(&c) || char::is_ascii_punctuation(&c)
- }
-}
-
-impl Completer for EditorHelper {
- type Candidate = String;
- fn complete(
- &self,
- line: &str,
- pos: usize,
- _ctx: &Context<'_>,
- ) -> Result<(usize, Vec<String>), ReadlineError> {
- let start = line[..pos].rfind(is_word_boundary).map_or_else(|| 0, |i| i);
- let end = line[pos..]
- .rfind(is_word_boundary)
- .map_or_else(|| pos, |i| pos + i);
-
- let word = &line[start..end];
- let word = word.strip_prefix(is_word_boundary).unwrap_or(word);
- let word = word.strip_suffix(is_word_boundary).unwrap_or(word);
-
- let fallback = format!(".{}", word);
+ fn get_global_lexical_scope_names(&self) -> Vec<String> {
+ let evaluate_response = self
+ .post_message(
+ "Runtime.globalLexicalScopeNames",
+ Some(json!({
+ "executionContextId": self.context_id,
+ })),
+ )
+ .unwrap();
- let (prefix, suffix) = match word.rfind('.') {
- Some(index) => word.split_at(index),
- None => ("globalThis", fallback.as_str()),
- };
+ evaluate_response
+ .get("names")
+ .unwrap()
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|n| n.as_str().unwrap().to_string())
+ .collect()
+ }
+ fn get_expression_property_names(&self, expr: &str) -> Vec<String> {
let evaluate_response = self
.post_message(
"Runtime.evaluate",
Some(json!({
"contextId": self.context_id,
- "expression": prefix,
+ "expression": expr,
"throwOnSideEffect": true,
"timeout": 200,
})),
diff --git a/cli/tools/repl.rs b/cli/tools/repl.rs
--- a/cli/tools/repl.rs
+++ b/cli/tools/repl.rs
@@ -98,8 +85,7 @@ impl Completer for EditorHelper {
.unwrap();
if evaluate_response.get("exceptionDetails").is_some() {
- let candidates = Vec::new();
- return Ok((pos, candidates));
+ return Vec::new();
}
if let Some(result) = evaluate_response.get("result") {
diff --git a/cli/tools/repl.rs b/cli/tools/repl.rs
--- a/cli/tools/repl.rs
+++ b/cli/tools/repl.rs
@@ -113,32 +99,83 @@ impl Completer for EditorHelper {
if let Ok(get_properties_response) = get_properties_response {
if let Some(result) = get_properties_response.get("result") {
- let candidates = result
+ let property_names = result
.as_array()
.unwrap()
.iter()
- .filter_map(|r| {
- let name = r.get("name").unwrap().as_str().unwrap().to_string();
-
- if name.starts_with("Symbol(") {
- return None;
- }
-
- if name.starts_with(&suffix[1..]) {
- return Some(name);
- }
-
- None
- })
+ .map(|r| r.get("name").unwrap().as_str().unwrap().to_string())
.collect();
- return Ok((pos - (suffix.len() - 1), candidates));
+ return property_names;
}
}
}
}
- Ok((pos, Vec::new()))
+ Vec::new()
+ }
+}
+
+fn is_word_boundary(c: char) -> bool {
+ if c == '.' {
+ false
+ } else {
+ char::is_ascii_whitespace(&c) || char::is_ascii_punctuation(&c)
+ }
+}
+
+fn get_expr_from_line_at_pos(line: &str, cursor_pos: usize) -> &str {
+ let start = line[..cursor_pos]
+ .rfind(is_word_boundary)
+ .map_or_else(|| 0, |i| i);
+ let end = line[cursor_pos..]
+ .rfind(is_word_boundary)
+ .map_or_else(|| cursor_pos, |i| cursor_pos + i);
+
+ let word = &line[start..end];
+ let word = word.strip_prefix(is_word_boundary).unwrap_or(word);
+ let word = word.strip_suffix(is_word_boundary).unwrap_or(word);
+
+ word
+}
+
+impl Completer for EditorHelper {
+ type Candidate = String;
+
+ fn complete(
+ &self,
+ line: &str,
+ pos: usize,
+ _ctx: &Context<'_>,
+ ) -> Result<(usize, Vec<String>), ReadlineError> {
+ let expr = get_expr_from_line_at_pos(line, pos);
+
+ // check if the expression is in the form `obj.prop`
+ if let Some(index) = expr.rfind('.') {
+ let sub_expr = &expr[..index];
+ let prop_name = &expr[index + 1..];
+ let candidates = self
+ .get_expression_property_names(sub_expr)
+ .into_iter()
+ .filter(|n| !n.starts_with("Symbol(") && n.starts_with(prop_name))
+ .collect();
+
+ Ok((pos - prop_name.len(), candidates))
+ } else {
+ // combine results of declarations and globalThis properties
+ let mut candidates = self
+ .get_expression_property_names("globalThis")
+ .into_iter()
+ .chain(self.get_global_lexical_scope_names())
+ .filter(|n| n.starts_with(expr))
+ .collect::<Vec<_>>();
+
+ // sort and remove duplicates
+ candidates.sort();
+ candidates.dedup(); // make sure to sort first
+
+ Ok((pos - expr.len(), candidates))
+ }
}
}
| 10,963 | diff --git a/cli/tests/integration_tests.rs b/cli/tests/integration_tests.rs
--- a/cli/tests/integration_tests.rs
+++ b/cli/tests/integration_tests.rs
@@ -2085,6 +2085,35 @@ mod integration {
}
}
+ #[cfg(unix)]
+ #[test]
+ fn pty_complete_declarations() {
+ use std::io::Read;
+ use util::pty::fork::*;
+ let deno_exe = util::deno_exe_path();
+ let fork = Fork::from_ptmx().unwrap();
+ if let Ok(mut master) = fork.is_parent() {
+ master.write_all(b"class MyClass {}\n").unwrap();
+ master.write_all(b"My\t\n").unwrap();
+ master.write_all(b"let myVar;\n").unwrap();
+ master.write_all(b"myV\t\n").unwrap();
+ master.write_all(b"close();\n").unwrap();
+
+ let mut output = String::new();
+ master.read_to_string(&mut output).unwrap();
+
+ assert!(output.contains("> MyClass"));
+ assert!(output.contains("> myVar"));
+
+ fork.wait().unwrap();
+ } else {
+ std::env::set_var("NO_COLOR", "1");
+ let err = exec::Command::new(deno_exe).arg("repl").exec();
+ println!("err {}", err);
+ unreachable!()
+ }
+ }
+
#[cfg(unix)]
#[test]
fn pty_ignore_symbols() {
| 67c9937e6658c2be9b54cd95132a1055756e433b | |
Yeah - I only added `harnessStatus` a few days ago. It should be taken into account when reporting status too.
The easiest and likely most logical fix would be to rethrow the error return value of `Deno.core.evalContext` in parent scope. This should cause the process to exit with a non 0 status code. This would align with one of Deno's goals: to always die on uncaught errors. | 2021-06-11T13:51:31Z | denoland/deno | denoland__deno-10932 | [
"10930"
] | 1a92c39b77c46170a2135994359962034c8131c5 | The WPT test runner doesn't detect exceptions thrown outside tests
While trying a few things related to workers on WPT (see #10903), I noticed that the `.any.worker.html` tests were reported as succeeding, even though they were using classic workers, which Deno doesn't support. This seems to be because the main script in `.any.worker.html` files is:
```js
fetch_tests_from_worker(new Worker("/workers/Worker-base64.any.worker.js"));
```
Since the worker constructor doesn't run inside a test, the exception isn't handled by the WPT test harness, but is returned as part of the return value of `Deno.core.evalContext` in the test runner, which the test runner then ignores. This results in no tests or exceptions being detected by the test harness, and so the `add_completion_callback` callbacks don't run. In order to have the WPT test harness react to the exception, it should be wrapped inside an `error` event to be fired at the global scope, [like HTML does](https://html.spec.whatwg.org/#report-the-error).
Fixing this is not enough, however, since the `reportVariation` function in the test runner expects that the only runner failures that can occur are failures where the runner process fails with a non-zero error status – but an exception thrown outside a test, if reported with an `error` event, will ultimately result in the `add_completion_callback` being called, and so the runner process will exit with zero status code, even though `result.harnessStatus.status !== 0`. So `reportVariation` would also need to be tweaked to account for this case.
| 1.11 | diff --git a/tools/wpt/runner.ts b/tools/wpt/runner.ts
--- a/tools/wpt/runner.ts
+++ b/tools/wpt/runner.ts
@@ -168,9 +168,13 @@ async function generateBundle(location: URL): Promise<string> {
}
}
- return scriptContents.map(([url, contents]) =>
- `Deno.core.evalContext(${JSON.stringify(contents)}, ${
- JSON.stringify(url)
- });`
- ).join("\n");
+ return scriptContents.map(([url, contents]) => `
+(function() {
+ const [_,err] = Deno.core.evalContext(${JSON.stringify(contents)}, ${
+ JSON.stringify(url)
+ });
+ if (err !== null) {
+ throw err?.thrown;
+ }
+})();`).join("\n");
}
| 10,932 | diff --git a/test_util/wpt b/test_util/wpt
--- a/test_util/wpt
+++ b/test_util/wpt
@@ -1,1 +1,1 @@
-Subproject commit e664d8ccb0a25bb28b3e027bce6817e9108845e0
+Subproject commit 146f12e8df2cac6b1e60152145124a81dad60d38
diff --git a/tools/wpt/testharnessreport.js b/tools/wpt/testharnessreport.js
--- a/tools/wpt/testharnessreport.js
+++ b/tools/wpt/testharnessreport.js
@@ -18,5 +18,5 @@ window.add_completion_callback((_tests, harnessStatus) => {
while (bytesWritten < data.byteLength) {
bytesWritten += Deno.stderr.writeSync(data.subarray(bytesWritten));
}
- Deno.exit(0);
+ Deno.exit(harnessStatus.status === 0 ? 0 : 1);
});
| 67c9937e6658c2be9b54cd95132a1055756e433b |
I will open a PR that removes all code related to plugins in the near future so we could evaluate its impact on the codebase.
PR for reference https://github.com/denoland/deno/pull/8493
What does "Rust scaffold" means? Like a template for developing plugins or a library that can be used to integrate with Deno?
Native plugins should fill the gap for modules that are not worth implementing into the deno core or are not general enough. While they haven't seen widespread adoption there is interest for such a feature and I think the reason is simply their immature state. I think replacing native plugins with ffi might be a better solution but I understand the issue remains the same.
The main (and my main) interest in deno plugins seems to come from the potential of using plugins for gui (webview/webgpu + windowing) and other os interactions (autopilot). The current pr for webgpu (#7977) could potentially fill this gap but would also require implementing a cross-platform windowing solution into deno core (unless the problem of windowing is passed to the user which in turn would require native plugins) which is far from ideal.
While I do understand every point made to why Deno should not have native plugins, it is worth saying that having plugins is more beneficial than we may think. Plugins offer a way to provide stability for applications with high requirements, one enterprise example would be: High-computing related tasks, these would be handled in the Rust side but call from a JS environment.
On this specific article: https://dev.to/andreespirela/how-mandarine-framework-could-surpass-nestjs-13c3 and this article: https://www.mandarinets.org/posts/making-mandarine-the-most-stable-framework-with-rust- I talk about leveraging JS with Rust and the benefits for it.
- More stability since it allows you to bring stable functionalities from stable environments such as a database driver written in Rust into a no so-stable environment such as Deno Database drivers.
- As mentioned by @eliassjogreen , Plugins allow you to bring modules that would not be so straightforward to write in JS, even when Deno would provide the necessary.
The way I see plugins is not really as an unstable piece of Deno, let me **elaborate** on this. It is very true that some parts of the plugin ecosystem are unstable and worth mentioning such as #7990 , although, plugins are different in its own nature, they provide a bridge between Rust (or c++) and JS which means, it is ok for them to have their own set of rules in order to work, for example: You cannot use Deno's main thread in your rust plugins, I think if there is documentation that states such issue as part of plugin's nature, and we keep treating Deno's plugins as something "Do at your own risk" , then we should not have an issue.
It is true having plugins break some concepts like the security Deno provides from inside, although, this kind of things should be on the user's side to decide: Not all users will use plugins nor Not all users will write modules in Rust, a good example of this would be a Deno Postgres driver & a Rust Postgres Driver used in Deno, where of course, the main recommendation is to use the Deno one.
I believe there is so much more to be discussed, but I am on the side that we should keep the plugins as they are right now, improve what we can improve, fix what we can fix. But removing the functionality will affect the ecosystem in terms of bringing modules that need some sort of system programming, and it will **also** affect the community in terms of leveraging enterprise needs with a typescript/JS ecosystem.
I think maybe replacing the `--allow-plugin` flag with `--allow-all` would make it clearer that security cannot be guaranteed when using plugins.
There are indeed many problems with plug-in features at present, but these problems stem from actual use cases. Unless we are clear that we must not plug-in functionality (obviously not) instead of temporarily stranding, we should still keep it. More use cases and discoveries The problem prompts us to design better solutions, not to stop everyone from exploring. I think it is better to keep the status quo.
Is it clear that the existence of the current and flawed plugin interface hinders development and refactors on the rest of the codebase?
If so, I think that should be elaborated and clarified as the primary motivation of this issue since people are broadly defending the benefit of plugins or are otherwise confused as to why we would resort to removal. In particular, the security problem already exists with the subprocess interface and will likely exist for any good plugin interface.
If not, I agree with @manyuanrong.
I am not really in favor of removing it... why we do not just let it in the experimental phase in order to gain knowledge about how to secure it? Using an experimental flag like 'unsafe' is perfect for that!
I don't think that it should be removed. But leave it in with a warning that it probably will get a rewrite later on that might break the plugins developed for deno. But I think we should leave the feature implemented to see if people will develop plugins.
Maybe in half a year we can go back to this topic and see if people made plugins and if we want to remove plugin support or if we want to rewrite this feature
@MierenManz not even in the case that it’s not used it should be removed. The thing with plugins is that it isn’t a feature that many people will use as many people **are not** actively looking for rust solutions to be used in JS. The vast majority of people using NodeJS or Deno look for the creation of solution in JS/TS, Plugins are really something more advanced that we shouldn’t expect a great amount of people to work on them, but those who do should be enough.
The issue of removing plugins is really something beyond “how many people are using them right now”, personally I believe plugins should be **kept** by all means because of the very fact they are the only way to provide a bridge between a system language and JS, this is extremely important for enterprise needs and corporate adoption of Deno as calling Rust from the JS side allows a limitless amount of solutions just like high performance calculations for example (and that’s just a very vague example on how analytics company can use JS and Rust).
Levereging Rust and JS is possibly the most important “bridge” when it comes to enterprise adoption (opinion)
@andreespirela I agree with you on the part where we should keep it in, but only if it doesn't hurt performance and that we are sure alot of good development will happen in the plugin section of deno before Deno 2.0
Like Bartlomieju said:
> I propose to completely remove native plugin interface in the next
minor release, revisit this topic after Deno 2.0, and in the meantime encourage
users to use WASM modules instead. I am aware that some of use cases for
plugins are not achievable using WASM
this would be a pretty good sollution I think. WASM can be compiled from alot of languages and even TS.
So it might be worth it to remove the rust plugins(for now) and maybe use WASM plugins and then revisit this topic later on
I agree and encourage the use of `wasm` in all scenarios that can be solved by `wasm`, or devote energy to the improvement of `wasi`. This can circumvent most of the current plugin problems. But for some scenes of native interaction, plugin mechanism is necessary, such as [deno-ffi](https://github.com/manyuanrong/deno-ffi) that I am currently improving, and deno-webview implemented by @eliassjogreen . deno-webview has a lot of attention, indicating that everyone has a lot of demand for this kind of scene.
So, my suggestion is to keep the current plugin feature
I think that the plugin interface is not good, but the idea of plugins should exist. The lack of docs helps that.
We should think about a model that integrates better with Deno interface, especially around security. I don't have a concrete API in my head, but I imagine two things can be added to improve security with plugins:
1. Allowing to load only specific plugins, by filename and maybe even cryptographically secure hash. This allows you to be sure that only trusted plugins will be loaded.
2. Provide an API in the Rust side that allows a plugin to create custom permissions, and query existing permissions. So for example, a database driver allows you to specify `--allow-dbs=my_db` permission. This will require interpreting `--allow-` flags dynamically, and also change the (unstable) permissions API.
This way, plugins will integrate better with the security model of Deno leading to more adoption, IMO.
I would go slightly further than @eliassjogreen suggests and make it `--allow-unsafe`
@tracker1 Makes less sense to make a new `--allow-unsafe` permission for it instead of using `--allow-all` as someone could simply invoke a new process with whatever permissions wanted through the plugin making it less clear that the user is by extension allowing everything.
@eliassjogreen I get it... just thinking that if "all" previously didn't allow plugins, that "unsafe" is a better meta, as you are allowing unsafe code, not just all security permissions.... `--allow-unsafe` === `--allow-all | --allow-plugins`.
There's no reason to tie allowing use of env/read/write etc from js (or read/write) when using a plugin. It's true that you are trusting the plugin (or maybe several specific plugins that could even be listed in the cli argument), and that plugins do sidestep the cli permissions, but using a plugin shouldn't mean you have to --allow-all for js.
> users to use WASM modules instead. I am aware that some of use cases for
> plugins are not achievable using WASM
Wasm itself operates at the exact same privilege level as JavaScript; WebAssembly is *weak*. There is absolutely **nothing** that Wasm can do, that JS can't do slower.
Asm.js is a **subset** of JS, Wasm supersedes it. Native plugins and FFI calls are only necessary for what *cannot* be done in JS. To compare native code to Wasm is to compare apples to oranges, they are very different; any comparison between the two makes no sense in this context.
Security-wise, using solely JS, I could check `Deno.build`, then `fetch` an appropriate binary from the web, and execute it using `Deno.run` or something, how are plugins less safe than that?
Regardless, I support the issue that has been raised, to remove "unstable native plugins," is a good thing, as long as it paves the way to introducing "stable native plugins."
The only way that I could get behind something like this is if there was some way to get stuff like webview to work with whatever will replace it. I don't know how one would want to go about doing something like that though. If some sort of alternative could be provided via WASM/WASI, that would be fine, however I am unsure.
I would like to note that the `Deno.run` command (under `--allow-run`) combined with a websocket is a way around this without too much trouble. (Just tedium.) I think that plugins can be placed under the same permission since they are essentially the same thing just easier to work with.
It may be worth creating a example table of what different permissions can expose security wise. Possibly also a tool for that.
WASM is not a solution to providing extensions that are platform specific.
GPU is getting fairly portable that wasm could nearly support it...
This is my project; and other than being used for work I do, and I'm not myself a corporation or corporate entitie, and most of this is solutions seeking problems; part of it overlaps internals, but has merits in being implemented as a homogenous external API.
https://github.com/d3x0r/sack.vfs
A feature a simple webserver script could do is just memory map a file, and pass that file to a socket handle without the buffer ever being copied to the JS heap (much less into a wasm heap).
There are a handful of OS specific extensions that Node (Deno?) can't really provide, as they are outside of the model it's based on... my system is purely interrupt driven; the platform abstraction I'm providing... which rather than being a OS itself just homogenouizes existing OS into a common experience for the developer.
It has a GUI too.. which is really just building with different npm scripts instead of a default; there's a separate branch for the GUI, but mostly it's just modifications to the docs to itself, and a change of the default build command.
I do rely on things like the OpenSSL library provided with Node - which is potentially a set of symbols you'll need to expose to plugins, but mostly it's bindings from C to V8, with a super thing C++ layer; although the C does just compile as C++....
I'm not a noob developer, but I really couldn't manage to figure how to get cargo linker to just build my C++ DLL and load it.
The entry point for plugins, for node, has been updated, because 'worker-threads' have their own isolates and contexts, so plugins need to be aware, so they can init for each context/isolate; I don't know if Deno even supports JS threads; because processes is THE model, right?
I'd be in favor of ripping it out, figuring out what it was providing, and reimplementing in a better way.
I'm not super knowledgeable on this topic, but for anyone that finds this thread I believe it is relevant to know that there have been significant updates to the plugin api recently:
* https://deno.com/blog/v1.10#updated-plugin-api
* https://github.com/denoland/deno/pull/9800
* https://github.com/denoland/deno/pull/10427
I was initially worried when I found this thread, but I looks like things are on the up and up for the plugins api. Though don't take my word for it. I would love it if someone on the Deno team could summarize the current state of the plugins api. | 2021-06-09T15:26:24Z | denoland/deno | denoland__deno-10908 | [
"8490"
] | 622f9c688902411e347038e82fc5c354c60678cf | Remove unstable native plugins
Opening this issue to start discussion on potential removal of native plugins.
Native plugins are an unstable feature that hasn't seen much adoption; partially
due to lack of documentation and partially due to shortcomings of plugin interface.
Currently there's one major problem that prevents from using plugins in the same
way to use "ops" in Deno; namely code loaded from dynamic library cannot obtain
proper handle to current thread which renders Tokio unusable from the plugins (#7990).
Moreover the plugin system adds some complexity to Deno's op interface and brakes
the security promises of Deno (because we can't control what's going on in dynamically
loaded library).
Therefore I propose to completely remove native plugin interface in the next
minor release, revisit this topic after Deno 2.0, and in the meantime encourage
users to use WASM modules instead. I am aware that some of use cases for
plugins are not achievable using WASM (eg. using webview), but for that
purpose we're working on providing Rust "scaffold" for projects that want to
integrate deeply with Deno.
Related issues and PRs:
- #7990
- #7030
- #5478
- #4222
- #3598
- #7031
- #5721
CC @ry @piscisaureus @eliassjogreen @manyuanrong @andreespirela
| 1.11 | diff --git a/runtime/js/40_plugins.js /dev/null
--- a/runtime/js/40_plugins.js
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
-"use strict";
-
-((window) => {
- const core = window.Deno.core;
-
- function openPlugin(filename) {
- const rid = core.opSync("op_open_plugin", filename);
- core.syncOpsCache();
- return rid;
- }
-
- window.__bootstrap.plugins = {
- openPlugin,
- };
-})(this);
diff --git a/runtime/js/90_deno_ns.js b/runtime/js/90_deno_ns.js
--- a/runtime/js/90_deno_ns.js
+++ b/runtime/js/90_deno_ns.js
@@ -109,7 +109,6 @@
Signal: __bootstrap.signals.Signal,
SignalStream: __bootstrap.signals.SignalStream,
emit: __bootstrap.compilerApi.emit,
- openPlugin: __bootstrap.plugins.openPlugin,
kill: __bootstrap.process.kill,
setRaw: __bootstrap.tty.setRaw,
consoleSize: __bootstrap.tty.consoleSize,
diff --git a/runtime/ops/mod.rs b/runtime/ops/mod.rs
--- a/runtime/ops/mod.rs
+++ b/runtime/ops/mod.rs
@@ -5,7 +5,6 @@ pub mod fs_events;
pub mod io;
pub mod os;
pub mod permissions;
-pub mod plugin;
pub mod process;
pub mod runtime;
pub mod signal;
diff --git a/runtime/ops/plugin.rs /dev/null
--- a/runtime/ops/plugin.rs
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
-use crate::permissions::Permissions;
-use deno_core::error::AnyError;
-use deno_core::op_sync;
-use deno_core::Extension;
-use deno_core::OpState;
-use deno_core::Resource;
-use deno_core::ResourceId;
-use dlopen::symbor::Library;
-use log::debug;
-use std::borrow::Cow;
-use std::mem;
-use std::path::PathBuf;
-use std::rc::Rc;
-
-/// A default `init` function for plugins which mimics the way the internal
-/// extensions are initalized. Plugins currently do not support all extension
-/// features and are most likely not going to in the future. Currently only
-/// `init_state` and `init_ops` are supported while `init_middleware` and `init_js`
-/// are not. Currently the `PluginResource` does not support being closed due to
-/// certain risks in unloading the dynamic library without unloading dependent
-/// functions and resources.
-pub type InitFn = fn() -> Extension;
-
-pub fn init() -> Extension {
- Extension::builder()
- .ops(vec![("op_open_plugin", op_sync(op_open_plugin))])
- .build()
-}
-
-pub fn op_open_plugin(
- state: &mut OpState,
- filename: String,
- _: (),
-) -> Result<ResourceId, AnyError> {
- let filename = PathBuf::from(&filename);
-
- super::check_unstable(state, "Deno.openPlugin");
- let permissions = state.borrow_mut::<Permissions>();
- permissions.plugin.check()?;
-
- debug!("Loading Plugin: {:#?}", filename);
- let plugin_lib = Library::open(filename).map(Rc::new)?;
- let plugin_resource = PluginResource::new(&plugin_lib);
-
- // Forgets the plugin_lib value to prevent segfaults when the process exits
- mem::forget(plugin_lib);
-
- let init = *unsafe { plugin_resource.0.symbol::<InitFn>("init") }?;
- let rid = state.resource_table.add(plugin_resource);
- let mut extension = init();
-
- if !extension.init_js().is_empty() {
- panic!("Plugins do not support loading js");
- }
-
- if extension.init_middleware().is_some() {
- panic!("Plugins do not support middleware");
- }
-
- extension.init_state(state)?;
- let ops = extension.init_ops().unwrap_or_default();
- for (name, opfn) in ops {
- state.op_table.register_op(name, opfn);
- }
-
- Ok(rid)
-}
-
-struct PluginResource(Rc<Library>);
-
-impl Resource for PluginResource {
- fn name(&self) -> Cow<str> {
- "plugin".into()
- }
-
- fn close(self: Rc<Self>) {
- unimplemented!();
- }
-}
-
-impl PluginResource {
- fn new(lib: &Rc<Library>) -> Self {
- Self(lib.clone())
- }
-}
diff --git a/runtime/web_worker.rs b/runtime/web_worker.rs
--- a/runtime/web_worker.rs
+++ b/runtime/web_worker.rs
@@ -333,7 +333,6 @@ impl WebWorker {
deno_net::init::<Permissions>(options.unstable),
ops::os::init(),
ops::permissions::init(),
- ops::plugin::init(),
ops::process::init(),
ops::signal::init(),
ops::tty::init(),
diff --git a/runtime/worker.rs b/runtime/worker.rs
--- a/runtime/worker.rs
+++ b/runtime/worker.rs
@@ -124,7 +124,6 @@ impl MainWorker {
deno_net::init::<Permissions>(options.unstable),
ops::os::init(),
ops::permissions::init(),
- ops::plugin::init(),
ops::process::init(),
ops::signal::init(),
ops::tty::init(),
| 10,908 | diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3550,16 +3550,6 @@ dependencies = [
"winapi-util",
]
-[[package]]
-name = "test_plugin"
-version = "0.0.1"
-dependencies = [
- "deno_core",
- "futures",
- "serde",
- "test_util",
-]
-
[[package]]
name = "test_util"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,7 +6,6 @@ members = [
"cli",
"core",
"runtime",
- "test_plugin",
"test_util",
"extensions/broadcast_channel",
"extensions/console",
diff --git a/cli/dts/lib.deno.unstable.d.ts b/cli/dts/lib.deno.unstable.d.ts
--- a/cli/dts/lib.deno.unstable.d.ts
+++ b/cli/dts/lib.deno.unstable.d.ts
@@ -129,37 +129,6 @@ declare namespace Deno {
speed: number | undefined;
}
- /** **UNSTABLE**: new API, yet to be vetted.
- *
- * Open and initialize a plugin.
- *
- * ```ts
- * import { assert } from "https://deno.land/std/testing/asserts.ts";
- * const rid = Deno.openPlugin("./path/to/some/plugin.so");
- *
- * // The Deno.core namespace is needed to interact with plugins, but this is
- * // internal so we use ts-ignore to skip type checking these calls.
- * // @ts-ignore
- * const { op_test_sync, op_test_async } = Deno.core.ops();
- *
- * assert(op_test_sync);
- * assert(op_test_async);
- *
- * // @ts-ignore
- * const result = Deno.core.opSync("op_test_sync");
- *
- * // @ts-ignore
- * const result = await Deno.core.opAsync("op_test_sync");
- * ```
- *
- * Requires `allow-plugin` permission.
- *
- * The plugin system is not stable and will change in the future, hence the
- * lack of docs. For now take a look at the example
- * https://github.com/denoland/deno/tree/main/test_plugin
- */
- export function openPlugin(filename: string): number;
-
/** The log category for a diagnostic message. */
export enum DiagnosticCategory {
Warning = 0,
diff --git a/cli/tests/integration/lsp_tests.rs b/cli/tests/integration/lsp_tests.rs
--- a/cli/tests/integration/lsp_tests.rs
+++ b/cli/tests/integration/lsp_tests.rs
@@ -470,7 +470,7 @@ fn lsp_hover_unstable_enabled() {
"uri": "file:///a/file.ts",
"languageId": "typescript",
"version": 1,
- "text": "console.log(Deno.openPlugin);\n"
+ "text": "console.log(Deno.ppid);\n"
}
}),
);
diff --git a/cli/tests/integration/lsp_tests.rs b/cli/tests/integration/lsp_tests.rs
--- a/cli/tests/integration/lsp_tests.rs
+++ b/cli/tests/integration/lsp_tests.rs
@@ -495,9 +495,9 @@ fn lsp_hover_unstable_enabled() {
"contents":[
{
"language":"typescript",
- "value":"function Deno.openPlugin(filename: string): number"
+ "value":"const Deno.ppid: number"
},
- "**UNSTABLE**: new API, yet to be vetted.\n\nOpen and initialize a plugin.\n\n```ts\nimport { assert } from \"https://deno.land/std/testing/asserts.ts\";\nconst rid = Deno.openPlugin(\"./path/to/some/plugin.so\");\n\n// The Deno.core namespace is needed to interact with plugins, but this is\n// internal so we use ts-ignore to skip type checking these calls.\n// @ts-ignore\nconst { op_test_sync, op_test_async } = Deno.core.ops();\n\nassert(op_test_sync);\nassert(op_test_async);\n\n// @ts-ignore\nconst result = Deno.core.opSync(\"op_test_sync\");\n\n// @ts-ignore\nconst result = await Deno.core.opAsync(\"op_test_sync\");\n```\n\nRequires `allow-plugin` permission.\n\nThe plugin system is not stable and will change in the future, hence the\nlack of docs. For now take a look at the example\nhttps://github.com/denoland/deno/tree/main/test_plugin"
+ "The pid of the current process's parent."
],
"range":{
"start":{
diff --git a/cli/tests/integration/lsp_tests.rs b/cli/tests/integration/lsp_tests.rs
--- a/cli/tests/integration/lsp_tests.rs
+++ b/cli/tests/integration/lsp_tests.rs
@@ -506,7 +506,7 @@ fn lsp_hover_unstable_enabled() {
},
"end":{
"line":0,
- "character":27
+ "character":21
}
}
}))
diff --git a/test_plugin/Cargo.toml /dev/null
--- a/test_plugin/Cargo.toml
+++ /dev/null
@@ -1,19 +0,0 @@
-# Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
-
-[package]
-name = "test_plugin"
-version = "0.0.1"
-authors = ["the deno authors"]
-edition = "2018"
-publish = false
-
-[lib]
-crate-type = ["cdylib"]
-
-[dependencies]
-deno_core = { path = "../core" }
-futures = "0.3.15"
-serde = "1"
-
-[dev-dependencies]
-test_util = { path = "../test_util" }
diff --git a/test_plugin/README.md /dev/null
--- a/test_plugin/README.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# `test_plugin` crate
-
-## To run this test manually
-
-```
-cd test_plugin
-
-../target/debug/deno run --unstable --allow-plugin tests/test.js debug
-```
diff --git a/test_plugin/src/lib.rs /dev/null
--- a/test_plugin/src/lib.rs
+++ /dev/null
@@ -1,114 +0,0 @@
-// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
-
-use std::borrow::Cow;
-use std::cell::RefCell;
-use std::rc::Rc;
-
-use deno_core::error::bad_resource_id;
-use deno_core::error::AnyError;
-use deno_core::op_async;
-use deno_core::op_sync;
-use deno_core::Extension;
-use deno_core::OpState;
-use deno_core::Resource;
-use deno_core::ResourceId;
-use deno_core::ZeroCopyBuf;
-use serde::Deserialize;
-
-#[no_mangle]
-pub fn init() -> Extension {
- Extension::builder()
- .ops(vec![
- ("op_test_sync", op_sync(op_test_sync)),
- ("op_test_async", op_async(op_test_async)),
- (
- "op_test_resource_table_add",
- op_sync(op_test_resource_table_add),
- ),
- (
- "op_test_resource_table_get",
- op_sync(op_test_resource_table_get),
- ),
- ])
- .build()
-}
-
-#[derive(Debug, Deserialize)]
-struct TestArgs {
- val: String,
-}
-
-fn op_test_sync(
- _state: &mut OpState,
- args: TestArgs,
- zero_copy: Option<ZeroCopyBuf>,
-) -> Result<String, AnyError> {
- println!("Hello from sync plugin op.");
-
- println!("args: {:?}", args);
-
- if let Some(buf) = zero_copy {
- let buf_str = std::str::from_utf8(&buf[..])?;
- println!("zero_copy: {}", buf_str);
- }
-
- Ok("test".to_string())
-}
-
-async fn op_test_async(
- _state: Rc<RefCell<OpState>>,
- args: TestArgs,
- zero_copy: Option<ZeroCopyBuf>,
-) -> Result<String, AnyError> {
- println!("Hello from async plugin op.");
-
- println!("args: {:?}", args);
-
- if let Some(buf) = zero_copy {
- let buf_str = std::str::from_utf8(&buf[..])?;
- println!("zero_copy: {}", buf_str);
- }
-
- let (tx, rx) = futures::channel::oneshot::channel::<Result<(), ()>>();
- std::thread::spawn(move || {
- std::thread::sleep(std::time::Duration::from_secs(1));
- tx.send(Ok(())).unwrap();
- });
- assert!(rx.await.is_ok());
-
- Ok("test".to_string())
-}
-
-struct TestResource(String);
-impl Resource for TestResource {
- fn name(&self) -> Cow<str> {
- "TestResource".into()
- }
-}
-
-fn op_test_resource_table_add(
- state: &mut OpState,
- text: String,
- _: (),
-) -> Result<u32, AnyError> {
- println!("Hello from resource_table.add plugin op.");
-
- Ok(state.resource_table.add(TestResource(text)))
-}
-
-fn op_test_resource_table_get(
- state: &mut OpState,
- rid: ResourceId,
- _: (),
-) -> Result<String, AnyError> {
- println!("Hello from resource_table.get plugin op.");
-
- Ok(
- state
- .resource_table
- .get::<TestResource>(rid)
- .ok_or_else(bad_resource_id)?
- .0
- .clone(),
- )
-}
diff --git a/test_plugin/tests/integration_tests.rs /dev/null
--- a/test_plugin/tests/integration_tests.rs
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
-
-use std::process::Command;
-use test_util::deno_cmd;
-
-#[cfg(debug_assertions)]
-const BUILD_VARIANT: &str = "debug";
-
-#[cfg(not(debug_assertions))]
-const BUILD_VARIANT: &str = "release";
-
-#[test]
-fn basic() {
- let mut build_plugin_base = Command::new("cargo");
- let mut build_plugin =
- build_plugin_base.arg("build").arg("-p").arg("test_plugin");
- if BUILD_VARIANT == "release" {
- build_plugin = build_plugin.arg("--release");
- }
- let build_plugin_output = build_plugin.output().unwrap();
- assert!(build_plugin_output.status.success());
- let output = deno_cmd()
- .arg("run")
- .arg("--allow-plugin")
- .arg("--unstable")
- .arg("tests/test.js")
- .arg(BUILD_VARIANT)
- .output()
- .unwrap();
- let stdout = std::str::from_utf8(&output.stdout).unwrap();
- let stderr = std::str::from_utf8(&output.stderr).unwrap();
- if !output.status.success() {
- println!("stdout {}", stdout);
- println!("stderr {}", stderr);
- }
- println!("{:?}", output.status);
- assert!(output.status.success());
- let expected = "\
- Plugin rid: 3\n\
- Hello from sync plugin op.\n\
- args: TestArgs { val: \"1\" }\n\
- zero_copy: test\n\
- op_test_sync returned: test\n\
- Hello from async plugin op.\n\
- args: TestArgs { val: \"1\" }\n\
- zero_copy: 123\n\
- op_test_async returned: test\n\
- Hello from resource_table.add plugin op.\n\
- TestResource rid: 4\n\
- Hello from resource_table.get plugin op.\n\
- TestResource get value: hello plugin!\n\
- Hello from sync plugin op.\n\
- args: TestArgs { val: \"1\" }\n\
- Ops completed count is correct!\n\
- Ops dispatched count is correct!\n";
- assert_eq!(stdout, expected);
- assert_eq!(stderr, "");
-}
diff --git a/test_plugin/tests/test.js /dev/null
--- a/test_plugin/tests/test.js
+++ /dev/null
@@ -1,135 +0,0 @@
-// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
-// deno-lint-ignore-file
-
-const filenameBase = "test_plugin";
-
-let filenameSuffix = ".so";
-let filenamePrefix = "lib";
-
-if (Deno.build.os === "windows") {
- filenameSuffix = ".dll";
- filenamePrefix = "";
-} else if (Deno.build.os === "darwin") {
- filenameSuffix = ".dylib";
-}
-
-const filename = `../target/${
- Deno.args[0]
-}/${filenamePrefix}${filenameBase}${filenameSuffix}`;
-
-const resourcesPre = Deno.resources();
-
-const pluginRid = Deno.openPlugin(filename);
-console.log(`Plugin rid: ${pluginRid}`);
-
-const {
- op_test_sync,
- op_test_async,
- op_test_resource_table_add,
- op_test_resource_table_get,
-} = Deno.core.ops();
-
-if (
- op_test_sync === null ||
- op_test_async === null ||
- op_test_resource_table_add === null ||
- op_test_resource_table_get === null
-) {
- throw new Error("Not all expected ops were registered");
-}
-
-function runTestSync() {
- const result = Deno.core.opSync(
- "op_test_sync",
- { val: "1" },
- new Uint8Array([116, 101, 115, 116]),
- );
-
- console.log(`op_test_sync returned: ${result}`);
-
- if (result !== "test") {
- throw new Error("op_test_sync returned an unexpected value!");
- }
-}
-
-async function runTestAsync() {
- const promise = Deno.core.opAsync(
- "op_test_async",
- { val: "1" },
- new Uint8Array([49, 50, 51]),
- );
-
- if (!(promise instanceof Promise)) {
- throw new Error("Expected promise!");
- }
-
- const result = await promise;
- console.log(`op_test_async returned: ${result}`);
-
- if (result !== "test") {
- throw new Error("op_test_async promise resolved to an unexpected value!");
- }
-}
-
-function runTestResourceTable() {
- const expect = "hello plugin!";
-
- const testRid = Deno.core.opSync("op_test_resource_table_add", expect);
- console.log(`TestResource rid: ${testRid}`);
-
- if (testRid === null || Deno.resources()[testRid] !== "TestResource") {
- throw new Error("TestResource was not found!");
- }
-
- const testValue = Deno.core.opSync("op_test_resource_table_get", testRid);
- console.log(`TestResource get value: ${testValue}`);
-
- if (testValue !== expect) {
- throw new Error("Did not get correct resource value!");
- }
-
- Deno.close(testRid);
-}
-
-function runTestOpCount() {
- const start = Deno.metrics();
-
- Deno.core.opSync("op_test_sync", { val: "1" });
-
- const end = Deno.metrics();
-
- if (end.opsCompleted - start.opsCompleted !== 1) {
- throw new Error("The opsCompleted metric is not correct!");
- }
- console.log("Ops completed count is correct!");
-
- if (end.opsDispatched - start.opsDispatched !== 1) {
- throw new Error("The opsDispatched metric is not correct!");
- }
- console.log("Ops dispatched count is correct!");
-}
-
-function runTestPluginClose() {
- // Closing does not yet work
- Deno.close(pluginRid);
-
- const resourcesPost = Deno.resources();
-
- const preStr = JSON.stringify(resourcesPre, null, 2);
- const postStr = JSON.stringify(resourcesPost, null, 2);
- if (preStr !== postStr) {
- throw new Error(
- `Difference in open resources before openPlugin and after Plugin.close():
-Before: ${preStr}
-After: ${postStr}`,
- );
- }
- console.log("Correct number of resources");
-}
-
-runTestSync();
-await runTestAsync();
-runTestResourceTable();
-
-runTestOpCount();
-// runTestPluginClose();
| 67c9937e6658c2be9b54cd95132a1055756e433b |
For whoever wants to fix this:
For `Deno.ppid` and `Deno.memoryUsage` you need to move the type declarations from `deno.unstable` to `deno.ns` lib.
For `Deno.sleepSync` you need to move [this line](https://github.com/denoland/deno/blob/875ac73f1e8459ecec3d0d7b275546740bfe007e/runtime/js/90_deno_ns.js#L88) to the `denoNsUnstable` object in that file. (it is actually unstable)
`Deno.shutdown` is actually stable and needs [this line](https://github.com/denoland/deno/blob/875ac73f1e8459ecec3d0d7b275546740bfe007e/runtime/js/90_deno_ns.js#L122) to be moved to `denoNs` object in that file.
| 2021-06-07T11:34:15Z | denoland/deno | denoland__deno-10880 | [
"10827"
] | a5eb2dfc93afc2899ed6e1ad2b3e029157889f7c | stable/unstable documentation vs implementation discrepancy
The following Deno APIs are documented as unstable, but are available in stable:
* `Deno.ppid`
* `Deno.memoryUsage`
* `Deno.sleepSync`
On the other hand, the following Deno APIs are documented as stable, but is only available in unstable:
* `Deno.shutdown`
Is there a reason for this discrepancy? We're building a [Deno namespace shim for Node](https://github.com/fromdeno/deno.ns/), and often have to make decisions on whether to add APIs on this side or the other side of the wall.
| 1.11 | diff --git a/cli/dts/lib.deno.ns.d.ts b/cli/dts/lib.deno.ns.d.ts
--- a/cli/dts/lib.deno.ns.d.ts
+++ b/cli/dts/lib.deno.ns.d.ts
@@ -90,6 +90,24 @@ declare namespace Deno {
/** The current process id of the runtime. */
export const pid: number;
+ /**
+ * The pid of the current process's parent.
+ */
+ export const ppid: number;
+
+ export interface MemoryUsage {
+ rss: number;
+ heapTotal: number;
+ heapUsed: number;
+ external: number;
+ }
+
+ /**
+ * Returns an object describing the memory usage of the Deno process measured
+ * in bytes.
+ */
+ export function memoryUsage(): MemoryUsage;
+
/** Reflects the `NO_COLOR` environment variable at program start.
*
* See: https://no-color.org/ */
diff --git a/cli/dts/lib.deno.unstable.d.ts b/cli/dts/lib.deno.unstable.d.ts
--- a/cli/dts/lib.deno.unstable.d.ts
+++ b/cli/dts/lib.deno.unstable.d.ts
@@ -1069,11 +1069,6 @@ declare namespace Deno {
*/
export function hostname(): string;
- /** **UNSTABLE**: New API, yet to be vetted.
- * The pid of the current process's parent.
- */
- export const ppid: number;
-
/** **UNSTABLE**: New API, yet to be vetted.
* A custom HttpClient for use with `fetch`.
*
diff --git a/cli/dts/lib.deno.unstable.d.ts b/cli/dts/lib.deno.unstable.d.ts
--- a/cli/dts/lib.deno.unstable.d.ts
+++ b/cli/dts/lib.deno.unstable.d.ts
@@ -1171,15 +1166,6 @@ declare namespace Deno {
bytesReceived: number;
}
- export interface MemoryUsage {
- rss: number;
- heapTotal: number;
- heapUsed: number;
- external: number;
- }
-
- export function memoryUsage(): MemoryUsage;
-
export interface RequestEvent {
readonly request: Request;
respondWith(r: Response | Promise<Response>): Promise<void>;
diff --git a/runtime/js/90_deno_ns.js b/runtime/js/90_deno_ns.js
--- a/runtime/js/90_deno_ns.js
+++ b/runtime/js/90_deno_ns.js
@@ -85,7 +85,7 @@
listen: __bootstrap.net.listen,
connectTls: __bootstrap.tls.connectTls,
listenTls: __bootstrap.tls.listenTls,
- sleepSync: __bootstrap.timers.sleepSync,
+ shutdown: __bootstrap.net.shutdown,
fstatSync: __bootstrap.fs.fstatSync,
fstat: __bootstrap.fs.fstat,
fsyncSync: __bootstrap.fs.fsyncSync,
diff --git a/runtime/js/90_deno_ns.js b/runtime/js/90_deno_ns.js
--- a/runtime/js/90_deno_ns.js
+++ b/runtime/js/90_deno_ns.js
@@ -119,7 +119,7 @@
systemCpuInfo: __bootstrap.os.systemCpuInfo,
applySourceMap: __bootstrap.errorStack.opApplySourceMap,
formatDiagnostics: __bootstrap.errorStack.opFormatDiagnostics,
- shutdown: __bootstrap.net.shutdown,
+ sleepSync: __bootstrap.timers.sleepSync,
resolveDns: __bootstrap.net.resolveDns,
listen: __bootstrap.netUnstable.listen,
connect: __bootstrap.netUnstable.connect,
| 10,880 | diff --git a/cli/diagnostics.rs b/cli/diagnostics.rs
--- a/cli/diagnostics.rs
+++ b/cli/diagnostics.rs
@@ -628,45 +628,4 @@ mod tests {
let actual = diagnostics.to_string();
assert_eq!(strip_ansi_codes(&actual), "TS2552 [ERROR]: Cannot find name \'foo_Bar\'. Did you mean \'foo_bar\'?\nfoo_Bar();\n~~~~~~~\n at test.ts:8:1\n\n \'foo_bar\' is declared here.\n function foo_bar() {\n ~~~~~~~\n at test.ts:4:10");
}
-
- #[test]
- fn test_unstable_suggestion() {
- let value = json![
- {
- "start": {
- "line": 0,
- "character": 17
- },
- "end": {
- "line": 0,
- "character": 21
- },
- "fileName": "file:///cli/tests/unstable_ts2551.ts",
- "messageText": "Property 'ppid' does not exist on type 'typeof Deno'. Did you mean 'pid'?",
- "sourceLine": "console.log(Deno.ppid);",
- "relatedInformation": [
- {
- "start": {
- "line": 89,
- "character": 15
- },
- "end": {
- "line": 89,
- "character": 18
- },
- "fileName": "asset:///lib.deno.ns.d.ts",
- "messageText": "'pid' is declared here.",
- "sourceLine": " export const pid: number;",
- "category": 3,
- "code": 2728
- }
- ],
- "category": 1,
- "code": 2551
- }
- ];
- let diagnostics: Diagnostic = serde_json::from_value(value).unwrap();
- let actual = diagnostics.to_string();
- assert_eq!(strip_ansi_codes(&actual), "TS2551 [ERROR]: Property \'ppid\' does not exist on type \'typeof Deno\'. \'Deno.ppid\' is an unstable API. Did you forget to run with the \'--unstable\' flag, or did you mean \'pid\'?\nconsole.log(Deno.ppid);\n ~~~~\n at file:///cli/tests/unstable_ts2551.ts:1:18\n\n \'pid\' is declared here.\n export const pid: number;\n ~~~\n at asset:///lib.deno.ns.d.ts:90:16");
- }
}
diff --git a/cli/tests/integration_tests.rs b/cli/tests/integration_tests.rs
--- a/cli/tests/integration_tests.rs
+++ b/cli/tests/integration_tests.rs
@@ -3976,12 +3976,6 @@ console.log("finish");
output: "unstable_enabled_js.out",
});
- itest!(unstable_disabled_ts2551 {
- args: "run --reload unstable_ts2551.ts",
- exit_code: 1,
- output: "unstable_disabled_ts2551.out",
- });
-
itest!(unstable_worker {
args: "run --reload --unstable --quiet --allow-read unstable_worker.ts",
output: "unstable_worker.ts.out",
diff --git a/cli/tests/unstable_disabled_ts2551.out /dev/null
--- a/cli/tests/unstable_disabled_ts2551.out
+++ /dev/null
@@ -1,10 +0,0 @@
-[WILDCARD]
-error: TS2551 [ERROR]: Property 'ppid' does not exist on type 'typeof Deno'. 'Deno.ppid' is an unstable API. Did you forget to run with the '--unstable' flag, or did you mean 'pid'?
-console.log(Deno.ppid);
- ~~~~
- at [WILDCARD]cli/tests/unstable_ts2551.ts:1:18
-
- 'pid' is declared here.
- export const pid: number;
- ~~~
- at asset:///lib.deno.ns.d.ts:[WILDCARD]
diff --git a/cli/tests/unstable_ts2551.ts /dev/null
--- a/cli/tests/unstable_ts2551.ts
+++ /dev/null
@@ -1,1 +0,0 @@
-console.log(Deno.ppid);
| 67c9937e6658c2be9b54cd95132a1055756e433b |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 5