diff --git a/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md similarity index 100% rename from CODE_OF_CONDUCT.md rename to .github/CODE_OF_CONDUCT.md diff --git a/SECURITY.md b/.github/SECURITY.md similarity index 100% rename from SECURITY.md rename to .github/SECURITY.md diff --git a/Cargo.lock b/Cargo.lock index 788716af16..f879783716 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -768,7 +768,7 @@ dependencies = [ [[package]] name = "deno" -version = "1.28.2" +version = "1.28.3" dependencies = [ "atty", "base32", @@ -884,7 +884,7 @@ dependencies = [ [[package]] name = "deno_bench_util" -version = "0.73.0" +version = "0.74.0" dependencies = [ "bencher", "deno_core", @@ -894,7 +894,7 @@ dependencies = [ [[package]] name = "deno_broadcast_channel" -version = "0.73.0" +version = "0.74.0" dependencies = [ "async-trait", "deno_core", @@ -904,7 +904,7 @@ dependencies = [ [[package]] name = "deno_cache" -version = "0.11.0" +version = "0.12.0" dependencies = [ "async-trait", "deno_core", @@ -916,14 +916,14 @@ dependencies = [ [[package]] name = "deno_console" -version = "0.79.0" +version = "0.80.0" dependencies = [ "deno_core", ] [[package]] name = "deno_core" -version = "0.161.0" +version = "0.162.0" dependencies = [ "anyhow", "bytes", @@ -948,7 +948,7 @@ dependencies = [ [[package]] name = "deno_crypto" -version = "0.93.0" +version = "0.94.0" dependencies = [ "aes", "aes-gcm", @@ -982,9 +982,9 @@ dependencies = [ [[package]] name = "deno_doc" -version = "0.49.1" +version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa3bb0abda350b6523cfc96e0b14c55037fd7b5a901fcc40cb87ef9a1abb6d92" +checksum = "7a5f0f24f690e9c0c1d22fe9c9da68b65d7378a5c10afe4a61398134eb031e21" dependencies = [ "cfg-if", "deno_ast", @@ -1000,9 +1000,9 @@ dependencies = [ [[package]] name = "deno_emit" -version = "0.11.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7be76420d8eaac9d82295eb51cb2c0aebd326d305a2ecbeab6582343fb1b743c" +checksum = "c721cb4e2ca7d94702f6987c2050aedfd270d18f87020080e396865a65dd957e" dependencies = [ "anyhow", "base64", @@ -1014,7 +1014,7 @@ dependencies = [ [[package]] name = "deno_fetch" -version = "0.102.0" +version = "0.103.0" dependencies = [ "bytes", "data-url", @@ -1031,7 +1031,7 @@ dependencies = [ [[package]] name = "deno_ffi" -version = "0.66.0" +version = "0.67.0" dependencies = [ "deno_core", "dlopen", @@ -1044,7 +1044,7 @@ dependencies = [ [[package]] name = "deno_flash" -version = "0.15.0" +version = "0.16.0" dependencies = [ "deno_core", "deno_tls", @@ -1063,19 +1063,18 @@ dependencies = [ [[package]] name = "deno_graph" -version = "0.38.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65eb6b2223b71a759b12bc21ee35842193d3703157950d1411c0243239f072eb" +checksum = "87b3758993b62cf234fac6e922b2217aac6c3086d6d9a4fa36ddf7779abb0890" dependencies = [ "anyhow", "cfg-if", "data-url", "deno_ast", "futures", - "lazy_static", + "once_cell", "parking_lot 0.12.1", "regex", - "ring", "serde", "serde_json", "sourcemap", @@ -1084,7 +1083,7 @@ dependencies = [ [[package]] name = "deno_http" -version = "0.73.0" +version = "0.74.0" dependencies = [ "async-compression", "base64", @@ -1125,7 +1124,7 @@ dependencies = [ [[package]] name = "deno_napi" -version = "0.9.0" +version = "0.10.0" dependencies = [ "deno_core", "libloading", @@ -1133,7 +1132,7 @@ dependencies = [ [[package]] name = "deno_net" -version = "0.71.0" +version = "0.72.0" dependencies = [ "deno_core", "deno_tls", @@ -1147,7 +1146,7 @@ dependencies = [ [[package]] name = "deno_node" -version = "0.16.0" +version = "0.17.0" dependencies = [ "deno_core", "once_cell", @@ -1158,7 +1157,7 @@ dependencies = [ [[package]] name = "deno_ops" -version = "0.39.0" +version = "0.40.0" dependencies = [ "once_cell", "pmutil", @@ -1174,7 +1173,7 @@ dependencies = [ [[package]] name = "deno_runtime" -version = "0.87.0" +version = "0.88.0" dependencies = [ "atty", "deno_broadcast_channel", @@ -1225,9 +1224,9 @@ dependencies = [ [[package]] name = "deno_task_shell" -version = "0.7.3" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a071a6407ade5107091a2481a502e7e6a9a96c5a631c71748058c5a28928fcd3" +checksum = "532b383a071a05144c712614d62f08a2f9fad48dd62d6d457ed3884b049357da" dependencies = [ "anyhow", "futures", @@ -1240,7 +1239,7 @@ dependencies = [ [[package]] name = "deno_tls" -version = "0.66.0" +version = "0.67.0" dependencies = [ "deno_core", "once_cell", @@ -1254,7 +1253,7 @@ dependencies = [ [[package]] name = "deno_url" -version = "0.79.0" +version = "0.80.0" dependencies = [ "deno_bench_util", "deno_core", @@ -1266,7 +1265,7 @@ dependencies = [ [[package]] name = "deno_web" -version = "0.110.0" +version = "0.111.0" dependencies = [ "async-trait", "base64-simd", @@ -1283,7 +1282,7 @@ dependencies = [ [[package]] name = "deno_webgpu" -version = "0.80.0" +version = "0.81.0" dependencies = [ "deno_core", "serde", @@ -1294,14 +1293,14 @@ dependencies = [ [[package]] name = "deno_webidl" -version = "0.79.0" +version = "0.80.0" dependencies = [ "deno_core", ] [[package]] name = "deno_websocket" -version = "0.84.0" +version = "0.85.0" dependencies = [ "deno_core", "deno_tls", @@ -1315,7 +1314,7 @@ dependencies = [ [[package]] name = "deno_webstorage" -version = "0.74.0" +version = "0.75.0" dependencies = [ "deno_core", "deno_web", @@ -1445,15 +1444,16 @@ dependencies = [ [[package]] name = "dprint-plugin-markdown" -version = "0.14.2" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49cf3bc0cb9cc526a894b1d5af07c2ce2af1fa56b765990845ec781ab4cd1c91" +checksum = "999e8891976e3b15b519b920db4ac70c6a85f0c6f0e0ddb6ef3b247373e8984d" dependencies = [ "anyhow", "dprint-core", "pulldown-cmark", "regex", "serde", + "unicode-width", ] [[package]] @@ -1659,9 +1659,9 @@ dependencies = [ [[package]] name = "eszip" -version = "0.30.0" +version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fdf9b31295c768c806cbc0d08d98868b4382684b002d216a16eb661bb8e8575" +checksum = "d8119eb19b5b7f9c6b6da550781249bb05562fbdadb10f80f0a3afb96dde4944" dependencies = [ "anyhow", "base64", @@ -2844,7 +2844,7 @@ dependencies = [ [[package]] name = "napi_sym" -version = "0.9.0" +version = "0.10.0" dependencies = [ "proc-macro2 1.0.43", "quote 1.0.21", @@ -3023,9 +3023,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.14.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f7254b99e31cad77da24b08ebf628882739a608578bb1bcdfc1f9c21260d7c0" +checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" [[package]] name = "opaque-debug" @@ -3977,7 +3977,7 @@ dependencies = [ [[package]] name = "serde_v8" -version = "0.72.0" +version = "0.73.0" dependencies = [ "bencher", "bytes", @@ -5155,9 +5155,9 @@ checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" [[package]] name = "trybuild" -version = "1.0.71" +version = "1.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea496675d71016e9bc76aa42d87f16aefd95447cc5818e671e12b2d7e269075d" +checksum = "db29f438342820400f2d9acfec0d363e987a38b2950bdb50a7069ed17b2148ee" dependencies = [ "glob", "once_cell", @@ -5387,14 +5387,13 @@ dependencies = [ [[package]] name = "v8" -version = "0.55.0" +version = "0.58.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46cd4f562bce7520fbb511850c5488366264caf346be221cf7e908f51ac33dbc" +checksum = "8e9b88668afedf6ec9f8f6d30b446f622498da2ef0b3991a52e10f0ea8c6cc09" dependencies = [ "bitflags", "fslock", "lazy_static", - "libc", "which", ] diff --git a/Cargo.toml b/Cargo.toml index 37df295aca..760a610486 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ resolver = "2" members = [ "bench_util", "cli", - "cli/napi_sym", + "cli/napi/sym", "core", "ops", "runtime", @@ -40,36 +40,36 @@ license = "MIT" repository = "https://github.com/denoland/deno" [workspace.dependencies] -v8 = { version = "0.55.0", default-features = false } +v8 = { version = "0.58.0", default-features = false } deno_ast = { version = "0.21.0", features = ["transpiling"] } -deno_core = { version = "0.161.0", path = "./core" } -deno_ops = { version = "0.39.0", path = "./ops" } -serde_v8 = { version = "0.72.0", path = "./serde_v8" } -deno_runtime = { version = "0.87.0", path = "./runtime" } -napi_sym = { version = "0.9.0", path = "./cli/napi_sym" } -deno_bench_util = { version = "0.73.0", path = "./bench_util" } +deno_core = { version = "0.162.0", path = "./core" } +deno_ops = { version = "0.40.0", path = "./ops" } +serde_v8 = { version = "0.73.0", path = "./serde_v8" } +deno_runtime = { version = "0.88.0", path = "./runtime" } +napi_sym = { version = "0.10.0", path = "./cli/napi/sym" } +deno_bench_util = { version = "0.74.0", path = "./bench_util" } test_util = { path = "./test_util" } # exts -deno_broadcast_channel = { version = "0.73.0", path = "./ext/broadcast_channel" } -deno_cache = { version = "0.11.0", path = "./ext/cache" } -deno_console = { version = "0.79.0", path = "./ext/console" } -deno_crypto = { version = "0.93.0", path = "./ext/crypto" } -deno_fetch = { version = "0.102.0", path = "./ext/fetch" } -deno_ffi = { version = "0.66.0", path = "./ext/ffi" } -deno_flash = { version = "0.15.0", path = "./ext/flash" } -deno_http = { version = "0.73.0", path = "./ext/http" } -deno_net = { version = "0.71.0", path = "./ext/net" } -deno_node = { version = "0.16.0", path = "./ext/node" } -deno_tls = { version = "0.66.0", path = "./ext/tls" } -deno_url = { version = "0.79.0", path = "./ext/url" } -deno_web = { version = "0.110.0", path = "./ext/web" } -deno_webgpu = { version = "0.80.0", path = "./ext/webgpu" } -deno_webidl = { version = "0.79.0", path = "./ext/webidl" } -deno_websocket = { version = "0.84.0", path = "./ext/websocket" } -deno_webstorage = { version = "0.74.0", path = "./ext/webstorage" } -deno_napi = { version = "0.9.0", path = "./ext/napi" } +deno_broadcast_channel = { version = "0.74.0", path = "./ext/broadcast_channel" } +deno_cache = { version = "0.12.0", path = "./ext/cache" } +deno_console = { version = "0.80.0", path = "./ext/console" } +deno_crypto = { version = "0.94.0", path = "./ext/crypto" } +deno_fetch = { version = "0.103.0", path = "./ext/fetch" } +deno_ffi = { version = "0.67.0", path = "./ext/ffi" } +deno_flash = { version = "0.16.0", path = "./ext/flash" } +deno_http = { version = "0.74.0", path = "./ext/http" } +deno_net = { version = "0.72.0", path = "./ext/net" } +deno_node = { version = "0.17.0", path = "./ext/node" } +deno_tls = { version = "0.67.0", path = "./ext/tls" } +deno_url = { version = "0.80.0", path = "./ext/url" } +deno_web = { version = "0.111.0", path = "./ext/web" } +deno_webgpu = { version = "0.81.0", path = "./ext/webgpu" } +deno_webidl = { version = "0.80.0", path = "./ext/webidl" } +deno_websocket = { version = "0.85.0", path = "./ext/websocket" } +deno_webstorage = { version = "0.75.0", path = "./ext/webstorage" } +deno_napi = { version = "0.10.0", path = "./ext/napi" } anyhow = "1.0.57" async-trait = "0.1.51" @@ -89,7 +89,7 @@ libc = "=0.2.126" log = "=0.4.17" lzzzz = "1.0" notify = "=5.0.0" -once_cell = "=1.14.0" +once_cell = "=1.16.0" os_pipe = "=1.0.1" parking_lot = "0.12.0" percent-encoding = "=2.2.0" diff --git a/Releases.md b/Releases.md index 8ce785530d..5c734ef93c 100644 --- a/Releases.md +++ b/Releases.md @@ -6,6 +6,40 @@ https://github.com/denoland/deno/releases We also have one-line install commands at: https://github.com/denoland/deno_install +### 1.28.3 / 2022.12.01 + +- Revert "fix(ext/flash): graceful server startup/shutdown with unsettl… + (#16839) +- feat(core): send "executionContextDestroyed" notification on program end + (#16831) +- feat(core): show unresolved promise origin (#16650) +- feat(core): support initializing extensions with and without JS (#16789) +- feat(ops): fast calls for Wasm (#16776) +- feat(ops): support raw pointer arguments (#16826) +- feat(unstable): rework Deno.Command (#16812) +- fix(cli/js): improve resource sanitizer messages (#16798) +- fix(coverage): Error if the emit cache is invalid (#16850) +- fix(ext/ffi): Null buffer pointer value is inconsistent (#16625) +- fix(ext/node): allow absolute path in createRequire (#16853) +- fix(ext/web): fix typings for readable stream readers (#16191) +- fix(fmt/markdown): fix emoji width calculation in tables (#16870) +- fix(inspector): send "isDefault" in aux data (#16836) +- fix(lsp): analyze fs dependencies of dependencies to find npm package + requirements (#16866) +- fix(npm): allow to inspect npm modules with --inspect-brk (#16841) +- fix(npm): better error message when attempting to use typescript in npm + packages (#16813) +- fix(npm): don't resolve JS files when resolving types (#16854) +- fix(npm): ensure npm package downloaded once per run when using `--reload` + (#16842) +- fix(npm): improve package.json exports support for types (#16880) +- fix(ops): circular dependency in deno_ops test (#16809) +- fix(repl): more reliable history handling (#16797) +- fix(repl): respect --quiet flag (#16875) +- fix(runtime): feature-flag snapshot from snapshot (#16843) +- fix(task): output encoding issues on windows (#16794) +- perf(ops): Reenable fast unit result optimization (#16827) + ### 1.28.2 / 2022.11.24 - feat(cli): add warning for incorrectly ordered flags (#16734) diff --git a/bench_util/Cargo.toml b/bench_util/Cargo.toml index 71a40b16a6..a8be80cdd0 100644 --- a/bench_util/Cargo.toml +++ b/bench_util/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_bench_util" -version = "0.73.0" +version = "0.74.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/bench_util/js_runtime.rs b/bench_util/js_runtime.rs index f87fa3b03a..0495d6d8dc 100644 --- a/bench_util/js_runtime.rs +++ b/bench_util/js_runtime.rs @@ -9,7 +9,7 @@ use crate::profiling::is_profiling; pub fn create_js_runtime(setup: impl FnOnce() -> Vec) -> JsRuntime { JsRuntime::new(RuntimeOptions { - extensions: setup(), + extensions_with_js: setup(), ..Default::default() }) } diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 3c15f823f9..e5025d5d73 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno" -version = "1.28.2" +version = "1.28.3" authors.workspace = true default-run = "deno" edition.workspace = true @@ -26,7 +26,7 @@ harness = false path = "./bench/lsp_bench_standalone.rs" [build-dependencies] -deno_runtime.workspace = true +deno_runtime = { workspace = true, features = ["snapshot_from_snapshot"] } deno_core.workspace = true regex.workspace = true serde.workspace = true @@ -43,12 +43,12 @@ winres.workspace = true [dependencies] deno_ast = { workspace = true, features = ["bundler", "cjs", "codegen", "dep_graph", "module_specifier", "proposal", "react", "sourcemap", "transforms", "typescript", "view", "visit"] } deno_core.workspace = true -deno_doc = "0.49.1" -deno_emit = "0.11.0" -deno_graph = "0.38.0" +deno_doc = "0.51.0" +deno_emit = "0.12.0" +deno_graph = "0.39.0" deno_lint = { version = "0.35.0", features = ["docs"] } deno_runtime.workspace = true -deno_task_shell = "0.7.3" +deno_task_shell = "0.8.1" napi_sym.workspace = true atty.workspace = true @@ -62,11 +62,11 @@ clap_complete_fig = "=3.1.5" data-url.workspace = true dissimilar = "=1.0.4" dprint-plugin-json = "=0.16.0" -dprint-plugin-markdown = "=0.14.2" +dprint-plugin-markdown = "=0.14.3" dprint-plugin-typescript = "=0.78.0" encoding_rs.workspace = true env_logger = "=0.9.0" -eszip = "=0.30.0" +eszip = "=0.31.0" fancy-regex = "=0.10.0" flate2.workspace = true http.workspace = true diff --git a/cli/args/config_file.rs b/cli/args/config_file.rs index 435e0d715b..76340aa8ba 100644 --- a/cli/args/config_file.rs +++ b/cli/args/config_file.rs @@ -3,10 +3,9 @@ use crate::args::ConfigFlag; use crate::args::Flags; use crate::args::TaskFlags; -use crate::fs_util; -use crate::fs_util::canonicalize_path; -use crate::fs_util::specifier_parent; -use crate::fs_util::specifier_to_file_path; +use crate::util::fs::canonicalize_path; +use crate::util::path::specifier_parent; +use crate::util::path::specifier_to_file_path; use deno_core::anyhow::anyhow; use deno_core::anyhow::bail; @@ -467,7 +466,7 @@ impl ConfigFile { .. }) = &flags.subcommand { - let task_cwd = fs_util::canonicalize_path(&PathBuf::from(path))?; + let task_cwd = canonicalize_path(&PathBuf::from(path))?; if let Some(path) = Self::discover_from(&task_cwd, &mut checked)? { return Ok(Some(path)); } diff --git a/cli/args/flags.rs b/cli/args/flags.rs index 829051bcee..7a4416cf50 100644 --- a/cli/args/flags.rs +++ b/cli/args/flags.rs @@ -163,6 +163,7 @@ pub struct LintFlags { pub struct ReplFlags { pub eval_files: Option>, pub eval: Option, + pub is_default_command: bool, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] @@ -245,6 +246,7 @@ impl Default for DenoSubcommand { DenoSubcommand::Repl(ReplFlags { eval_files: None, eval: None, + is_default_command: true, }) } } @@ -624,6 +626,7 @@ pub fn flags_from_vec(args: Vec) -> clap::Result { ReplFlags { eval_files: None, eval: None, + is_default_command: true, }, ), } @@ -632,15 +635,18 @@ pub fn flags_from_vec(args: Vec) -> clap::Result { } fn handle_repl_flags(flags: &mut Flags, repl_flags: ReplFlags) { + // If user runs just `deno` binary we enter REPL and allow all permissions. + if repl_flags.is_default_command { + flags.allow_net = Some(vec![]); + flags.allow_env = Some(vec![]); + flags.allow_run = Some(vec![]); + flags.allow_read = Some(vec![]); + flags.allow_sys = Some(vec![]); + flags.allow_write = Some(vec![]); + flags.allow_ffi = Some(vec![]); + flags.allow_hrtime = true; + } flags.subcommand = DenoSubcommand::Repl(repl_flags); - flags.allow_net = Some(vec![]); - flags.allow_env = Some(vec![]); - flags.allow_run = Some(vec![]); - flags.allow_read = Some(vec![]); - flags.allow_sys = Some(vec![]); - flags.allow_write = Some(vec![]); - flags.allow_ffi = Some(vec![]); - flags.allow_hrtime = true; } fn clap_root(version: &str) -> Command { @@ -797,12 +803,20 @@ Future runs of this module will trigger no downloads or compilation unless \ fn check_subcommand<'a>() -> Command<'a> { compile_args_without_check_args(Command::new("check")) - .arg( - Arg::new("remote") - .long("remote") - .help("Type-check all modules, including remote") - .conflicts_with("no-remote") + .arg( + Arg::new("all") + .long("all") + .help("Type-check all code, including remote modules and npm packages") + .conflicts_with("no-remote") ) + .arg( + // past alias for --all + Arg::new("remote") + .long("remote") + .help("Type-check all modules, including remote") + .conflicts_with("no-remote") + .hide(true) + ) .arg( Arg::new("file") .takes_value(true) @@ -1456,7 +1470,7 @@ Ignore linting a file by adding an ignore comment at the top of the file: } fn repl_subcommand<'a>() -> Command<'a> { - runtime_args(Command::new("repl"), false, true) + runtime_args(Command::new("repl"), true, true) .about("Read Eval Print Loop") .arg( Arg::new("eval-file") @@ -1475,7 +1489,6 @@ fn repl_subcommand<'a>() -> Command<'a> { .takes_value(true) .value_name("code"), ) - .arg(unsafely_ignore_certificate_errors_arg()) } fn run_subcommand<'a>() -> Command<'a> { @@ -2343,7 +2356,7 @@ fn check_parse(flags: &mut Flags, matches: &clap::ArgMatches) { .unwrap() .map(String::from) .collect(); - if matches.is_present("remote") { + if matches.is_present("all") || matches.is_present("remote") { flags.type_check_mode = TypeCheckMode::All; } flags.subcommand = DenoSubcommand::Check(CheckFlags { files }); @@ -2646,7 +2659,7 @@ fn lint_parse(flags: &mut Flags, matches: &clap::ArgMatches) { } fn repl_parse(flags: &mut Flags, matches: &clap::ArgMatches) { - runtime_args_parse(flags, matches, false, true); + runtime_args_parse(flags, matches, true, true); unsafely_ignore_certificate_errors_parse(flags, matches); let eval_files: Option> = matches @@ -2658,6 +2671,7 @@ fn repl_parse(flags: &mut Flags, matches: &clap::ArgMatches) { ReplFlags { eval_files, eval: matches.value_of("eval").map(ToOwned::to_owned), + is_default_command: false, }, ); } @@ -4001,26 +4015,28 @@ mod tests { } ); - let r = flags_from_vec(svec!["deno", "check", "--remote", "script.ts"]); - assert_eq!( - r.unwrap(), - Flags { - subcommand: DenoSubcommand::Check(CheckFlags { - files: svec!["script.ts"], - }), - type_check_mode: TypeCheckMode::All, - ..Flags::default() - } - ); + for all_flag in ["--remote", "--all"] { + let r = flags_from_vec(svec!["deno", "check", all_flag, "script.ts"]); + assert_eq!( + r.unwrap(), + Flags { + subcommand: DenoSubcommand::Check(CheckFlags { + files: svec!["script.ts"], + }), + type_check_mode: TypeCheckMode::All, + ..Flags::default() + } + ); - let r = flags_from_vec(svec![ - "deno", - "check", - "--remote", - "--no-remote", - "script.ts" - ]); - assert_eq!(r.unwrap_err().kind(), clap::ErrorKind::ArgumentConflict); + let r = flags_from_vec(svec![ + "deno", + "check", + all_flag, + "--no-remote", + "script.ts" + ]); + assert_eq!(r.unwrap_err().kind(), clap::ErrorKind::ArgumentConflict); + } } #[test] @@ -4266,7 +4282,8 @@ mod tests { Flags { subcommand: DenoSubcommand::Repl(ReplFlags { eval_files: None, - eval: None + eval: None, + is_default_command: true, }), allow_net: Some(vec![]), unsafely_ignore_certificate_errors: None, @@ -4285,13 +4302,14 @@ mod tests { #[test] fn repl_with_flags() { #[rustfmt::skip] - let r = flags_from_vec(svec!["deno", "repl", "--import-map", "import_map.json", "--no-remote", "--config", "tsconfig.json", "--no-check", "--reload", "--lock", "lock.json", "--lock-write", "--cert", "example.crt", "--cached-only", "--location", "https:foo", "--v8-flags=--help", "--seed", "1", "--inspect=127.0.0.1:9229", "--unsafely-ignore-certificate-errors"]); + let r = flags_from_vec(svec!["deno", "repl", "-A", "--import-map", "import_map.json", "--no-remote", "--config", "tsconfig.json", "--no-check", "--reload", "--lock", "lock.json", "--lock-write", "--cert", "example.crt", "--cached-only", "--location", "https:foo", "--v8-flags=--help", "--seed", "1", "--inspect=127.0.0.1:9229", "--unsafely-ignore-certificate-errors"]); assert_eq!( r.unwrap(), Flags { subcommand: DenoSubcommand::Repl(ReplFlags { eval_files: None, - eval: None + eval: None, + is_default_command: false, }), import_map_path: Some("import_map.json".to_string()), no_remote: true, @@ -4306,6 +4324,7 @@ mod tests { v8_flags: svec!["--help", "--random-seed=1"], seed: Some(1), inspect: Some("127.0.0.1:9229".parse().unwrap()), + allow_all: true, allow_net: Some(vec![]), allow_env: Some(vec![]), allow_run: Some(vec![]), @@ -4323,22 +4342,16 @@ mod tests { #[test] fn repl_with_eval_flag() { #[rustfmt::skip] - let r = flags_from_vec(svec!["deno", "repl", "--eval", "console.log('hello');"]); + let r = flags_from_vec(svec!["deno", "repl", "--allow-write", "--eval", "console.log('hello');"]); assert_eq!( r.unwrap(), Flags { subcommand: DenoSubcommand::Repl(ReplFlags { eval_files: None, eval: Some("console.log('hello');".to_string()), + is_default_command: false, }), - allow_net: Some(vec![]), - allow_env: Some(vec![]), - allow_run: Some(vec![]), - allow_read: Some(vec![]), - allow_sys: Some(vec![]), allow_write: Some(vec![]), - allow_ffi: Some(vec![]), - allow_hrtime: true, type_check_mode: TypeCheckMode::None, ..Flags::default() } @@ -4359,15 +4372,8 @@ mod tests { "https://examples.deno.land/hello-world.ts".to_string() ]), eval: None, + is_default_command: false, }), - allow_net: Some(vec![]), - allow_env: Some(vec![]), - allow_run: Some(vec![]), - allow_read: Some(vec![]), - allow_sys: Some(vec![]), - allow_write: Some(vec![]), - allow_ffi: Some(vec![]), - allow_hrtime: true, type_check_mode: TypeCheckMode::None, ..Flags::default() } @@ -5162,16 +5168,9 @@ mod tests { subcommand: DenoSubcommand::Repl(ReplFlags { eval_files: None, eval: Some("console.log('hello');".to_string()), + is_default_command: false, }), unsafely_ignore_certificate_errors: Some(vec![]), - allow_net: Some(vec![]), - allow_env: Some(vec![]), - allow_run: Some(vec![]), - allow_read: Some(vec![]), - allow_sys: Some(vec![]), - allow_write: Some(vec![]), - allow_ffi: Some(vec![]), - allow_hrtime: true, type_check_mode: TypeCheckMode::None, ..Flags::default() } @@ -5236,7 +5235,8 @@ mod tests { Flags { subcommand: DenoSubcommand::Repl(ReplFlags { eval_files: None, - eval: None + eval: None, + is_default_command: false, }), unsafely_ignore_certificate_errors: Some(svec![ "deno.land", @@ -5246,14 +5246,6 @@ mod tests { "[::1]", "1.2.3.4" ]), - allow_net: Some(vec![]), - allow_env: Some(vec![]), - allow_run: Some(vec![]), - allow_read: Some(vec![]), - allow_sys: Some(vec![]), - allow_write: Some(vec![]), - allow_ffi: Some(vec![]), - allow_hrtime: true, type_check_mode: TypeCheckMode::None, ..Flags::default() } diff --git a/cli/args/lockfile.rs b/cli/args/lockfile.rs index f99d2f5701..0d3b2f249d 100644 --- a/cli/args/lockfile.rs +++ b/cli/args/lockfile.rs @@ -2,24 +2,20 @@ use deno_core::anyhow::Context; use deno_core::error::AnyError; -use deno_core::parking_lot::Mutex; use deno_core::serde::Deserialize; use deno_core::serde::Serialize; use deno_core::serde_json; -use deno_core::ModuleSpecifier; use log::debug; -use std::cell::RefCell; use std::collections::BTreeMap; use std::io::Write; use std::path::PathBuf; -use std::rc::Rc; -use std::sync::Arc; use crate::args::ConfigFile; use crate::npm::NpmPackageId; use crate::npm::NpmPackageReq; use crate::npm::NpmResolutionPackage; use crate::tools::fmt::format_json; +use crate::util; use crate::Flags; #[derive(Debug)] @@ -95,15 +91,6 @@ pub struct Lockfile { } impl Lockfile { - pub fn as_maybe_locker( - lockfile: Option>>, - ) -> Option>> { - lockfile.as_ref().map(|lf| { - Rc::new(RefCell::new(Locker(Some(lf.clone())))) - as Rc> - }) - } - pub fn discover( flags: &Flags, maybe_config_file: Option<&ConfigFile>, @@ -260,7 +247,7 @@ impl Lockfile { /// is not included, insert it. fn check_or_insert(&mut self, specifier: &str, code: &str) -> bool { if let Some(lockfile_checksum) = self.content.remote.get(specifier) { - let compiled_checksum = crate::checksum::gen(&[code.as_bytes()]); + let compiled_checksum = util::checksum::gen(&[code.as_bytes()]); lockfile_checksum == &compiled_checksum } else { self.insert(specifier, code); @@ -269,7 +256,7 @@ impl Lockfile { } fn insert(&mut self, specifier: &str, code: &str) { - let checksum = crate::checksum::gen(&[code.as_bytes()]); + let checksum = util::checksum::gen(&[code.as_bytes()]); self.content.remote.insert(specifier.to_string(), checksum); self.has_content_changed = true; } @@ -341,33 +328,6 @@ Use \"--lock-write\" flag to regenerate the lockfile at \"{}\".", } } -#[derive(Debug)] -pub struct Locker(Option>>); - -impl deno_graph::source::Locker for Locker { - fn check_or_insert( - &mut self, - specifier: &ModuleSpecifier, - source: &str, - ) -> bool { - if let Some(lock_file) = &self.0 { - let mut lock_file = lock_file.lock(); - lock_file.check_or_insert_remote(specifier.as_str(), source) - } else { - true - } - } - - fn get_checksum(&self, content: &str) -> String { - crate::checksum::gen(&[content.as_bytes()]) - } - - fn get_filename(&self) -> Option { - let lock_file = self.0.as_ref()?.lock(); - lock_file.filename.to_str().map(|s| s.to_string()) - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/cli/args/mod.rs b/cli/args/mod.rs index 50a407ee3d..38e0abea0d 100644 --- a/cli/args/mod.rs +++ b/cli/args/mod.rs @@ -22,6 +22,10 @@ pub use config_file::TsConfig; pub use config_file::TsConfigForEmit; pub use config_file::TsConfigType; pub use config_file::TsTypeLib; +use deno_runtime::deno_tls::rustls; +use deno_runtime::deno_tls::rustls_native_certs::load_native_certs; +use deno_runtime::deno_tls::rustls_pemfile; +use deno_runtime::deno_tls::webpki_roots; pub use flags::*; pub use lockfile::Lockfile; pub use lockfile::LockfileError; @@ -40,16 +44,130 @@ use deno_runtime::inspector_server::InspectorServer; use deno_runtime::permissions::PermissionsOptions; use std::collections::BTreeMap; use std::env; +use std::io::BufReader; use std::net::SocketAddr; use std::path::PathBuf; use std::sync::Arc; use crate::cache::DenoDir; -use crate::file_fetcher::get_root_cert_store; -use crate::file_fetcher::CacheSetting; -use crate::fs_util; +use crate::util::fs::canonicalize_path_maybe_not_exists; use crate::version; +/// Indicates how cached source files should be handled. +#[derive(Debug, Clone, Eq, PartialEq)] +pub enum CacheSetting { + /// Only the cached files should be used. Any files not in the cache will + /// error. This is the equivalent of `--cached-only` in the CLI. + Only, + /// No cached source files should be used, and all files should be reloaded. + /// This is the equivalent of `--reload` in the CLI. + ReloadAll, + /// Only some cached resources should be used. This is the equivalent of + /// `--reload=https://deno.land/std` or + /// `--reload=https://deno.land/std,https://deno.land/x/example`. + ReloadSome(Vec), + /// The usability of a cached value is determined by analyzing the cached + /// headers and other metadata associated with a cached response, reloading + /// any cached "non-fresh" cached responses. + RespectHeaders, + /// The cached source files should be used for local modules. This is the + /// default behavior of the CLI. + Use, +} + +impl CacheSetting { + pub fn should_use_for_npm_package(&self, package_name: &str) -> bool { + match self { + CacheSetting::ReloadAll => false, + CacheSetting::ReloadSome(list) => { + if list.iter().any(|i| i == "npm:") { + return false; + } + let specifier = format!("npm:{}", package_name); + if list.contains(&specifier) { + return false; + } + true + } + _ => true, + } + } +} + +/// Create and populate a root cert store based on the passed options and +/// environment. +pub fn get_root_cert_store( + maybe_root_path: Option, + maybe_ca_stores: Option>, + maybe_ca_file: Option, +) -> Result { + let mut root_cert_store = RootCertStore::empty(); + let ca_stores: Vec = maybe_ca_stores + .or_else(|| { + let env_ca_store = env::var("DENO_TLS_CA_STORE").ok()?; + Some( + env_ca_store + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(), + ) + }) + .unwrap_or_else(|| vec!["mozilla".to_string()]); + + for store in ca_stores.iter() { + match store.as_str() { + "mozilla" => { + root_cert_store.add_server_trust_anchors( + webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| { + rustls::OwnedTrustAnchor::from_subject_spki_name_constraints( + ta.subject, + ta.spki, + ta.name_constraints, + ) + }), + ); + } + "system" => { + let roots = load_native_certs().expect("could not load platform certs"); + for root in roots { + root_cert_store + .add(&rustls::Certificate(root.0)) + .expect("Failed to add platform cert to root cert store"); + } + } + _ => { + return Err(anyhow!("Unknown certificate store \"{}\" specified (allowed: \"system,mozilla\")", store)); + } + } + } + + let ca_file = maybe_ca_file.or_else(|| env::var("DENO_CERT").ok()); + if let Some(ca_file) = ca_file { + let ca_file = if let Some(root) = &maybe_root_path { + root.join(&ca_file) + } else { + PathBuf::from(ca_file) + }; + let certfile = std::fs::File::open(&ca_file)?; + let mut reader = BufReader::new(certfile); + + match rustls_pemfile::certs(&mut reader) { + Ok(certs) => { + root_cert_store.add_parsable_certificates(&certs); + } + Err(e) => { + return Err(anyhow!( + "Unable to add pem file to certificate store: {}", + e + )); + } + } + } + + Ok(root_cert_store) +} + /// Overrides for the options below that when set will /// use these values over the values derived from the /// CLI flags or config file. @@ -176,7 +294,7 @@ impl CliOptions { } else { std::env::current_dir()?.join("node_modules") }; - Ok(Some(fs_util::canonicalize_path_maybe_not_exists(&path)?)) + Ok(Some(canonicalize_path_maybe_not_exists(&path)?)) } pub fn resolve_root_cert_store(&self) -> Result { @@ -342,6 +460,13 @@ impl CliOptions { self.flags.log_level } + pub fn is_quiet(&self) -> bool { + self + .log_level() + .map(|l| l == log::Level::Error) + .unwrap_or(false) + } + pub fn location_flag(&self) -> Option<&Url> { self.flags.location.as_ref() } diff --git a/cli/bench/console.js b/cli/bench/console.js index b1873953c3..1e0ebb37a6 100644 --- a/cli/bench/console.js +++ b/cli/bench/console.js @@ -1,8 +1,3 @@ // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. const count = 100000; - -const start = Date.now(); for (let i = 0; i < count; i++) console.log("Hello World"); -const elapsed = Date.now() - start; -const rate = Math.floor(count / (elapsed / 1000)); -console.log(`time ${elapsed} ms rate ${rate}`); diff --git a/cli/bench/encode_into.js b/cli/bench/encode_into.js index aaee234348..458a88b84c 100644 --- a/cli/bench/encode_into.js +++ b/cli/bench/encode_into.js @@ -1,11 +1,10 @@ // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. -const queueMicrotask = globalThis.queueMicrotask || process.nextTick; let [total, count] = typeof Deno !== "undefined" ? Deno.args : [process.argv[2], process.argv[3]]; total = total ? parseInt(total, 0) : 50; -count = count ? parseInt(count, 10) : 1000000; +count = count ? parseInt(count, 10) : 10000000; function bench(fun) { const start = Date.now(); @@ -13,7 +12,7 @@ function bench(fun) { const elapsed = Date.now() - start; const rate = Math.floor(count / (elapsed / 1000)); console.log(`time ${elapsed} ms rate ${rate}`); - if (--total) queueMicrotask(() => bench(fun)); + if (--total) bench(fun); } const encoder = new TextEncoder(); diff --git a/cli/bench/stdio/README.md b/cli/bench/stdio/README.md new file mode 100644 index 0000000000..b2d4875ac7 --- /dev/null +++ b/cli/bench/stdio/README.md @@ -0,0 +1,9 @@ +## `stdio` benchmarks + +Compile the C baseline and run the benchmark: + +```bash +cc stdio.c -o stdio -O3 +time dd if=/dev/zero bs=65536 count=500000 | ./stdio +time dd if=/dev/zero bs=65536 count=500000 | deno run stdio.js +``` diff --git a/cli/bench/stdio/stdio.c b/cli/bench/stdio/stdio.c new file mode 100644 index 0000000000..8125a0d00f --- /dev/null +++ b/cli/bench/stdio/stdio.c @@ -0,0 +1,29 @@ +// From https://github.com/just-js/benchmarks/tree/main/01-stdio +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + unsigned int blocksize = 65536; + if (argc == 2) { + blocksize = atoi(argv[1]); + } + char buf[blocksize]; + unsigned long size = 0; + unsigned int reads = 0; + int n = read(STDIN_FILENO, buf, blocksize); + while (n > 0) { + reads++; + size += n; + n = read(STDIN_FILENO, buf, blocksize); + } + if (n < 0) { + fprintf(stderr, "read: %s (%i)\n", strerror(errno), errno); + exit(1); + } + fprintf(stdout, "size %lu reads %u blocksize %u\n", size, reads, blocksize); +} \ No newline at end of file diff --git a/cli/bench/stdio/stdio.js b/cli/bench/stdio/stdio.js new file mode 100644 index 0000000000..0663d6fd7d --- /dev/null +++ b/cli/bench/stdio/stdio.js @@ -0,0 +1,16 @@ +// From https://github.com/just-js/benchmarks/tree/main/01-stdio +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +const blocksize = parseInt(Deno.args[0] || 65536); +const buf = new Uint8Array(blocksize); +let size = 0; +let reads = 0; + +let n = Deno.stdin.readSync(buf); +while (n > 0) { + reads++; + size += n; + n = Deno.stdin.readSync(buf); +} +if (n < 0) throw new Error("Bad Read"); +console.log(`size ${size} reads ${reads} blocksize ${blocksize}`); diff --git a/cli/bench/webstorage.js b/cli/bench/webstorage.js new file mode 100644 index 0000000000..bdb10e5681 --- /dev/null +++ b/cli/bench/webstorage.js @@ -0,0 +1,21 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +// Note: when benchmarking across different Deno version, make sure to clear +// the DENO_DIR cache. +let [total, count] = typeof Deno !== "undefined" ? Deno.args : []; + +total = total ? parseInt(total, 0) : 50; +count = count ? parseInt(count, 10) : 1000000; + +function bench(fun) { + const start = Date.now(); + for (let i = 0; i < count; i++) fun(i); + const elapsed = Date.now() - start; + const rate = Math.floor(count / (elapsed / 1000)); + console.log(`time ${elapsed} ms rate ${rate}`); + if (--total) queueMicrotask(() => bench(fun)); +} + +localStorage.clear(); +localStorage.setItem("foo", "bar"); +bench(() => localStorage.getItem("foo")); diff --git a/cli/build.rs b/cli/build.rs index 15be033fd8..a92ba21d0b 100644 --- a/cli/build.rs +++ b/cli/build.rs @@ -130,6 +130,10 @@ mod ts { path_dts.join(format!("lib.{}.d.ts", name)).display() ); } + println!( + "cargo:rerun-if-changed={}", + cwd.join("js").join("40_testing.js").display() + ); // create a copy of the vector that includes any op crate libs to be passed // to the JavaScript compiler to build into the snapshot @@ -243,6 +247,7 @@ mod ts { Ok(()) }) .build()], + extensions_with_js: vec![], additional_files: files, compression_cb: Some(Box::new(|vec, snapshot_slice| { vec.extend_from_slice( @@ -254,17 +259,24 @@ mod ts { } pub(crate) fn version() -> String { - std::fs::read_to_string("tsc/00_typescript.js") - .unwrap() - .lines() - .find(|l| l.contains("ts.version = ")) - .expect( - "Failed to find the pattern `ts.version = ` in typescript source code", - ) - .chars() - .skip_while(|c| !char::is_numeric(*c)) - .take_while(|c| *c != '"') - .collect::() + let file_text = std::fs::read_to_string("tsc/00_typescript.js").unwrap(); + let mut version = String::new(); + for line in file_text.lines() { + let major_minor_text = "ts.versionMajorMinor = \""; + let version_text = "ts.version = \"\".concat(ts.versionMajorMinor, \""; + if version.is_empty() { + if let Some(index) = line.find(major_minor_text) { + let remaining_line = &line[index + major_minor_text.len()..]; + version + .push_str(&remaining_line[..remaining_line.find('"').unwrap()]); + } + } else if let Some(index) = line.find(version_text) { + let remaining_line = &line[index + version_text.len()..]; + version.push_str(&remaining_line[..remaining_line.find('"').unwrap()]); + return version; + } + } + panic!("Could not find ts version.") } } @@ -304,6 +316,7 @@ fn create_cli_snapshot(snapshot_path: PathBuf, files: Vec) { snapshot_path, startup_snapshot: Some(deno_runtime::js::deno_isolate_init()), extensions, + extensions_with_js: vec![], additional_files: files, compression_cb: Some(Box::new(|vec, snapshot_slice| { lzzzz::lz4_hc::compress_to_vec( diff --git a/cli/cache/disk_cache.rs b/cli/cache/disk_cache.rs index 81379ac94a..60e353d852 100644 --- a/cli/cache/disk_cache.rs +++ b/cli/cache/disk_cache.rs @@ -1,7 +1,8 @@ // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. -use crate::fs_util; -use crate::http_cache::url_to_filename; +use super::http_cache::url_to_filename; +use super::CACHE_PERM; +use crate::util::fs::atomic_write_file; use deno_core::url::Host; use deno_core::url::Url; @@ -144,7 +145,7 @@ impl DiskCache { Some(parent) => self.ensure_dir_exists(parent), None => Ok(()), }?; - fs_util::atomic_write_file(&path, data, crate::http_cache::CACHE_PERM) + atomic_write_file(&path, data, CACHE_PERM) .map_err(|e| with_io_context(&e, format!("{:#?}", &path))) } } diff --git a/cli/cache/emit.rs b/cli/cache/emit.rs index b3edcbc692..8595627f82 100644 --- a/cli/cache/emit.rs +++ b/cli/cache/emit.rs @@ -44,7 +44,7 @@ impl EmitCache { pub fn get_emit_code( &self, specifier: &ModuleSpecifier, - expected_source_hash: Option, + expected_source_hash: u64, ) -> Option { let meta_filename = self.get_meta_filename(specifier)?; let emit_filename = self.get_emit_filename(specifier)?; @@ -52,10 +52,8 @@ impl EmitCache { // load and verify the meta data file is for this source and CLI version let bytes = self.disk_cache.get(&meta_filename).ok()?; let meta: EmitMetadata = serde_json::from_slice(&bytes).ok()?; - if let Some(expected_source_hash) = expected_source_hash { - if meta.source_hash != expected_source_hash.to_string() { - return None; - } + if meta.source_hash != expected_source_hash.to_string() { + return None; } // load and verify the emit is for the meta data @@ -173,31 +171,26 @@ mod test { let specifier2 = ModuleSpecifier::from_file_path(temp_dir.path().join("file2.ts")) .unwrap(); - assert_eq!(cache.get_emit_code(&specifier1, Some(1)), None); + assert_eq!(cache.get_emit_code(&specifier1, 1), None); let emit_code1 = "text1".to_string(); let emit_code2 = "text2".to_string(); cache.set_emit_code(&specifier1, 10, &emit_code1); cache.set_emit_code(&specifier2, 2, &emit_code2); // providing the incorrect source hash - assert_eq!(cache.get_emit_code(&specifier1, Some(5)), None); + assert_eq!(cache.get_emit_code(&specifier1, 5), None); // providing the correct source hash assert_eq!( - cache.get_emit_code(&specifier1, Some(10)), - Some(emit_code1.clone()), - ); - assert_eq!(cache.get_emit_code(&specifier2, Some(2)), Some(emit_code2)); - // providing no hash - assert_eq!( - cache.get_emit_code(&specifier1, None), + cache.get_emit_code(&specifier1, 10), Some(emit_code1.clone()), ); + assert_eq!(cache.get_emit_code(&specifier2, 2), Some(emit_code2)); // try changing the cli version (should not load previous ones) let cache = EmitCache { disk_cache: disk_cache.clone(), cli_version: "2.0.0".to_string(), }; - assert_eq!(cache.get_emit_code(&specifier1, Some(10)), None); + assert_eq!(cache.get_emit_code(&specifier1, 10), None); cache.set_emit_code(&specifier1, 5, &emit_code1); // recreating the cache should still load the data because the CLI version is the same @@ -205,12 +198,12 @@ mod test { disk_cache, cli_version: "2.0.0".to_string(), }; - assert_eq!(cache.get_emit_code(&specifier1, Some(5)), Some(emit_code1)); + assert_eq!(cache.get_emit_code(&specifier1, 5), Some(emit_code1)); // adding when already exists should not cause issue let emit_code3 = "asdf".to_string(); cache.set_emit_code(&specifier1, 20, &emit_code3); - assert_eq!(cache.get_emit_code(&specifier1, Some(5)), None); - assert_eq!(cache.get_emit_code(&specifier1, Some(20)), Some(emit_code3)); + assert_eq!(cache.get_emit_code(&specifier1, 5), None); + assert_eq!(cache.get_emit_code(&specifier1, 20), Some(emit_code3)); } } diff --git a/cli/http_cache.rs b/cli/cache/http_cache.rs similarity index 92% rename from cli/http_cache.rs rename to cli/cache/http_cache.rs index 6cda9f2794..f4cf3ef110 100644 --- a/cli/http_cache.rs +++ b/cli/cache/http_cache.rs @@ -3,8 +3,8 @@ //! as defined in RFC 7234 (). //! Currently it's a very simplified version to fulfill Deno needs //! at hand. -use crate::fs_util; use crate::http_util::HeadersMap; +use crate::util; use deno_core::error::generic_error; use deno_core::error::AnyError; use deno_core::serde::Deserialize; @@ -19,7 +19,7 @@ use std::path::Path; use std::path::PathBuf; use std::time::SystemTime; -pub const CACHE_PERM: u32 = 0o644; +use super::CACHE_PERM; /// Turn base of url (scheme, hostname, port) into a valid filename. /// This method replaces port part with a special string token (because @@ -68,31 +68,32 @@ pub fn url_to_filename(url: &Url) -> Option { // NOTE: fragment is omitted on purpose - it's not taken into // account when caching - it denotes parts of webpage, which // in case of static resources doesn't make much sense - let hashed_filename = crate::checksum::gen(&[rest_str.as_bytes()]); + let hashed_filename = util::checksum::gen(&[rest_str.as_bytes()]); cache_filename.push(hashed_filename); Some(cache_filename) } +/// Cached metadata about a url. #[derive(Serialize, Deserialize)] -pub struct Metadata { +pub struct CachedUrlMetadata { pub headers: HeadersMap, pub url: String, #[serde(default = "SystemTime::now")] pub now: SystemTime, } -impl Metadata { +impl CachedUrlMetadata { pub fn write(&self, cache_filename: &Path) -> Result<(), AnyError> { let metadata_filename = Self::filename(cache_filename); let json = serde_json::to_string_pretty(self)?; - fs_util::atomic_write_file(&metadata_filename, json, CACHE_PERM)?; + util::fs::atomic_write_file(&metadata_filename, json, CACHE_PERM)?; Ok(()) } - pub fn read(cache_filename: &Path) -> Result { - let metadata_filename = Metadata::filename(cache_filename); + pub fn read(cache_filename: &Path) -> Result { + let metadata_filename = Self::filename(cache_filename); let metadata = fs::read_to_string(metadata_filename)?; - let metadata: Metadata = serde_json::from_str(&metadata)?; + let metadata: Self = serde_json::from_str(&metadata)?; Ok(metadata) } @@ -149,10 +150,10 @@ impl HttpCache { url_to_filename(url) .ok_or_else(|| generic_error("Can't convert url to filename."))?, ); - let metadata_filename = Metadata::filename(&cache_filename); + let metadata_filename = CachedUrlMetadata::filename(&cache_filename); let file = File::open(cache_filename)?; let metadata = fs::read_to_string(metadata_filename)?; - let metadata: Metadata = serde_json::from_str(&metadata)?; + let metadata: CachedUrlMetadata = serde_json::from_str(&metadata)?; Ok((file, metadata.headers, metadata.now)) } @@ -172,9 +173,9 @@ impl HttpCache { .expect("Cache filename should have a parent dir"); self.ensure_dir_exists(parent_filename)?; // Cache content - fs_util::atomic_write_file(&cache_filename, content, CACHE_PERM)?; + util::fs::atomic_write_file(&cache_filename, content, CACHE_PERM)?; - let metadata = Metadata { + let metadata = CachedUrlMetadata { now: SystemTime::now(), url: url.to_string(), headers: headers_map, diff --git a/cli/cache/mod.rs b/cli/cache/mod.rs index cf9a4c4413..b0d79400aa 100644 --- a/cli/cache/mod.rs +++ b/cli/cache/mod.rs @@ -19,6 +19,7 @@ mod common; mod deno_dir; mod disk_cache; mod emit; +mod http_cache; mod incremental; mod node; mod parsed_source; @@ -28,10 +29,15 @@ pub use common::FastInsecureHasher; pub use deno_dir::DenoDir; pub use disk_cache::DiskCache; pub use emit::EmitCache; +pub use http_cache::CachedUrlMetadata; +pub use http_cache::HttpCache; pub use incremental::IncrementalCache; pub use node::NodeAnalysisCache; pub use parsed_source::ParsedSourceCache; +/// Permissions used to save a file in the disk caches. +pub const CACHE_PERM: u32 = 0o644; + /// A "wrapper" for the FileFetcher and DiskCache for the Deno CLI that provides /// a concise interface to the DENO_DIR when building module graphs. pub struct FetchCacher { diff --git a/cli/deno_std.rs b/cli/deno_std.rs index 21aa8b6d00..2b114681d3 100644 --- a/cli/deno_std.rs +++ b/cli/deno_std.rs @@ -5,7 +5,7 @@ use once_cell::sync::Lazy; // WARNING: Ensure this is the only deno_std version reference as this // is automatically updated by the version bump workflow. -static CURRENT_STD_URL_STR: &str = "https://deno.land/std@0.166.0/"; +static CURRENT_STD_URL_STR: &str = "https://deno.land/std@0.167.0/"; pub static CURRENT_STD_URL: Lazy = Lazy::new(|| Url::parse(CURRENT_STD_URL_STR).unwrap()); diff --git a/cli/emit.rs b/cli/emit.rs index 3bf56fae69..ee591b2a19 100644 --- a/cli/emit.rs +++ b/cli/emit.rs @@ -12,7 +12,7 @@ use std::sync::Arc; /// A hashing function that takes the source code and emit options /// hash then generates a string hash which can be stored to /// determine if the cached emit is valid or not. -fn get_source_hash(source_text: &str, emit_options_hash: u64) -> u64 { +pub fn get_source_hash(source_text: &str, emit_options_hash: u64) -> u64 { FastInsecureHasher::new() .write_str(source_text) .write_u64(emit_options_hash) @@ -30,9 +30,7 @@ pub fn emit_parsed_source( ) -> Result { let source_hash = get_source_hash(source, emit_config_hash); - if let Some(emit_code) = - emit_cache.get_emit_code(specifier, Some(source_hash)) - { + if let Some(emit_code) = emit_cache.get_emit_code(specifier, source_hash) { Ok(emit_code) } else { // this will use a cached version if it exists diff --git a/cli/errors.rs b/cli/errors.rs index 2b5d195035..eb6667bbea 100644 --- a/cli/errors.rs +++ b/cli/errors.rs @@ -26,8 +26,7 @@ fn get_diagnostic_class(_: &Diagnostic) -> &'static str { fn get_module_graph_error_class(err: &ModuleGraphError) -> &'static str { match err { ModuleGraphError::LoadingErr(_, err) => get_error_class_name(err.as_ref()), - ModuleGraphError::InvalidSource(_, _) - | ModuleGraphError::InvalidTypeAssertion { .. } => "SyntaxError", + ModuleGraphError::InvalidTypeAssertion { .. } => "SyntaxError", ModuleGraphError::ParseErr(_, diagnostic) => { get_diagnostic_class(diagnostic) } diff --git a/cli/file_fetcher.rs b/cli/file_fetcher.rs index b9a91d41a0..12f39c7e30 100644 --- a/cli/file_fetcher.rs +++ b/cli/file_fetcher.rs @@ -1,18 +1,18 @@ // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. +use crate::args::CacheSetting; use crate::auth_tokens::AuthTokens; +use crate::cache::HttpCache; use crate::colors; -use crate::http_cache::HttpCache; use crate::http_util::CacheSemantics; use crate::http_util::FetchOnceArgs; use crate::http_util::FetchOnceResult; use crate::http_util::HttpClient; -use crate::progress_bar::ProgressBar; -use crate::text_encoding; +use crate::util::progress_bar::ProgressBar; +use crate::util::text_encoding; use data_url::DataUrl; use deno_ast::MediaType; -use deno_core::anyhow::anyhow; use deno_core::error::custom_error; use deno_core::error::generic_error; use deno_core::error::uri_error; @@ -21,11 +21,6 @@ use deno_core::futures; use deno_core::futures::future::FutureExt; use deno_core::parking_lot::Mutex; use deno_core::ModuleSpecifier; -use deno_runtime::deno_tls::rustls; -use deno_runtime::deno_tls::rustls::RootCertStore; -use deno_runtime::deno_tls::rustls_native_certs::load_native_certs; -use deno_runtime::deno_tls::rustls_pemfile; -use deno_runtime::deno_tls::webpki_roots; use deno_runtime::deno_web::BlobStore; use deno_runtime::permissions::Permissions; use log::debug; @@ -34,7 +29,6 @@ use std::collections::HashMap; use std::env; use std::fs; use std::future::Future; -use std::io::BufReader; use std::io::Read; use std::path::PathBuf; use std::pin::Pin; @@ -82,86 +76,6 @@ impl FileCache { } } -/// Indicates how cached source files should be handled. -#[derive(Debug, Clone, Eq, PartialEq)] -pub enum CacheSetting { - /// Only the cached files should be used. Any files not in the cache will - /// error. This is the equivalent of `--cached-only` in the CLI. - Only, - /// No cached source files should be used, and all files should be reloaded. - /// This is the equivalent of `--reload` in the CLI. - ReloadAll, - /// Only some cached resources should be used. This is the equivalent of - /// `--reload=https://deno.land/std` or - /// `--reload=https://deno.land/std,https://deno.land/x/example`. - ReloadSome(Vec), - /// The usability of a cached value is determined by analyzing the cached - /// headers and other metadata associated with a cached response, reloading - /// any cached "non-fresh" cached responses. - RespectHeaders, - /// The cached source files should be used for local modules. This is the - /// default behavior of the CLI. - Use, -} - -impl CacheSetting { - /// Returns if the cache should be used for a given specifier. - pub fn should_use( - &self, - specifier: &ModuleSpecifier, - http_cache: &HttpCache, - ) -> bool { - match self { - CacheSetting::ReloadAll => false, - CacheSetting::Use | CacheSetting::Only => true, - CacheSetting::RespectHeaders => { - if let Ok((_, headers, cache_time)) = http_cache.get(specifier) { - let cache_semantics = - CacheSemantics::new(headers, cache_time, SystemTime::now()); - cache_semantics.should_use() - } else { - false - } - } - CacheSetting::ReloadSome(list) => { - let mut url = specifier.clone(); - url.set_fragment(None); - if list.contains(&url.as_str().to_string()) { - return false; - } - url.set_query(None); - let mut path = PathBuf::from(url.as_str()); - loop { - if list.contains(&path.to_str().unwrap().to_string()) { - return false; - } - if !path.pop() { - break; - } - } - true - } - } - } - - pub fn should_use_for_npm_package(&self, package_name: &str) -> bool { - match self { - CacheSetting::ReloadAll => false, - CacheSetting::ReloadSome(list) => { - if list.contains(&"npm:".to_string()) { - return false; - } - let specifier = format!("npm:{}", package_name); - if list.contains(&specifier) { - return false; - } - true - } - _ => true, - } - } -} - /// Fetch a source file from the local file system. fn fetch_local(specifier: &ModuleSpecifier) -> Result { let local = specifier.to_file_path().map_err(|_| { @@ -182,80 +96,6 @@ fn fetch_local(specifier: &ModuleSpecifier) -> Result { }) } -/// Create and populate a root cert store based on the passed options and -/// environment. -pub fn get_root_cert_store( - maybe_root_path: Option, - maybe_ca_stores: Option>, - maybe_ca_file: Option, -) -> Result { - let mut root_cert_store = RootCertStore::empty(); - let ca_stores: Vec = maybe_ca_stores - .or_else(|| { - let env_ca_store = env::var("DENO_TLS_CA_STORE").ok()?; - Some( - env_ca_store - .split(',') - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) - .collect(), - ) - }) - .unwrap_or_else(|| vec!["mozilla".to_string()]); - - for store in ca_stores.iter() { - match store.as_str() { - "mozilla" => { - root_cert_store.add_server_trust_anchors( - webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| { - rustls::OwnedTrustAnchor::from_subject_spki_name_constraints( - ta.subject, - ta.spki, - ta.name_constraints, - ) - }), - ); - } - "system" => { - let roots = load_native_certs().expect("could not load platform certs"); - for root in roots { - root_cert_store - .add(&rustls::Certificate(root.0)) - .expect("Failed to add platform cert to root cert store"); - } - } - _ => { - return Err(anyhow!("Unknown certificate store \"{}\" specified (allowed: \"system,mozilla\")", store)); - } - } - } - - let ca_file = maybe_ca_file.or_else(|| env::var("DENO_CERT").ok()); - if let Some(ca_file) = ca_file { - let ca_file = if let Some(root) = &maybe_root_path { - root.join(&ca_file) - } else { - PathBuf::from(ca_file) - }; - let certfile = fs::File::open(&ca_file)?; - let mut reader = BufReader::new(certfile); - - match rustls_pemfile::certs(&mut reader) { - Ok(certs) => { - root_cert_store.add_parsable_certificates(&certs); - } - Err(e) => { - return Err(anyhow!( - "Unable to add pem file to certificate store: {}", - e - )); - } - } - } - - Ok(root_cert_store) -} - /// Returns the decoded body and content-type of a provided /// data URL. pub fn get_source_from_data_url( @@ -571,7 +411,7 @@ impl FileFetcher { return futures::future::err(err).boxed(); } - if self.cache_setting.should_use(specifier, &self.http_cache) { + if self.should_use_cache(specifier) { match self.fetch_cached(specifier, redirect_limit) { Ok(Some(file)) => { return futures::future::ok(file).boxed(); @@ -654,6 +494,41 @@ impl FileFetcher { .boxed() } + /// Returns if the cache should be used for a given specifier. + fn should_use_cache(&self, specifier: &ModuleSpecifier) -> bool { + match &self.cache_setting { + CacheSetting::ReloadAll => false, + CacheSetting::Use | CacheSetting::Only => true, + CacheSetting::RespectHeaders => { + if let Ok((_, headers, cache_time)) = self.http_cache.get(specifier) { + let cache_semantics = + CacheSemantics::new(headers, cache_time, SystemTime::now()); + cache_semantics.should_use() + } else { + false + } + } + CacheSetting::ReloadSome(list) => { + let mut url = specifier.clone(); + url.set_fragment(None); + if list.contains(&url.as_str().to_string()) { + return false; + } + url.set_query(None); + let mut path = PathBuf::from(url.as_str()); + loop { + if list.contains(&path.to_str().unwrap().to_string()) { + return false; + } + if !path.pop() { + break; + } + } + true + } + } + } + /// Fetch a source file and asynchronously return it. pub async fn fetch( &self, @@ -754,6 +629,7 @@ impl FileFetcher { #[cfg(test)] mod tests { + use crate::cache::CachedUrlMetadata; use crate::http_util::HttpClient; use super::*; @@ -1175,8 +1051,7 @@ mod tests { .http_cache .get_cache_filename(&specifier) .unwrap(); - let mut metadata = - crate::http_cache::Metadata::read(&cache_filename).unwrap(); + let mut metadata = CachedUrlMetadata::read(&cache_filename).unwrap(); metadata.headers = HashMap::new(); metadata .headers @@ -1265,8 +1140,7 @@ mod tests { .await; assert!(result.is_ok()); - let metadata_filename = - crate::http_cache::Metadata::filename(&cache_filename); + let metadata_filename = CachedUrlMetadata::filename(&cache_filename); let metadata_file = fs::File::open(metadata_filename).unwrap(); let metadata_file_metadata = metadata_file.metadata().unwrap(); let metadata_file_modified_01 = metadata_file_metadata.modified().unwrap(); @@ -1285,8 +1159,7 @@ mod tests { .await; assert!(result.is_ok()); - let metadata_filename = - crate::http_cache::Metadata::filename(&cache_filename); + let metadata_filename = CachedUrlMetadata::filename(&cache_filename); let metadata_file = fs::File::open(metadata_filename).unwrap(); let metadata_file_metadata = metadata_file.metadata().unwrap(); let metadata_file_modified_02 = metadata_file_metadata.modified().unwrap(); @@ -1438,7 +1311,7 @@ mod tests { assert!(result.is_ok()); let metadata_filename = - crate::http_cache::Metadata::filename(&redirected_cache_filename); + CachedUrlMetadata::filename(&redirected_cache_filename); let metadata_file = fs::File::open(metadata_filename).unwrap(); let metadata_file_metadata = metadata_file.metadata().unwrap(); let metadata_file_modified_01 = metadata_file_metadata.modified().unwrap(); @@ -1458,7 +1331,7 @@ mod tests { assert!(result.is_ok()); let metadata_filename = - crate::http_cache::Metadata::filename(&redirected_cache_filename); + CachedUrlMetadata::filename(&redirected_cache_filename); let metadata_file = fs::File::open(metadata_filename).unwrap(); let metadata_file_metadata = metadata_file.metadata().unwrap(); let metadata_file_modified_02 = metadata_file_metadata.modified().unwrap(); diff --git a/cli/fs_util.rs b/cli/fs_util.rs deleted file mode 100644 index a27586da20..0000000000 --- a/cli/fs_util.rs +++ /dev/null @@ -1,1209 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use deno_core::anyhow::Context; -use deno_core::error::uri_error; -use deno_core::error::AnyError; -pub use deno_core::normalize_path; -use deno_core::ModuleSpecifier; -use deno_runtime::deno_crypto::rand; -use deno_runtime::deno_node::PathClean; -use std::borrow::Cow; -use std::env::current_dir; -use std::fs::OpenOptions; -use std::io::Error; -use std::io::ErrorKind; -use std::io::Write; -use std::path::Path; -use std::path::PathBuf; -use std::time::Duration; -use walkdir::WalkDir; - -pub fn atomic_write_file>( - filename: &Path, - data: T, - mode: u32, -) -> std::io::Result<()> { - let rand: String = (0..4) - .map(|_| format!("{:02x}", rand::random::())) - .collect(); - let extension = format!("{}.tmp", rand); - let tmp_file = filename.with_extension(extension); - write_file(&tmp_file, data, mode)?; - std::fs::rename(tmp_file, filename)?; - Ok(()) -} - -pub fn write_file>( - filename: &Path, - data: T, - mode: u32, -) -> std::io::Result<()> { - write_file_2(filename, data, true, mode, true, false) -} - -pub fn write_file_2>( - filename: &Path, - data: T, - update_mode: bool, - mode: u32, - is_create: bool, - is_append: bool, -) -> std::io::Result<()> { - let mut file = OpenOptions::new() - .read(false) - .write(true) - .append(is_append) - .truncate(!is_append) - .create(is_create) - .open(filename)?; - - if update_mode { - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mode = mode & 0o777; - let permissions = PermissionsExt::from_mode(mode); - file.set_permissions(permissions)?; - } - #[cfg(not(unix))] - let _ = mode; - } - - file.write_all(data.as_ref()) -} - -/// Similar to `std::fs::canonicalize()` but strips UNC prefixes on Windows. -pub fn canonicalize_path(path: &Path) -> Result { - let path = path.canonicalize()?; - #[cfg(windows)] - return Ok(strip_unc_prefix(path)); - #[cfg(not(windows))] - return Ok(path); -} - -/// Canonicalizes a path which might be non-existent by going up the -/// ancestors until it finds a directory that exists, canonicalizes -/// that path, then adds back the remaining path components. -/// -/// Note: When using this, you should be aware that a symlink may -/// subsequently be created along this path by some other code. -pub fn canonicalize_path_maybe_not_exists( - path: &Path, -) -> Result { - let path = path.to_path_buf().clean(); - let mut path = path.as_path(); - let mut names_stack = Vec::new(); - loop { - match canonicalize_path(path) { - Ok(mut canonicalized_path) => { - for name in names_stack.into_iter().rev() { - canonicalized_path = canonicalized_path.join(name); - } - return Ok(canonicalized_path); - } - Err(err) if err.kind() == ErrorKind::NotFound => { - names_stack.push(path.file_name().unwrap()); - path = path.parent().unwrap(); - } - Err(err) => return Err(err), - } - } -} - -#[cfg(windows)] -fn strip_unc_prefix(path: PathBuf) -> PathBuf { - use std::path::Component; - use std::path::Prefix; - - let mut components = path.components(); - match components.next() { - Some(Component::Prefix(prefix)) => { - match prefix.kind() { - // \\?\device - Prefix::Verbatim(device) => { - let mut path = PathBuf::new(); - path.push(format!(r"\\{}\", device.to_string_lossy())); - path.extend(components.filter(|c| !matches!(c, Component::RootDir))); - path - } - // \\?\c:\path - Prefix::VerbatimDisk(_) => { - let mut path = PathBuf::new(); - path.push(prefix.as_os_str().to_string_lossy().replace(r"\\?\", "")); - path.extend(components); - path - } - // \\?\UNC\hostname\share_name\path - Prefix::VerbatimUNC(hostname, share_name) => { - let mut path = PathBuf::new(); - path.push(format!( - r"\\{}\{}\", - hostname.to_string_lossy(), - share_name.to_string_lossy() - )); - path.extend(components.filter(|c| !matches!(c, Component::RootDir))); - path - } - _ => path, - } - } - _ => path, - } -} - -pub fn resolve_from_cwd(path: &Path) -> Result { - let resolved_path = if path.is_absolute() { - path.to_owned() - } else { - let cwd = - current_dir().context("Failed to get current working directory")?; - cwd.join(path) - }; - - Ok(normalize_path(&resolved_path)) -} - -/// Checks if the path has extension Deno supports. -pub fn is_supported_ext(path: &Path) -> bool { - if let Some(ext) = get_extension(path) { - matches!( - ext.as_str(), - "ts" | "tsx" | "js" | "jsx" | "mjs" | "mts" | "cjs" | "cts" - ) - } else { - false - } -} - -/// Checks if the path has a basename and extension Deno supports for tests. -pub fn is_supported_test_path(path: &Path) -> bool { - if let Some(name) = path.file_stem() { - let basename = name.to_string_lossy(); - (basename.ends_with("_test") - || basename.ends_with(".test") - || basename == "test") - && is_supported_ext(path) - } else { - false - } -} - -/// Checks if the path has a basename and extension Deno supports for benches. -pub fn is_supported_bench_path(path: &Path) -> bool { - if let Some(name) = path.file_stem() { - let basename = name.to_string_lossy(); - (basename.ends_with("_bench") - || basename.ends_with(".bench") - || basename == "bench") - && is_supported_ext(path) - } else { - false - } -} - -/// Checks if the path has an extension Deno supports for tests. -pub fn is_supported_test_ext(path: &Path) -> bool { - if let Some(ext) = get_extension(path) { - matches!( - ext.as_str(), - "ts" - | "tsx" - | "js" - | "jsx" - | "mjs" - | "mts" - | "cjs" - | "cts" - | "md" - | "mkd" - | "mkdn" - | "mdwn" - | "mdown" - | "markdown" - ) - } else { - false - } -} - -/// Get the extension of a file in lowercase. -pub fn get_extension(file_path: &Path) -> Option { - return file_path - .extension() - .and_then(|e| e.to_str()) - .map(|e| e.to_lowercase()); -} - -/// Collects file paths that satisfy the given predicate, by recursively walking `files`. -/// If the walker visits a path that is listed in `ignore`, it skips descending into the directory. -pub fn collect_files

( - files: &[PathBuf], - ignore: &[PathBuf], - predicate: P, -) -> Result, AnyError> -where - P: Fn(&Path) -> bool, -{ - let mut target_files = Vec::new(); - - // retain only the paths which exist and ignore the rest - let canonicalized_ignore: Vec = ignore - .iter() - .filter_map(|i| canonicalize_path(i).ok()) - .collect(); - - for file in files { - for entry in WalkDir::new(file) - .into_iter() - .filter_entry(|e| { - canonicalize_path(e.path()).map_or(false, |c| { - !canonicalized_ignore.iter().any(|i| c.starts_with(i)) - }) - }) - .filter_map(|e| match e { - Ok(e) if !e.file_type().is_dir() && predicate(e.path()) => Some(e), - _ => None, - }) - { - target_files.push(canonicalize_path(entry.path())?) - } - } - - Ok(target_files) -} - -/// Collects module specifiers that satisfy the given predicate as a file path, by recursively walking `include`. -/// Specifiers that start with http and https are left intact. -pub fn collect_specifiers

( - include: Vec, - ignore: &[PathBuf], - predicate: P, -) -> Result, AnyError> -where - P: Fn(&Path) -> bool, -{ - let mut prepared = vec![]; - - let root_path = current_dir()?; - for path in include { - let lowercase_path = path.to_lowercase(); - if lowercase_path.starts_with("http://") - || lowercase_path.starts_with("https://") - { - let url = ModuleSpecifier::parse(&path)?; - prepared.push(url); - continue; - } - - let p = if lowercase_path.starts_with("file://") { - specifier_to_file_path(&ModuleSpecifier::parse(&path)?)? - } else { - root_path.join(path) - }; - let p = normalize_path(&p); - if p.is_dir() { - let test_files = collect_files(&[p], ignore, &predicate).unwrap(); - let mut test_files_as_urls = test_files - .iter() - .map(|f| ModuleSpecifier::from_file_path(f).unwrap()) - .collect::>(); - - test_files_as_urls.sort(); - prepared.extend(test_files_as_urls); - } else { - let url = ModuleSpecifier::from_file_path(p).unwrap(); - prepared.push(url); - } - } - - Ok(prepared) -} - -/// Asynchronously removes a directory and all its descendants, but does not error -/// when the directory does not exist. -pub async fn remove_dir_all_if_exists(path: &Path) -> std::io::Result<()> { - let result = tokio::fs::remove_dir_all(path).await; - match result { - Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), - _ => result, - } -} - -/// Copies a directory to another directory. -/// -/// Note: Does not handle symlinks. -pub fn copy_dir_recursive(from: &Path, to: &Path) -> Result<(), AnyError> { - std::fs::create_dir_all(to) - .with_context(|| format!("Creating {}", to.display()))?; - let read_dir = std::fs::read_dir(from) - .with_context(|| format!("Reading {}", from.display()))?; - - for entry in read_dir { - let entry = entry?; - let file_type = entry.file_type()?; - let new_from = from.join(entry.file_name()); - let new_to = to.join(entry.file_name()); - - if file_type.is_dir() { - copy_dir_recursive(&new_from, &new_to).with_context(|| { - format!("Dir {} to {}", new_from.display(), new_to.display()) - })?; - } else if file_type.is_file() { - std::fs::copy(&new_from, &new_to).with_context(|| { - format!("Copying {} to {}", new_from.display(), new_to.display()) - })?; - } - } - - Ok(()) -} - -/// Hardlinks the files in one directory to another directory. -/// -/// Note: Does not handle symlinks. -pub fn hard_link_dir_recursive(from: &Path, to: &Path) -> Result<(), AnyError> { - std::fs::create_dir_all(to) - .with_context(|| format!("Creating {}", to.display()))?; - let read_dir = std::fs::read_dir(from) - .with_context(|| format!("Reading {}", from.display()))?; - - for entry in read_dir { - let entry = entry?; - let file_type = entry.file_type()?; - let new_from = from.join(entry.file_name()); - let new_to = to.join(entry.file_name()); - - if file_type.is_dir() { - hard_link_dir_recursive(&new_from, &new_to).with_context(|| { - format!("Dir {} to {}", new_from.display(), new_to.display()) - })?; - } else if file_type.is_file() { - // note: chance for race conditions here between attempting to create, - // then removing, then attempting to create. There doesn't seem to be - // a way to hard link with overwriting in Rust, but maybe there is some - // way with platform specific code. The workaround here is to handle - // scenarios where something else might create or remove files. - if let Err(err) = std::fs::hard_link(&new_from, &new_to) { - if err.kind() == ErrorKind::AlreadyExists { - if let Err(err) = std::fs::remove_file(&new_to) { - if err.kind() == ErrorKind::NotFound { - // Assume another process/thread created this hard link to the file we are wanting - // to remove then sleep a little bit to let the other process/thread move ahead - // faster to reduce contention. - std::thread::sleep(Duration::from_millis(10)); - } else { - return Err(err).with_context(|| { - format!( - "Removing file to hard link {} to {}", - new_from.display(), - new_to.display() - ) - }); - } - } - - // Always attempt to recreate the hardlink. In contention scenarios, the other process - // might have been killed or exited after removing the file, but before creating the hardlink - if let Err(err) = std::fs::hard_link(&new_from, &new_to) { - // Assume another process/thread created this hard link to the file we are wanting - // to now create then sleep a little bit to let the other process/thread move ahead - // faster to reduce contention. - if err.kind() == ErrorKind::AlreadyExists { - std::thread::sleep(Duration::from_millis(10)); - } else { - return Err(err).with_context(|| { - format!( - "Hard linking {} to {}", - new_from.display(), - new_to.display() - ) - }); - } - } - } else { - return Err(err).with_context(|| { - format!( - "Hard linking {} to {}", - new_from.display(), - new_to.display() - ) - }); - } - } - } - } - - Ok(()) -} - -pub fn symlink_dir(oldpath: &Path, newpath: &Path) -> Result<(), AnyError> { - let err_mapper = |err: Error| { - Error::new( - err.kind(), - format!( - "{}, symlink '{}' -> '{}'", - err, - oldpath.display(), - newpath.display() - ), - ) - }; - #[cfg(unix)] - { - use std::os::unix::fs::symlink; - symlink(oldpath, newpath).map_err(err_mapper)?; - } - #[cfg(not(unix))] - { - use std::os::windows::fs::symlink_dir; - symlink_dir(oldpath, newpath).map_err(err_mapper)?; - } - Ok(()) -} - -/// Attempts to convert a specifier to a file path. By default, uses the Url -/// crate's `to_file_path()` method, but falls back to try and resolve unix-style -/// paths on Windows. -pub fn specifier_to_file_path( - specifier: &ModuleSpecifier, -) -> Result { - let result = if cfg!(windows) { - match specifier.to_file_path() { - Ok(path) => Ok(path), - Err(()) => { - // This might be a unix-style path which is used in the tests even on Windows. - // Attempt to see if we can convert it to a `PathBuf`. This code should be removed - // once/if https://github.com/servo/rust-url/issues/730 is implemented. - if specifier.scheme() == "file" - && specifier.host().is_none() - && specifier.port().is_none() - && specifier.path_segments().is_some() - { - let path_str = specifier.path(); - match String::from_utf8( - percent_encoding::percent_decode(path_str.as_bytes()).collect(), - ) { - Ok(path_str) => Ok(PathBuf::from(path_str)), - Err(_) => Err(()), - } - } else { - Err(()) - } - } - } - } else { - specifier.to_file_path() - }; - match result { - Ok(path) => Ok(path), - Err(()) => Err(uri_error(format!( - "Invalid file path.\n Specifier: {}", - specifier - ))), - } -} - -/// Ensures a specifier that will definitely be a directory has a trailing slash. -pub fn ensure_directory_specifier( - mut specifier: ModuleSpecifier, -) -> ModuleSpecifier { - let path = specifier.path(); - if !path.ends_with('/') { - let new_path = format!("{}/", path); - specifier.set_path(&new_path); - } - specifier -} - -/// Gets the parent of this module specifier. -pub fn specifier_parent(specifier: &ModuleSpecifier) -> ModuleSpecifier { - let mut specifier = specifier.clone(); - // don't use specifier.segments() because it will strip the leading slash - let mut segments = specifier.path().split('/').collect::>(); - if segments.iter().all(|s| s.is_empty()) { - return specifier; - } - if let Some(last) = segments.last() { - if last.is_empty() { - segments.pop(); - } - segments.pop(); - let new_path = format!("{}/", segments.join("/")); - specifier.set_path(&new_path); - } - specifier -} - -/// `from.make_relative(to)` but with fixes. -pub fn relative_specifier( - from: &ModuleSpecifier, - to: &ModuleSpecifier, -) -> Option { - let is_dir = to.path().ends_with('/'); - - if is_dir && from == to { - return Some("./".to_string()); - } - - // workaround using parent directory until https://github.com/servo/rust-url/pull/754 is merged - let from = if !from.path().ends_with('/') { - if let Some(end_slash) = from.path().rfind('/') { - let mut new_from = from.clone(); - new_from.set_path(&from.path()[..end_slash + 1]); - Cow::Owned(new_from) - } else { - Cow::Borrowed(from) - } - } else { - Cow::Borrowed(from) - }; - - // workaround for url crate not adding a trailing slash for a directory - // it seems to be fixed once a version greater than 2.2.2 is released - let mut text = from.make_relative(to)?; - if is_dir && !text.ends_with('/') && to.query().is_none() { - text.push('/'); - } - - Some(if text.starts_with("../") || text.starts_with("./") { - text - } else { - format!("./{}", text) - }) -} - -/// This function checks if input path has trailing slash or not. If input path -/// has trailing slash it will return true else it will return false. -pub fn path_has_trailing_slash(path: &Path) -> bool { - if let Some(path_str) = path.to_str() { - if cfg!(windows) { - path_str.ends_with('\\') - } else { - path_str.ends_with('/') - } - } else { - false - } -} - -/// Gets a path with the specified file stem suffix. -/// -/// Ex. `file.ts` with suffix `_2` returns `file_2.ts` -pub fn path_with_stem_suffix(path: &Path, suffix: &str) -> PathBuf { - if let Some(file_name) = path.file_name().map(|f| f.to_string_lossy()) { - if let Some(file_stem) = path.file_stem().map(|f| f.to_string_lossy()) { - if let Some(ext) = path.extension().map(|f| f.to_string_lossy()) { - return if file_stem.to_lowercase().ends_with(".d") { - path.with_file_name(format!( - "{}{}.{}.{}", - &file_stem[..file_stem.len() - ".d".len()], - suffix, - // maintain casing - &file_stem[file_stem.len() - "d".len()..], - ext - )) - } else { - path.with_file_name(format!("{}{}.{}", file_stem, suffix, ext)) - }; - } - } - - path.with_file_name(format!("{}{}", file_name, suffix)) - } else { - path.with_file_name(suffix) - } -} - -/// Gets if the provided character is not supported on all -/// kinds of file systems. -pub fn is_banned_path_char(c: char) -> bool { - matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*') -} - -/// Gets a safe local directory name for the provided url. -/// -/// For example: -/// https://deno.land:8080/path -> deno.land_8080/path -pub fn root_url_to_safe_local_dirname(root: &ModuleSpecifier) -> PathBuf { - fn sanitize_segment(text: &str) -> String { - text - .chars() - .map(|c| if is_banned_segment_char(c) { '_' } else { c }) - .collect() - } - - fn is_banned_segment_char(c: char) -> bool { - matches!(c, '/' | '\\') || is_banned_path_char(c) - } - - let mut result = String::new(); - if let Some(domain) = root.domain() { - result.push_str(&sanitize_segment(domain)); - } - if let Some(port) = root.port() { - if !result.is_empty() { - result.push('_'); - } - result.push_str(&port.to_string()); - } - let mut result = PathBuf::from(result); - if let Some(segments) = root.path_segments() { - for segment in segments.filter(|s| !s.is_empty()) { - result = result.join(sanitize_segment(segment)); - } - } - - result -} - -/// Gets the total size (in bytes) of a directory. -pub fn dir_size(path: &Path) -> std::io::Result { - let entries = std::fs::read_dir(path)?; - let mut total = 0; - for entry in entries { - let entry = entry?; - total += match entry.metadata()? { - data if data.is_dir() => dir_size(&entry.path())?, - data => data.len(), - }; - } - Ok(total) -} - -#[cfg(test)] -mod tests { - use super::*; - use test_util::TempDir; - - #[test] - fn resolve_from_cwd_child() { - let cwd = current_dir().unwrap(); - assert_eq!(resolve_from_cwd(Path::new("a")).unwrap(), cwd.join("a")); - } - - #[test] - fn resolve_from_cwd_dot() { - let cwd = current_dir().unwrap(); - assert_eq!(resolve_from_cwd(Path::new(".")).unwrap(), cwd); - } - - #[test] - fn resolve_from_cwd_parent() { - let cwd = current_dir().unwrap(); - assert_eq!(resolve_from_cwd(Path::new("a/..")).unwrap(), cwd); - } - - #[test] - fn test_normalize_path() { - assert_eq!(normalize_path(Path::new("a/../b")), PathBuf::from("b")); - assert_eq!(normalize_path(Path::new("a/./b/")), PathBuf::from("a/b/")); - assert_eq!( - normalize_path(Path::new("a/./b/../c")), - PathBuf::from("a/c") - ); - - if cfg!(windows) { - assert_eq!( - normalize_path(Path::new("C:\\a\\.\\b\\..\\c")), - PathBuf::from("C:\\a\\c") - ); - } - } - - // TODO: Get a good expected value here for Windows. - #[cfg(not(windows))] - #[test] - fn resolve_from_cwd_absolute() { - let expected = Path::new("/a"); - assert_eq!(resolve_from_cwd(expected).unwrap(), expected); - } - - #[test] - fn test_is_supported_ext() { - assert!(!is_supported_ext(Path::new("tests/subdir/redirects"))); - assert!(!is_supported_ext(Path::new("README.md"))); - assert!(is_supported_ext(Path::new("lib/typescript.d.ts"))); - assert!(is_supported_ext(Path::new("testdata/run/001_hello.js"))); - assert!(is_supported_ext(Path::new("testdata/run/002_hello.ts"))); - assert!(is_supported_ext(Path::new("foo.jsx"))); - assert!(is_supported_ext(Path::new("foo.tsx"))); - assert!(is_supported_ext(Path::new("foo.TS"))); - assert!(is_supported_ext(Path::new("foo.TSX"))); - assert!(is_supported_ext(Path::new("foo.JS"))); - assert!(is_supported_ext(Path::new("foo.JSX"))); - assert!(is_supported_ext(Path::new("foo.mjs"))); - assert!(is_supported_ext(Path::new("foo.mts"))); - assert!(is_supported_ext(Path::new("foo.cjs"))); - assert!(is_supported_ext(Path::new("foo.cts"))); - assert!(!is_supported_ext(Path::new("foo.mjsx"))); - } - - #[test] - fn test_is_supported_test_ext() { - assert!(!is_supported_test_ext(Path::new("tests/subdir/redirects"))); - assert!(is_supported_test_ext(Path::new("README.md"))); - assert!(is_supported_test_ext(Path::new("readme.MD"))); - assert!(is_supported_test_ext(Path::new("lib/typescript.d.ts"))); - assert!(is_supported_test_ext(Path::new( - "testdata/run/001_hello.js" - ))); - assert!(is_supported_test_ext(Path::new( - "testdata/run/002_hello.ts" - ))); - assert!(is_supported_test_ext(Path::new("foo.jsx"))); - assert!(is_supported_test_ext(Path::new("foo.tsx"))); - assert!(is_supported_test_ext(Path::new("foo.TS"))); - assert!(is_supported_test_ext(Path::new("foo.TSX"))); - assert!(is_supported_test_ext(Path::new("foo.JS"))); - assert!(is_supported_test_ext(Path::new("foo.JSX"))); - assert!(is_supported_test_ext(Path::new("foo.mjs"))); - assert!(is_supported_test_ext(Path::new("foo.mts"))); - assert!(is_supported_test_ext(Path::new("foo.cjs"))); - assert!(is_supported_test_ext(Path::new("foo.cts"))); - assert!(!is_supported_test_ext(Path::new("foo.mjsx"))); - assert!(!is_supported_test_ext(Path::new("foo.jsonc"))); - assert!(!is_supported_test_ext(Path::new("foo.JSONC"))); - assert!(!is_supported_test_ext(Path::new("foo.json"))); - assert!(!is_supported_test_ext(Path::new("foo.JsON"))); - } - - #[test] - fn test_is_supported_test_path() { - assert!(is_supported_test_path(Path::new( - "tests/subdir/foo_test.ts" - ))); - assert!(is_supported_test_path(Path::new( - "tests/subdir/foo_test.tsx" - ))); - assert!(is_supported_test_path(Path::new( - "tests/subdir/foo_test.js" - ))); - assert!(is_supported_test_path(Path::new( - "tests/subdir/foo_test.jsx" - ))); - assert!(is_supported_test_path(Path::new("bar/foo.test.ts"))); - assert!(is_supported_test_path(Path::new("bar/foo.test.tsx"))); - assert!(is_supported_test_path(Path::new("bar/foo.test.js"))); - assert!(is_supported_test_path(Path::new("bar/foo.test.jsx"))); - assert!(is_supported_test_path(Path::new("foo/bar/test.js"))); - assert!(is_supported_test_path(Path::new("foo/bar/test.jsx"))); - assert!(is_supported_test_path(Path::new("foo/bar/test.ts"))); - assert!(is_supported_test_path(Path::new("foo/bar/test.tsx"))); - assert!(!is_supported_test_path(Path::new("README.md"))); - assert!(!is_supported_test_path(Path::new("lib/typescript.d.ts"))); - assert!(!is_supported_test_path(Path::new("notatest.js"))); - assert!(!is_supported_test_path(Path::new("NotAtest.ts"))); - } - - #[test] - fn test_collect_files() { - fn create_files(dir_path: &Path, files: &[&str]) { - std::fs::create_dir(dir_path).expect("Failed to create directory"); - for f in files { - let path = dir_path.join(f); - std::fs::write(path, "").expect("Failed to create file"); - } - } - - // dir.ts - // ├── a.ts - // ├── b.js - // ├── child - // │ ├── e.mjs - // │ ├── f.mjsx - // │ ├── .foo.TS - // │ └── README.md - // ├── c.tsx - // ├── d.jsx - // └── ignore - // ├── g.d.ts - // └── .gitignore - - let t = TempDir::new(); - - let root_dir_path = t.path().join("dir.ts"); - let root_dir_files = ["a.ts", "b.js", "c.tsx", "d.jsx"]; - create_files(&root_dir_path, &root_dir_files); - - let child_dir_path = root_dir_path.join("child"); - let child_dir_files = ["e.mjs", "f.mjsx", ".foo.TS", "README.md"]; - create_files(&child_dir_path, &child_dir_files); - - let ignore_dir_path = root_dir_path.join("ignore"); - let ignore_dir_files = ["g.d.ts", ".gitignore"]; - create_files(&ignore_dir_path, &ignore_dir_files); - - let result = collect_files(&[root_dir_path], &[ignore_dir_path], |path| { - // exclude dotfiles - path - .file_name() - .and_then(|f| f.to_str()) - .map_or(false, |f| !f.starts_with('.')) - }) - .unwrap(); - let expected = [ - "a.ts", - "b.js", - "e.mjs", - "f.mjsx", - "README.md", - "c.tsx", - "d.jsx", - ]; - for e in expected.iter() { - assert!(result.iter().any(|r| r.ends_with(e))); - } - assert_eq!(result.len(), expected.len()); - } - - #[test] - fn test_collect_specifiers() { - fn create_files(dir_path: &Path, files: &[&str]) { - std::fs::create_dir(dir_path).expect("Failed to create directory"); - for f in files { - let path = dir_path.join(f); - std::fs::write(path, "").expect("Failed to create file"); - } - } - - // dir.ts - // ├── a.ts - // ├── b.js - // ├── child - // │ ├── e.mjs - // │ ├── f.mjsx - // │ ├── .foo.TS - // │ └── README.md - // ├── c.tsx - // ├── d.jsx - // └── ignore - // ├── g.d.ts - // └── .gitignore - - let t = TempDir::new(); - - let root_dir_path = t.path().join("dir.ts"); - let root_dir_files = ["a.ts", "b.js", "c.tsx", "d.jsx"]; - create_files(&root_dir_path, &root_dir_files); - - let child_dir_path = root_dir_path.join("child"); - let child_dir_files = ["e.mjs", "f.mjsx", ".foo.TS", "README.md"]; - create_files(&child_dir_path, &child_dir_files); - - let ignore_dir_path = root_dir_path.join("ignore"); - let ignore_dir_files = ["g.d.ts", ".gitignore"]; - create_files(&ignore_dir_path, &ignore_dir_files); - - let predicate = |path: &Path| { - // exclude dotfiles - path - .file_name() - .and_then(|f| f.to_str()) - .map_or(false, |f| !f.starts_with('.')) - }; - - let result = collect_specifiers( - vec![ - "http://localhost:8080".to_string(), - root_dir_path.to_str().unwrap().to_string(), - "https://localhost:8080".to_string(), - ], - &[ignore_dir_path], - predicate, - ) - .unwrap(); - - let root_dir_url = ModuleSpecifier::from_file_path( - canonicalize_path(&root_dir_path).unwrap(), - ) - .unwrap() - .to_string(); - let expected: Vec = [ - "http://localhost:8080", - &format!("{}/a.ts", root_dir_url), - &format!("{}/b.js", root_dir_url), - &format!("{}/c.tsx", root_dir_url), - &format!("{}/child/README.md", root_dir_url), - &format!("{}/child/e.mjs", root_dir_url), - &format!("{}/child/f.mjsx", root_dir_url), - &format!("{}/d.jsx", root_dir_url), - "https://localhost:8080", - ] - .iter() - .map(|f| ModuleSpecifier::parse(f).unwrap()) - .collect::>(); - - assert_eq!(result, expected); - - let scheme = if cfg!(target_os = "windows") { - "file:///" - } else { - "file://" - }; - let result = collect_specifiers( - vec![format!( - "{}{}", - scheme, - root_dir_path - .join("child") - .to_str() - .unwrap() - .replace('\\', "/") - )], - &[], - predicate, - ) - .unwrap(); - - let expected: Vec = [ - &format!("{}/child/README.md", root_dir_url), - &format!("{}/child/e.mjs", root_dir_url), - &format!("{}/child/f.mjsx", root_dir_url), - ] - .iter() - .map(|f| ModuleSpecifier::parse(f).unwrap()) - .collect::>(); - - assert_eq!(result, expected); - } - - #[cfg(windows)] - #[test] - fn test_strip_unc_prefix() { - run_test(r"C:\", r"C:\"); - run_test(r"C:\test\file.txt", r"C:\test\file.txt"); - - run_test(r"\\?\C:\", r"C:\"); - run_test(r"\\?\C:\test\file.txt", r"C:\test\file.txt"); - - run_test(r"\\.\C:\", r"\\.\C:\"); - run_test(r"\\.\C:\Test\file.txt", r"\\.\C:\Test\file.txt"); - - run_test(r"\\?\UNC\localhost\", r"\\localhost"); - run_test(r"\\?\UNC\localhost\c$\", r"\\localhost\c$"); - run_test( - r"\\?\UNC\localhost\c$\Windows\file.txt", - r"\\localhost\c$\Windows\file.txt", - ); - run_test(r"\\?\UNC\wsl$\deno.json", r"\\wsl$\deno.json"); - - run_test(r"\\?\server1", r"\\server1"); - run_test(r"\\?\server1\e$\", r"\\server1\e$\"); - run_test( - r"\\?\server1\e$\test\file.txt", - r"\\server1\e$\test\file.txt", - ); - - fn run_test(input: &str, expected: &str) { - assert_eq!( - strip_unc_prefix(PathBuf::from(input)), - PathBuf::from(expected) - ); - } - } - - #[test] - fn test_specifier_to_file_path() { - run_success_test("file:///", "/"); - run_success_test("file:///test", "/test"); - run_success_test("file:///dir/test/test.txt", "/dir/test/test.txt"); - run_success_test( - "file:///dir/test%20test/test.txt", - "/dir/test test/test.txt", - ); - - fn run_success_test(specifier: &str, expected_path: &str) { - let result = - specifier_to_file_path(&ModuleSpecifier::parse(specifier).unwrap()) - .unwrap(); - assert_eq!(result, PathBuf::from(expected_path)); - } - } - - #[test] - fn test_ensure_directory_specifier() { - run_test("file:///", "file:///"); - run_test("file:///test", "file:///test/"); - run_test("file:///test/", "file:///test/"); - run_test("file:///test/other", "file:///test/other/"); - run_test("file:///test/other/", "file:///test/other/"); - - fn run_test(specifier: &str, expected: &str) { - let result = - ensure_directory_specifier(ModuleSpecifier::parse(specifier).unwrap()); - assert_eq!(result.to_string(), expected); - } - } - - #[test] - fn test_specifier_parent() { - run_test("file:///", "file:///"); - run_test("file:///test", "file:///"); - run_test("file:///test/", "file:///"); - run_test("file:///test/other", "file:///test/"); - run_test("file:///test/other.txt", "file:///test/"); - run_test("file:///test/other/", "file:///test/"); - - fn run_test(specifier: &str, expected: &str) { - let result = - specifier_parent(&ModuleSpecifier::parse(specifier).unwrap()); - assert_eq!(result.to_string(), expected); - } - } - - #[test] - fn test_relative_specifier() { - let fixtures: Vec<(&str, &str, Option<&str>)> = vec![ - ("file:///from", "file:///to", Some("./to")), - ("file:///from", "file:///from/other", Some("./from/other")), - ("file:///from", "file:///from/other/", Some("./from/other/")), - ("file:///from", "file:///other/from", Some("./other/from")), - ("file:///from/", "file:///other/from", Some("../other/from")), - ("file:///from", "file:///other/from/", Some("./other/from/")), - ( - "file:///from", - "file:///to/other.txt", - Some("./to/other.txt"), - ), - ( - "file:///from/test", - "file:///to/other.txt", - Some("../to/other.txt"), - ), - ( - "file:///from/other.txt", - "file:///to/other.txt", - Some("../to/other.txt"), - ), - ( - "https://deno.land/x/a/b/d.ts", - "https://deno.land/x/a/b/c.ts", - Some("./c.ts"), - ), - ( - "https://deno.land/x/a/b/d.ts", - "https://deno.land/x/a/c.ts", - Some("../c.ts"), - ), - ( - "https://deno.land/x/a/b/d.ts", - "https://deno.land/x/a/b/c/d.ts", - Some("./c/d.ts"), - ), - ( - "https://deno.land/x/a/b/c/", - "https://deno.land/x/a/b/c/d.ts", - Some("./d.ts"), - ), - ( - "https://deno.land/x/a/b/c/", - "https://deno.land/x/a/b/c/d/e.ts", - Some("./d/e.ts"), - ), - ( - "https://deno.land/x/a/b/c/f.ts", - "https://deno.land/x/a/b/c/d/e.ts", - Some("./d/e.ts"), - ), - ( - "https://deno.land/x/a/b/d.ts", - "https://deno.land/x/a/c.ts?foo=bar", - Some("../c.ts?foo=bar"), - ), - ( - "https://deno.land/x/a/b/d.ts?foo=bar", - "https://deno.land/x/a/b/c.ts", - Some("./c.ts"), - ), - ("file:///a/b/d.ts", "file:///a/b/c.ts", Some("./c.ts")), - ("https://deno.land/x/a/b/c.ts", "file:///a/b/c.ts", None), - ( - "https://deno.land/", - "https://deno.land/x/a/b/c.ts", - Some("./x/a/b/c.ts"), - ), - ( - "https://deno.land/x/d/e/f.ts", - "https://deno.land/x/a/b/c.ts", - Some("../../a/b/c.ts"), - ), - ]; - for (from_str, to_str, expected) in fixtures { - let from = ModuleSpecifier::parse(from_str).unwrap(); - let to = ModuleSpecifier::parse(to_str).unwrap(); - let actual = relative_specifier(&from, &to); - assert_eq!( - actual.as_deref(), - expected, - "from: \"{}\" to: \"{}\"", - from_str, - to_str - ); - } - } - - #[test] - fn test_path_has_trailing_slash() { - #[cfg(not(windows))] - { - run_test("/Users/johndoe/Desktop/deno-project/target/", true); - run_test(r"/Users/johndoe/deno-project/target//", true); - run_test("/Users/johndoe/Desktop/deno-project", false); - run_test(r"/Users/johndoe/deno-project\", false); - } - - #[cfg(windows)] - { - run_test(r"C:\test\deno-project\", true); - run_test(r"C:\test\deno-project\\", true); - run_test(r"C:\test\file.txt", false); - run_test(r"C:\test\file.txt/", false); - } - - fn run_test(path_str: &str, expected: bool) { - let path = Path::new(path_str); - let result = path_has_trailing_slash(path); - assert_eq!(result, expected); - } - } - - #[test] - fn test_path_with_stem_suffix() { - assert_eq!( - path_with_stem_suffix(&PathBuf::from("/"), "_2"), - PathBuf::from("/_2") - ); - assert_eq!( - path_with_stem_suffix(&PathBuf::from("/test"), "_2"), - PathBuf::from("/test_2") - ); - assert_eq!( - path_with_stem_suffix(&PathBuf::from("/test.txt"), "_2"), - PathBuf::from("/test_2.txt") - ); - assert_eq!( - path_with_stem_suffix(&PathBuf::from("/test/subdir"), "_2"), - PathBuf::from("/test/subdir_2") - ); - assert_eq!( - path_with_stem_suffix(&PathBuf::from("/test/subdir.other.txt"), "_2"), - PathBuf::from("/test/subdir.other_2.txt") - ); - assert_eq!( - path_with_stem_suffix(&PathBuf::from("/test.d.ts"), "_2"), - PathBuf::from("/test_2.d.ts") - ); - assert_eq!( - path_with_stem_suffix(&PathBuf::from("/test.D.TS"), "_2"), - PathBuf::from("/test_2.D.TS") - ); - assert_eq!( - path_with_stem_suffix(&PathBuf::from("/test.d.mts"), "_2"), - PathBuf::from("/test_2.d.mts") - ); - assert_eq!( - path_with_stem_suffix(&PathBuf::from("/test.d.cts"), "_2"), - PathBuf::from("/test_2.d.cts") - ); - } -} diff --git a/cli/graph_util.rs b/cli/graph_util.rs index 8ffd284b81..7cef4b6f15 100644 --- a/cli/graph_util.rs +++ b/cli/graph_util.rs @@ -1,5 +1,6 @@ // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. +use crate::args::Lockfile; use crate::args::TsTypeLib; use crate::colors; use crate::errors::get_error_class_name; @@ -80,23 +81,23 @@ impl GraphData { let mut has_npm_specifier_in_graph = false; for (specifier, result) in graph.specifiers() { - if NpmPackageReference::from_specifier(&specifier).is_ok() { + if NpmPackageReference::from_specifier(specifier).is_ok() { has_npm_specifier_in_graph = true; continue; } - if !reload && self.modules.contains_key(&specifier) { + if !reload && self.modules.contains_key(specifier) { continue; } - if let Some(found) = graph.redirects.get(&specifier) { + if let Some(found) = graph.redirects.get(specifier) { let module_entry = ModuleEntry::Redirect(found.clone()); self.modules.insert(specifier.clone(), module_entry); continue; } match result { Ok((_, _, media_type)) => { - let module = graph.get(&specifier).unwrap(); + let module = graph.get(specifier).unwrap(); let code = match &module.maybe_source { Some(source) => source.clone(), None => continue, @@ -134,11 +135,11 @@ impl GraphData { checked_libs: Default::default(), maybe_types, }; - self.modules.insert(specifier, module_entry); + self.modules.insert(specifier.clone(), module_entry); } Err(error) => { - let module_entry = ModuleEntry::Error(error); - self.modules.insert(specifier, module_entry); + let module_entry = ModuleEntry::Error(error.clone()); + self.modules.insert(specifier.clone(), module_entry); } } } @@ -475,10 +476,23 @@ pub fn graph_valid( .unwrap() } -/// Calls `graph.lock()` and exits on errors. -pub fn graph_lock_or_exit(graph: &ModuleGraph) { - if let Err(err) = graph.lock() { - log::error!("{} {}", colors::red("error:"), err); - std::process::exit(10); +/// Checks the lockfile against the graph and and exits on errors. +pub fn graph_lock_or_exit(graph: &ModuleGraph, lockfile: &mut Lockfile) { + for module in graph.modules() { + if let Some(source) = &module.maybe_source { + if !lockfile.check_or_insert_remote(module.specifier.as_str(), source) { + let err = format!( + concat!( + "The source code is invalid, as it does not match the expected hash in the lock file.\n", + " Specifier: {}\n", + " Lock file: {}", + ), + module.specifier, + lockfile.filename.display(), + ); + log::error!("{} {}", colors::red("error:"), err); + std::process::exit(10); + } + } } } diff --git a/cli/js/40_testing.js b/cli/js/40_testing.js index 4dd24a2860..3818c36479 100644 --- a/cli/js/40_testing.js +++ b/cli/js/40_testing.js @@ -708,7 +708,7 @@ ); } testDesc.origin = getTestOrigin(); - const jsError = Deno.core.destructureError(new Error()); + const jsError = core.destructureError(new Error()); testDesc.location = { fileName: jsError.frames[1].fileName, lineNumber: jsError.frames[1].lineNumber, @@ -1086,6 +1086,9 @@ } for (const desc of filtered) { + if (ops.op_tests_should_stop()) { + break; + } ops.op_dispatch_test_event({ wait: desc.id }); const earlier = DateNow(); const result = await runTest(desc); @@ -1290,7 +1293,7 @@ stepDesc.sanitizeResources ??= desc.sanitizeResources; stepDesc.sanitizeExit ??= desc.sanitizeExit; stepDesc.origin = getTestOrigin(); - const jsError = Deno.core.destructureError(new Error()); + const jsError = core.destructureError(new Error()); stepDesc.location = { fileName: jsError.frames[1].fileName, lineNumber: jsError.frames[1].lineNumber, diff --git a/cli/lsp/cache.rs b/cli/lsp/cache.rs index c4512a8039..7f7f698718 100644 --- a/cli/lsp/cache.rs +++ b/cli/lsp/cache.rs @@ -1,6 +1,7 @@ // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. -use crate::http_cache; +use crate::cache::CachedUrlMetadata; +use crate::cache::HttpCache; use deno_core::parking_lot::Mutex; use deno_core::ModuleSpecifier; @@ -49,14 +50,14 @@ struct Metadata { #[derive(Debug, Default, Clone)] pub struct CacheMetadata { - cache: http_cache::HttpCache, + cache: HttpCache, metadata: Arc>>, } impl CacheMetadata { pub fn new(location: &Path) -> Self { Self { - cache: http_cache::HttpCache::new(location), + cache: HttpCache::new(location), metadata: Default::default(), } } @@ -87,8 +88,7 @@ impl CacheMetadata { return None; } let cache_filename = self.cache.get_cache_filename(specifier)?; - let specifier_metadata = - http_cache::Metadata::read(&cache_filename).ok()?; + let specifier_metadata = CachedUrlMetadata::read(&cache_filename).ok()?; let values = Arc::new(parse_metadata(&specifier_metadata.headers)); let version = calculate_fs_version(&cache_filename); let mut metadata_map = self.metadata.lock(); @@ -98,7 +98,7 @@ impl CacheMetadata { } pub fn set_location(&mut self, location: &Path) { - self.cache = http_cache::HttpCache::new(location); + self.cache = HttpCache::new(location); self.metadata.lock().clear(); } } diff --git a/cli/lsp/completions.rs b/cli/lsp/completions.rs index 67978fbc98..5e0fad0f43 100644 --- a/cli/lsp/completions.rs +++ b/cli/lsp/completions.rs @@ -7,9 +7,9 @@ use super::lsp_custom; use super::registries::ModuleRegistry; use super::tsc; -use crate::fs_util::is_supported_ext; -use crate::fs_util::relative_specifier; -use crate::fs_util::specifier_to_file_path; +use crate::util::path::is_supported_ext; +use crate::util::path::relative_specifier; +use crate::util::path::specifier_to_file_path; use deno_ast::LineAndColumnIndex; use deno_ast::SourceTextInfo; @@ -505,7 +505,7 @@ fn get_workspace_completions( #[cfg(test)] mod tests { use super::*; - use crate::http_cache::HttpCache; + use crate::cache::HttpCache; use crate::lsp::documents::Documents; use crate::lsp::documents::LanguageId; use deno_core::resolve_url; diff --git a/cli/lsp/config.rs b/cli/lsp/config.rs index 04a48435f1..8d5da46b7a 100644 --- a/cli/lsp/config.rs +++ b/cli/lsp/config.rs @@ -2,7 +2,8 @@ use super::client::Client; use super::logging::lsp_log; -use crate::fs_util; +use crate::util::path::ensure_directory_specifier; +use crate::util::path::specifier_to_file_path; use deno_core::error::AnyError; use deno_core::serde::Deserialize; use deno_core::serde::Serialize; @@ -549,11 +550,11 @@ impl Config { workspace: &ModuleSpecifier, enabled_paths: Vec, ) -> bool { - let workspace = fs_util::ensure_directory_specifier(workspace.clone()); + let workspace = ensure_directory_specifier(workspace.clone()); let key = workspace.to_string(); let mut touched = false; if !enabled_paths.is_empty() { - if let Ok(workspace_path) = fs_util::specifier_to_file_path(&workspace) { + if let Ok(workspace_path) = specifier_to_file_path(&workspace) { let mut paths = Vec::new(); for path in &enabled_paths { let fs_path = workspace_path.join(path); diff --git a/cli/lsp/documents.rs b/cli/lsp/documents.rs index 5c1e60e736..18464b178c 100644 --- a/cli/lsp/documents.rs +++ b/cli/lsp/documents.rs @@ -6,21 +6,20 @@ use super::tsc; use super::tsc::AssetDocument; use crate::args::ConfigFile; +use crate::cache::CachedUrlMetadata; +use crate::cache::HttpCache; use crate::file_fetcher::get_source_from_bytes; use crate::file_fetcher::map_content_type; use crate::file_fetcher::SUPPORTED_SCHEMES; -use crate::fs_util::specifier_to_file_path; -use crate::http_cache; -use crate::http_cache::HttpCache; use crate::node; use crate::node::node_resolve_npm_reference; use crate::node::NodeResolution; -use crate::node::NodeResolutionMode; use crate::npm::NpmPackageReference; use crate::npm::NpmPackageReq; use crate::npm::NpmPackageResolver; use crate::resolver::CliResolver; -use crate::text_encoding; +use crate::util::path::specifier_to_file_path; +use crate::util::text_encoding; use deno_ast::MediaType; use deno_ast::ParsedSource; @@ -33,10 +32,12 @@ use deno_core::url; use deno_core::ModuleSpecifier; use deno_graph::GraphImport; use deno_graph::Resolved; +use deno_runtime::deno_node::NodeResolutionMode; use once_cell::sync::Lazy; use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; +use std::collections::VecDeque; use std::fs; use std::ops::Range; use std::path::Path; @@ -610,7 +611,7 @@ impl SpecifierResolver { ) -> Option { let cache_filename = self.cache.get_cache_filename(specifier)?; if redirect_limit > 0 && cache_filename.is_file() { - let headers = http_cache::Metadata::read(&cache_filename) + let headers = CachedUrlMetadata::read(&cache_filename) .ok() .map(|m| m.headers)?; if let Some(location) = headers.get("location") { @@ -633,6 +634,23 @@ struct FileSystemDocuments { } impl FileSystemDocuments { + pub fn get( + &mut self, + cache: &HttpCache, + maybe_resolver: Option<&dyn deno_graph::source::Resolver>, + specifier: &ModuleSpecifier, + ) -> Option { + let fs_version = get_document_path(cache, specifier) + .and_then(|path| calculate_fs_version(&path)); + let file_system_doc = self.docs.get(specifier); + if file_system_doc.map(|d| d.fs_version().to_string()) != fs_version { + // attempt to update the file on the file system + self.refresh_document(cache, maybe_resolver, specifier) + } else { + file_system_doc.cloned() + } + } + /// Adds or updates a document by reading the document from the file system /// returning the document. fn refresh_document( @@ -657,8 +675,7 @@ impl FileSystemDocuments { ) } else { let cache_filename = cache.get_cache_filename(specifier)?; - let specifier_metadata = - http_cache::Metadata::read(&cache_filename).ok()?; + let specifier_metadata = CachedUrlMetadata::read(&cache_filename).ok()?; let maybe_content_type = specifier_metadata.headers.get("content-type").cloned(); let maybe_headers = Some(&specifier_metadata.headers); @@ -710,7 +727,7 @@ pub struct Documents { /// settings. maybe_resolver: Option, /// The npm package requirements. - npm_reqs: HashSet, + npm_reqs: Arc>, /// Resolves a specifier to its final redirected to specifier. specifier_resolver: Arc, } @@ -725,7 +742,7 @@ impl Documents { file_system_docs: Default::default(), imports: Default::default(), maybe_resolver: None, - npm_reqs: HashSet::new(), + npm_reqs: Default::default(), specifier_resolver: Arc::new(SpecifierResolver::new(location)), } } @@ -863,7 +880,7 @@ impl Documents { /// Returns a collection of npm package requirements. pub fn npm_package_reqs(&mut self) -> HashSet { self.calculate_dependents_if_dirty(); - self.npm_reqs.clone() + (*self.npm_reqs).clone() } /// Return a document for the specifier. @@ -873,19 +890,7 @@ impl Documents { Some(document.clone()) } else { let mut file_system_docs = self.file_system_docs.lock(); - let fs_version = get_document_path(&self.cache, &specifier) - .and_then(|path| calculate_fs_version(&path)); - let file_system_doc = file_system_docs.docs.get(&specifier); - if file_system_doc.map(|d| d.fs_version().to_string()) != fs_version { - // attempt to update the file on the file system - file_system_docs.refresh_document( - &self.cache, - self.get_maybe_resolver(), - &specifier, - ) - } else { - file_system_doc.cloned() - } + file_system_docs.get(&self.cache, self.get_maybe_resolver(), &specifier) } } @@ -938,7 +943,7 @@ impl Documents { /// tsc when type checking. pub fn resolve( &self, - specifiers: Vec, + specifiers: &[String], referrer: &ModuleSpecifier, maybe_npm_resolver: Option<&NpmPackageResolver>, ) -> Option>> { @@ -950,9 +955,9 @@ impl Documents { // we're in an npm package, so use node resolution results.push(Some(NodeResolution::into_specifier_and_media_type( node::node_resolve( - &specifier, + specifier, referrer, - node::NodeResolutionMode::Types, + NodeResolutionMode::Types, npm_resolver, ) .ok() @@ -963,13 +968,13 @@ impl Documents { } // handle npm: urls if specifier.starts_with("asset:") { - if let Ok(specifier) = ModuleSpecifier::parse(&specifier) { + if let Ok(specifier) = ModuleSpecifier::parse(specifier) { let media_type = MediaType::from(&specifier); results.push(Some((specifier, media_type))); } else { results.push(None); } - } else if let Some(dep) = dependencies.deps.get(&specifier) { + } else if let Some(dep) = dependencies.deps.get(specifier) { if let Resolved::Ok { specifier, .. } = &dep.maybe_type { results.push(self.resolve_dependency(specifier, maybe_npm_resolver)); } else if let Resolved::Ok { specifier, .. } = &dep.maybe_code { @@ -978,12 +983,12 @@ impl Documents { results.push(None); } } else if let Some(Resolved::Ok { specifier, .. }) = - self.resolve_imports_dependency(&specifier) + self.resolve_imports_dependency(specifier) { // clone here to avoid double borrow of self let specifier = specifier.clone(); results.push(self.resolve_dependency(&specifier, maybe_npm_resolver)); - } else if let Ok(npm_ref) = NpmPackageReference::from_str(&specifier) { + } else if let Ok(npm_ref) = NpmPackageReference::from_str(specifier) { results.push(maybe_npm_resolver.map(|npm_resolver| { NodeResolution::into_specifier_and_media_type( node_resolve_npm_reference( @@ -1076,46 +1081,74 @@ impl Documents { /// document and the value is a set of specifiers that depend on that /// document. fn calculate_dependents_if_dirty(&mut self) { + #[derive(Default)] + struct DocAnalyzer { + dependents_map: HashMap>, + analyzed_specifiers: HashSet, + pending_specifiers: VecDeque, + npm_reqs: HashSet, + } + + impl DocAnalyzer { + fn add(&mut self, dep: &ModuleSpecifier, specifier: &ModuleSpecifier) { + if !self.analyzed_specifiers.contains(dep) { + self.analyzed_specifiers.insert(dep.clone()); + // perf: ensure this is not added to unless this specifier has never + // been analyzed in order to not cause an extra file system lookup + self.pending_specifiers.push_back(dep.clone()); + if let Ok(reference) = NpmPackageReference::from_specifier(dep) { + self.npm_reqs.insert(reference.req); + } + } + + self + .dependents_map + .entry(dep.clone()) + .or_default() + .insert(specifier.clone()); + } + + fn analyze_doc(&mut self, specifier: &ModuleSpecifier, doc: &Document) { + self.analyzed_specifiers.insert(specifier.clone()); + for dependency in doc.dependencies().values() { + if let Some(dep) = dependency.get_code() { + self.add(dep, specifier); + } + if let Some(dep) = dependency.get_type() { + self.add(dep, specifier); + } + } + if let Resolved::Ok { specifier: dep, .. } = + doc.maybe_types_dependency() + { + self.add(&dep, specifier); + } + } + } + let mut file_system_docs = self.file_system_docs.lock(); if !file_system_docs.dirty && !self.dirty { return; } - let mut dependents_map: HashMap> = - HashMap::new(); - // favour documents that are open in case a document exists in both collections + let mut doc_analyzer = DocAnalyzer::default(); + // favor documents that are open in case a document exists in both collections let documents = file_system_docs.docs.iter().chain(self.open_docs.iter()); for (specifier, doc) in documents { - for dependency in doc.dependencies().values() { - if let Some(dep) = dependency.get_code() { - dependents_map - .entry(dep.clone()) - .or_default() - .insert(specifier.clone()); - } - if let Some(dep) = dependency.get_type() { - dependents_map - .entry(dep.clone()) - .or_default() - .insert(specifier.clone()); - } - } - if let Resolved::Ok { specifier: dep, .. } = doc.maybe_types_dependency() + doc_analyzer.analyze_doc(specifier, doc); + } + + let maybe_resolver = self.get_maybe_resolver(); + while let Some(specifier) = doc_analyzer.pending_specifiers.pop_front() { + if let Some(doc) = + file_system_docs.get(&self.cache, maybe_resolver, &specifier) { - dependents_map - .entry(dep.clone()) - .or_default() - .insert(specifier.clone()); + doc_analyzer.analyze_doc(&specifier, &doc); } } - let mut npm_reqs = HashSet::new(); - for specifier in dependents_map.keys() { - if let Ok(reference) = NpmPackageReference::from_specifier(specifier) { - npm_reqs.insert(reference.req); - } - } - self.dependents_map = Arc::new(dependents_map); - self.npm_reqs = npm_reqs; + + self.dependents_map = Arc::new(doc_analyzer.dependents_map); + self.npm_reqs = Arc::new(doc_analyzer.npm_reqs); self.dirty = false; file_system_docs.dirty = false; } diff --git a/cli/lsp/language_server.rs b/cli/lsp/language_server.rs index 4e7c4b240b..11897af9d9 100644 --- a/cli/lsp/language_server.rs +++ b/cli/lsp/language_server.rs @@ -57,6 +57,8 @@ use super::tsc::Assets; use super::tsc::AssetsSnapshot; use super::tsc::TsServer; use super::urls; +use crate::args::get_root_cert_store; +use crate::args::CacheSetting; use crate::args::CliOptions; use crate::args::ConfigFile; use crate::args::Flags; @@ -64,10 +66,7 @@ use crate::args::FmtConfig; use crate::args::LintConfig; use crate::args::TsConfig; use crate::cache::DenoDir; -use crate::file_fetcher::get_root_cert_store; use crate::file_fetcher::get_source_from_data_url; -use crate::file_fetcher::CacheSetting; -use crate::fs_util; use crate::graph_util::graph_valid; use crate::http_util::HttpClient; use crate::npm::NpmCache; @@ -75,9 +74,12 @@ use crate::npm::NpmPackageResolver; use crate::npm::RealNpmRegistryApi; use crate::proc_state::import_map_from_text; use crate::proc_state::ProcState; -use crate::progress_bar::ProgressBar; use crate::tools::fmt::format_file; use crate::tools::fmt::format_parsed_source; +use crate::util::fs::remove_dir_all_if_exists; +use crate::util::path::ensure_directory_specifier; +use crate::util::path::specifier_to_file_path; +use crate::util::progress_bar::ProgressBar; #[derive(Debug, Clone)] pub struct LanguageServer(Arc>); @@ -238,22 +240,20 @@ fn create_lsp_npm_resolver( http_client: HttpClient, ) -> NpmPackageResolver { let registry_url = RealNpmRegistryApi::default_url(); - // Use an "only" cache setting in order to make the - // user do an explicit "cache" command and prevent - // the cache from being filled with lots of packages while - // the user is typing. - let cache_setting = CacheSetting::Only; let progress_bar = ProgressBar::default(); let npm_cache = NpmCache::from_deno_dir( dir, - cache_setting.clone(), + // Use an "only" cache setting in order to make the + // user do an explicit "cache" command and prevent + // the cache from being filled with lots of packages while + // the user is typing. + CacheSetting::Only, http_client.clone(), progress_bar.clone(), ); let api = RealNpmRegistryApi::new( registry_url, npm_cache.clone(), - cache_setting, http_client, progress_bar, ); @@ -409,7 +409,7 @@ impl Inner { // file open and not a workspace. In those situations we can't // automatically discover the configuration if let Some(root_uri) = &self.config.root_uri { - let root_path = fs_util::specifier_to_file_path(root_uri)?; + let root_path = specifier_to_file_path(root_uri)?; let mut checked = std::collections::HashSet::new(); let maybe_config = ConfigFile::discover_from(&root_path, &mut checked)?; Ok(maybe_config.map(|c| { @@ -483,7 +483,7 @@ impl Inner { let cache_url = if let Ok(url) = Url::from_file_path(cache_str) { Ok(url) } else if let Some(root_uri) = &self.config.root_uri { - let root_path = fs_util::specifier_to_file_path(root_uri)?; + let root_path = specifier_to_file_path(root_uri)?; let cache_path = root_path.join(cache_str); Url::from_file_path(cache_path).map_err(|_| { anyhow!("Bad file path for import path: {:?}", cache_str) @@ -494,7 +494,7 @@ impl Inner { cache_str )) }?; - let cache_path = fs_util::specifier_to_file_path(&cache_url)?; + let cache_path = specifier_to_file_path(&cache_url)?; lsp_log!( " Resolved cache path: \"{}\"", cache_path.to_string_lossy() @@ -523,7 +523,7 @@ impl Inner { .config .root_uri .as_ref() - .and_then(|uri| fs_util::specifier_to_file_path(uri).ok()); + .and_then(|uri| specifier_to_file_path(uri).ok()); let root_cert_store = Some(get_root_cert_store( maybe_root_path, workspace_settings.certificate_stores.clone(), @@ -571,7 +571,7 @@ impl Inner { anyhow!("Bad data url for import map: {}", import_map_str) })?) } else if let Some(root_uri) = &self.config.root_uri { - let root_path = fs_util::specifier_to_file_path(root_uri)?; + let root_path = specifier_to_file_path(root_uri)?; let import_map_path = root_path.join(&import_map_str); Some(Url::from_file_path(import_map_path).map_err(|_| { anyhow!("Bad file path for import map: {}", import_map_str) @@ -614,7 +614,7 @@ impl Inner { let import_map_json = if import_map_url.scheme() == "data" { get_source_from_data_url(&import_map_url)?.0 } else { - let import_map_path = fs_util::specifier_to_file_path(&import_map_url)?; + let import_map_path = specifier_to_file_path(&import_map_url)?; lsp_log!( " Resolved import map: \"{}\"", import_map_path.to_string_lossy() @@ -770,7 +770,7 @@ impl Inner { self.config.root_uri = params .root_uri .map(|s| self.url_map.normalize_url(&s)) - .map(fs_util::ensure_directory_specifier); + .map(ensure_directory_specifier); if let Some(value) = params.initialization_options { self.config.set_workspace_settings(value).map_err(|err| { @@ -1139,11 +1139,10 @@ impl Inner { _ => return Ok(None), }; let mark = self.performance.mark("formatting", Some(¶ms)); - let file_path = - fs_util::specifier_to_file_path(&specifier).map_err(|err| { - error!("{}", err); - LspError::invalid_request() - })?; + let file_path = specifier_to_file_path(&specifier).map_err(|err| { + error!("{}", err); + LspError::invalid_request() + })?; let fmt_options = if let Some(fmt_config) = self.maybe_fmt_config.as_ref() { // skip formatting any files ignored by the config file @@ -2065,7 +2064,7 @@ impl Inner { .config .root_uri .as_ref() - .and_then(|uri| fs_util::specifier_to_file_path(uri).ok()); + .and_then(|uri| specifier_to_file_path(uri).ok()); let mut resolved_items = Vec::::new(); for item in incoming_calls.iter() { if let Some(resolved) = item.try_resolve_call_hierarchy_incoming_call( @@ -2111,7 +2110,7 @@ impl Inner { .config .root_uri .as_ref() - .and_then(|uri| fs_util::specifier_to_file_path(uri).ok()); + .and_then(|uri| specifier_to_file_path(uri).ok()); let mut resolved_items = Vec::::new(); for item in outgoing_calls.iter() { if let Some(resolved) = item.try_resolve_call_hierarchy_outgoing_call( @@ -2164,7 +2163,7 @@ impl Inner { .config .root_uri .as_ref() - .and_then(|uri| fs_util::specifier_to_file_path(uri).ok()); + .and_then(|uri| specifier_to_file_path(uri).ok()); let mut resolved_items = Vec::::new(); match one_or_many { tsc::OneOrMany::One(item) => { @@ -3012,7 +3011,7 @@ impl Inner { } async fn reload_import_registries(&mut self) -> LspResult> { - fs_util::remove_dir_all_if_exists(&self.module_registries_location) + remove_dir_all_if_exists(&self.module_registries_location) .await .map_err(|err| { error!("Unable to remove registries cache: {}", err); diff --git a/cli/lsp/registries.rs b/cli/lsp/registries.rs index 43500e6970..1488077dd4 100644 --- a/cli/lsp/registries.rs +++ b/cli/lsp/registries.rs @@ -12,10 +12,10 @@ use super::path_to_regex::StringOrNumber; use super::path_to_regex::StringOrVec; use super::path_to_regex::Token; +use crate::args::CacheSetting; use crate::cache::DenoDir; -use crate::file_fetcher::CacheSetting; +use crate::cache::HttpCache; use crate::file_fetcher::FileFetcher; -use crate::http_cache::HttpCache; use crate::http_util::HttpClient; use deno_core::anyhow::anyhow; diff --git a/cli/lsp/testing/definitions.rs b/cli/lsp/testing/definitions.rs index 14ac165fd1..a2cd780123 100644 --- a/cli/lsp/testing/definitions.rs +++ b/cli/lsp/testing/definitions.rs @@ -2,9 +2,9 @@ use super::lsp_custom; -use crate::checksum; use crate::lsp::analysis::source_range_to_lsp_range; use crate::lsp::client::TestingNotification; +use crate::util::checksum; use deno_ast::SourceRange; use deno_ast::SourceTextInfo; diff --git a/cli/lsp/testing/execution.rs b/cli/lsp/testing/execution.rs index d839cda568..f0ab1c8fcd 100644 --- a/cli/lsp/testing/execution.rs +++ b/cli/lsp/testing/execution.rs @@ -6,7 +6,6 @@ use super::lsp_custom; use crate::args::flags_from_vec; use crate::args::DenoSubcommand; -use crate::checksum; use crate::lsp::client::Client; use crate::lsp::client::TestingNotification; use crate::lsp::config; @@ -14,7 +13,9 @@ use crate::lsp::logging::lsp_log; use crate::ops; use crate::proc_state; use crate::tools::test; +use crate::tools::test::FailFastTracker; use crate::tools::test::TestEventSender; +use crate::util::checksum; use crate::worker::create_main_worker_for_test_or_bench; use deno_core::anyhow::anyhow; @@ -144,25 +145,29 @@ impl LspTestFilter { } } +#[allow(clippy::too_many_arguments)] async fn test_specifier( ps: proc_state::ProcState, permissions: Permissions, specifier: ModuleSpecifier, mode: test::TestMode, - sender: &TestEventSender, + sender: TestEventSender, + fail_fast_tracker: FailFastTracker, token: CancellationToken, filter: test::TestFilter, ) -> Result<(), AnyError> { if !token.is_cancelled() { + let stdout = StdioPipe::File(sender.stdout()); + let stderr = StdioPipe::File(sender.stderr()); let mut worker = create_main_worker_for_test_or_bench( &ps, specifier.clone(), permissions, - vec![ops::testing::init(sender.clone(), filter)], + vec![ops::testing::init(sender, fail_fast_tracker, filter)], Stdio { stdin: StdioPipe::Inherit, - stdout: StdioPipe::File(sender.stdout()), - stderr: StdioPipe::File(sender.stderr()), + stdout, + stderr, }, ) .await?; @@ -262,19 +267,17 @@ impl TestRun { ) .await?; - let (sender, mut receiver) = mpsc::unbounded_channel::(); - let sender = TestEventSender::new(sender); - let (concurrent_jobs, fail_fast) = if let DenoSubcommand::Test(test_flags) = ps.options.sub_command() { - ( - test_flags.concurrent_jobs.into(), - test_flags.fail_fast.map(|count| count.into()), - ) + (test_flags.concurrent_jobs.into(), test_flags.fail_fast) } else { unreachable!("Should always be Test subcommand."); }; + let (sender, mut receiver) = mpsc::unbounded_channel::(); + let sender = TestEventSender::new(sender); + let fail_fast_tracker = FailFastTracker::new(fail_fast); + let mut queue = self.queue.iter().collect::>(); queue.sort(); @@ -288,6 +291,7 @@ impl TestRun { let ps = ps.clone(); let permissions = permissions.clone(); let mut sender = sender.clone(); + let fail_fast_tracker = fail_fast_tracker.clone(); let lsp_filter = self.filters.get(&specifier); let filter = test::TestFilter { substring: None, @@ -305,13 +309,17 @@ impl TestRun { let tests = tests_.clone(); tokio::task::spawn_blocking(move || { + if fail_fast_tracker.should_stop() { + return Ok(()); + } let origin = specifier.to_string(); let file_result = run_local(test_specifier( ps, permissions, specifier, test::TestMode::Executable, - &sender, + sender.clone(), + fail_fast_tracker, token, filter, )); @@ -427,12 +435,6 @@ impl TestRun { ); } } - - if let Some(count) = fail_fast { - if summary.failed >= count { - break; - } - } } let elapsed = Instant::now().duration_since(earlier); diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs index 4bb5ae5f99..1152c080d2 100644 --- a/cli/lsp/tsc.rs +++ b/cli/lsp/tsc.rs @@ -18,10 +18,10 @@ use super::urls::LspUrlMap; use super::urls::INVALID_SPECIFIER; use crate::args::TsConfig; -use crate::fs_util::relative_specifier; -use crate::fs_util::specifier_to_file_path; use crate::tsc; use crate::tsc::ResolveArgs; +use crate::util::path::relative_specifier; +use crate::util::path::specifier_to_file_path; use deno_core::anyhow::anyhow; use deno_core::error::custom_error; @@ -2726,7 +2726,7 @@ fn op_resolve( let referrer = state.normalize_specifier(&args.base)?; let result = if let Some(resolved) = state.state_snapshot.documents.resolve( - args.specifiers, + &args.specifiers, &referrer, state.state_snapshot.maybe_npm_resolver.as_ref(), ) { @@ -3445,7 +3445,7 @@ pub fn request( #[cfg(test)] mod tests { use super::*; - use crate::http_cache::HttpCache; + use crate::cache::HttpCache; use crate::http_util::HeadersMap; use crate::lsp::config::WorkspaceSettings; use crate::lsp::documents::Documents; @@ -3913,7 +3913,7 @@ mod tests { // You might have found this assertion starts failing after upgrading TypeScript. // Just update the new number of assets (declaration files) for this number. - assert_eq!(assets.len(), 71); + assert_eq!(assets.len(), 72); // get some notification when the size of the assets grows let mut total_size = 0; diff --git a/cli/lsp/urls.rs b/cli/lsp/urls.rs index 9b14098ae8..5aed54ad5e 100644 --- a/cli/lsp/urls.rs +++ b/cli/lsp/urls.rs @@ -56,7 +56,7 @@ fn hash_data_specifier(specifier: &ModuleSpecifier) -> String { file_name_str.push('?'); file_name_str.push_str(query); } - crate::checksum::gen(&[file_name_str.as_bytes()]) + crate::util::checksum::gen(&[file_name_str.as_bytes()]) } #[derive(Debug, Default)] diff --git a/cli/main.rs b/cli/main.rs index fde8b51ae5..f9ef036e18 100644 --- a/cli/main.rs +++ b/cli/main.rs @@ -3,20 +3,13 @@ mod args; mod auth_tokens; mod cache; -mod checksum; mod deno_std; -mod diff; -mod display; mod emit; mod errors; mod file_fetcher; -mod file_watcher; -mod fs_util; mod graph_util; -mod http_cache; mod http_util; mod js; -mod logger; mod lsp; mod module_loader; mod napi; @@ -24,15 +17,12 @@ mod node; mod npm; mod ops; mod proc_state; -mod progress_bar; mod resolver; mod standalone; -mod text_encoding; mod tools; mod tsc; -mod unix_util; +mod util; mod version; -mod windows_util; mod worker; use crate::args::flags_from_vec; @@ -63,14 +53,14 @@ use crate::args::UpgradeFlags; use crate::args::VendorFlags; use crate::cache::TypeCheckCache; use crate::file_fetcher::File; -use crate::file_watcher::ResolutionResult; use crate::graph_util::graph_lock_or_exit; use crate::proc_state::ProcState; use crate::resolver::CliResolver; use crate::tools::check; +use crate::util::display; +use crate::util::file_watcher::ResolutionResult; use args::CliOptions; -use args::Lockfile; use deno_ast::MediaType; use deno_core::anyhow::bail; use deno_core::error::generic_error; @@ -324,7 +314,6 @@ async fn create_graph_and_maybe_check( Permissions::allow_all(), Permissions::allow_all(), ); - let maybe_locker = Lockfile::as_maybe_locker(ps.lockfile.clone()); let maybe_imports = ps.options.to_maybe_imports()?; let maybe_cli_resolver = CliResolver::maybe_new( ps.options.to_maybe_jsx_import_source_config(), @@ -341,7 +330,6 @@ async fn create_graph_and_maybe_check( is_dynamic: false, imports: maybe_imports, resolver: maybe_graph_resolver, - locker: maybe_locker, module_analyzer: Some(&*analyzer), reporter: None, }, @@ -362,7 +350,9 @@ async fn create_graph_and_maybe_check( ps.npm_resolver .add_package_reqs(graph_data.npm_package_reqs().clone()) .await?; - graph_lock_or_exit(&graph); + if let Some(lockfile) = &ps.lockfile { + graph_lock_or_exit(&graph, &mut lockfile.lock()); + } if ps.options.type_check_mode() != TypeCheckMode::None { let ts_config_result = @@ -442,7 +432,6 @@ async fn bundle_command( let mut paths_to_watch: Vec = graph .specifiers() - .iter() .filter_map(|(_, r)| { r.as_ref().ok().and_then(|(s, _, _)| s.to_file_path().ok()) }) @@ -482,7 +471,7 @@ async fn bundle_command( if let Some(out_file) = out_file.as_ref() { let output_bytes = bundle_output.code.as_bytes(); let output_len = output_bytes.len(); - fs_util::write_file(out_file, output_bytes, 0o644)?; + util::fs::write_file(out_file, output_bytes, 0o644)?; info!( "{} {:?} ({})", colors::green("Emit"), @@ -498,7 +487,7 @@ async fn bundle_command( "map".to_string() }; let map_out_file = out_file.with_extension(ext); - fs_util::write_file(&map_out_file, map_bytes, 0o644)?; + util::fs::write_file(&map_out_file, map_bytes, 0o644)?; info!( "{} {:?} ({})", colors::green("Emit"), @@ -515,10 +504,10 @@ async fn bundle_command( }; if cli_options.watch_paths().is_some() { - file_watcher::watch_func( + util::file_watcher::watch_func( resolver, operation, - file_watcher::PrintConfig { + util::file_watcher::PrintConfig { job_name: "Bundle".to_string(), clear_screen: !cli_options.no_clear_screen(), }, @@ -542,9 +531,8 @@ fn error_for_any_npm_specifier( ) -> Result<(), AnyError> { let first_npm_specifier = graph .specifiers() - .values() - .filter_map(|r| match r { - Ok((specifier, kind, _)) if *kind == deno_graph::ModuleKind::External => { + .filter_map(|(_, r)| match r { + Ok((specifier, kind, _)) if kind == deno_graph::ModuleKind::External => { Some(specifier.clone()) } _ => None, @@ -590,8 +578,7 @@ async fn repl_command( ) -> Result { let main_module = resolve_url_or_path("./$deno$repl.ts").unwrap(); let ps = ProcState::build(flags).await?; - tools::repl::run(&ps, main_module, repl_flags.eval_files, repl_flags.eval) - .await + tools::repl::run(&ps, main_module, repl_flags).await } async fn run_from_stdin(flags: Flags) -> Result { @@ -648,11 +635,11 @@ async fn run_with_watch(flags: Flags, script: String) -> Result { }) }; - file_watcher::watch_func2( + util::file_watcher::watch_func2( receiver, operation, (sender, main_module), - file_watcher::PrintConfig { + util::file_watcher::PrintConfig { job_name: "Process".to_string(), clear_screen: !flags.no_clear_screen, }, @@ -940,8 +927,8 @@ fn unwrap_or_exit(result: Result) -> T { pub fn main() { setup_panic_hook(); - unix_util::raise_fd_limit(); - windows_util::ensure_stdio_open(); + util::unix::raise_fd_limit(); + util::windows::ensure_stdio_open(); #[cfg(windows)] colors::enable_ansi(); // For Windows 10 @@ -972,7 +959,7 @@ pub fn main() { init_v8_flags(&flags.v8_flags); } - logger::init(flags.log_level); + util::logger::init(flags.log_level); get_subcommand(flags).await }; diff --git a/cli/module_loader.rs b/cli/module_loader.rs index 41ec7e28ce..6adfc9f491 100644 --- a/cli/module_loader.rs +++ b/cli/module_loader.rs @@ -5,8 +5,8 @@ use crate::emit::emit_parsed_source; use crate::graph_util::ModuleEntry; use crate::node; use crate::proc_state::ProcState; -use crate::text_encoding::code_without_source_map; -use crate::text_encoding::source_map_from_code; +use crate::util::text_encoding::code_without_source_map; +use crate::util::text_encoding::source_map_from_code; use deno_ast::MediaType; use deno_core::anyhow::anyhow; diff --git a/cli/napi/env.rs b/cli/napi/env.rs index df9af522fe..0adb0481ea 100644 --- a/cli/napi/env.rs +++ b/cli/napi/env.rs @@ -59,7 +59,7 @@ fn napi_add_env_cleanup_hook( _hook: extern "C" fn(*const c_void), _data: *const c_void, ) -> Result { - eprintln!("napi_add_env_cleanup_hook is currently not supported"); + log::info!("napi_add_env_cleanup_hook is currently not supported"); Ok(()) } @@ -69,7 +69,7 @@ fn napi_remove_env_cleanup_hook( _hook: extern "C" fn(*const c_void), _data: *const c_void, ) -> Result { - eprintln!("napi_remove_env_cleanup_hook is currently not supported"); + log::info!("napi_remove_env_cleanup_hook is currently not supported"); Ok(()) } diff --git a/cli/napi/js_native_api.rs b/cli/napi/js_native_api.rs index a0605af11c..1c3b02fa91 100644 --- a/cli/napi/js_native_api.rs +++ b/cli/napi/js_native_api.rs @@ -737,7 +737,7 @@ fn napi_make_callback( } if !async_context.is_null() { - eprintln!("napi_make_callback: async_context is not supported"); + log::info!("napi_make_callback: async_context is not supported"); } let recv = transmute::>(recv); @@ -1006,7 +1006,7 @@ fn napi_add_finalizer( _finalize_hint: *const c_void, _result: *mut napi_ref, ) -> Result { - eprintln!("napi_add_finalizer is not yet supported."); + log::info!("napi_add_finalizer is not yet supported."); Ok(()) } @@ -1260,11 +1260,10 @@ fn napi_delete_reference(env: *mut Env, _nref: napi_ref) -> Result { } #[napi_sym::napi_sym] -fn napi_detach_arraybuffer(env: *mut Env, value: napi_value) -> Result { - let env: &mut Env = env.as_mut().ok_or(Error::InvalidArg)?; +fn napi_detach_arraybuffer(_env: *mut Env, value: napi_value) -> Result { let value = transmute::>(value); let ab = v8::Local::::try_from(value).unwrap(); - ab.detach(v8::undefined(&mut env.scope()).into()); + ab.detach(None); Ok(()) } diff --git a/cli/napi_sym/Cargo.toml b/cli/napi/sym/Cargo.toml similarity index 96% rename from cli/napi_sym/Cargo.toml rename to cli/napi/sym/Cargo.toml index 49a11fff9d..3542df78c3 100644 --- a/cli/napi_sym/Cargo.toml +++ b/cli/napi/sym/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "napi_sym" -version = "0.9.0" +version = "0.10.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/cli/napi_sym/README.md b/cli/napi/sym/README.md similarity index 100% rename from cli/napi_sym/README.md rename to cli/napi/sym/README.md diff --git a/cli/napi_sym/lib.rs b/cli/napi/sym/lib.rs similarity index 95% rename from cli/napi_sym/lib.rs rename to cli/napi/sym/lib.rs index 2805c99572..984d7f4bcd 100644 --- a/cli/napi_sym/lib.rs +++ b/cli/napi/sym/lib.rs @@ -20,7 +20,7 @@ pub fn napi_sym(_attr: TokenStream, item: TokenStream) -> TokenStream { let name = &func.sig.ident; assert!( exports.symbols.contains(&name.to_string()), - "tools/napi/symbol_exports.json is out of sync!" + "tools/napi/sym/symbol_exports.json is out of sync!" ); let block = &func.block; diff --git a/cli/napi_sym/symbol_exports.json b/cli/napi/sym/symbol_exports.json similarity index 100% rename from cli/napi_sym/symbol_exports.json rename to cli/napi/sym/symbol_exports.json diff --git a/cli/node/mod.rs b/cli/node/mod.rs index fc4db33ee2..d0c3ed03f3 100644 --- a/cli/node/mod.rs +++ b/cli/node/mod.rs @@ -27,12 +27,12 @@ use deno_runtime::deno_node::package_imports_resolve; use deno_runtime::deno_node::package_resolve; use deno_runtime::deno_node::path_to_declaration_path; use deno_runtime::deno_node::NodeModuleKind; +use deno_runtime::deno_node::NodeResolutionMode; use deno_runtime::deno_node::PackageJson; use deno_runtime::deno_node::PathClean; use deno_runtime::deno_node::RequireNpmResolver; use deno_runtime::deno_node::DEFAULT_CONDITIONS; use deno_runtime::deno_node::NODE_GLOBAL_THIS_NAME; -use deno_runtime::deno_node::TYPES_CONDITIONS; use once_cell::sync::Lazy; use regex::Regex; @@ -95,25 +95,15 @@ impl NodeResolution { }, ) } - maybe_response => { - let specifier = match maybe_response { - Some(response) => response.into_url(), - None => { - ModuleSpecifier::parse("deno:///missing_dependency.d.ts").unwrap() - } - }; - (specifier, MediaType::Dts) - } + Some(resolution) => (resolution.into_url(), MediaType::Dts), + None => ( + ModuleSpecifier::parse("deno:///missing_dependency.d.ts").unwrap(), + MediaType::Dts, + ), } } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum NodeResolutionMode { - Execution, - Types, -} - struct NodeModulePolyfill { /// Name of the module like "assert" or "timers/promises" name: &'static str, @@ -480,8 +470,13 @@ pub fn node_resolve( } } - let conditions = mode_conditions(mode); - let url = module_resolve(specifier, referrer, conditions, npm_resolver)?; + let url = module_resolve( + specifier, + referrer, + DEFAULT_CONDITIONS, + mode, + npm_resolver, + )?; let url = match url { Some(url) => url, None => return Ok(None), @@ -492,7 +487,10 @@ pub fn node_resolve( let path = url.to_file_path().unwrap(); // todo(16370): the module kind is not correct here. I think we need // typescript to tell us if the referrer is esm or cjs - let path = path_to_declaration_path(path, NodeModuleKind::Esm); + let path = match path_to_declaration_path(path, NodeModuleKind::Esm) { + Some(path) => path, + None => return Ok(None), + }; ModuleSpecifier::from_file_path(path).unwrap() } }; @@ -519,7 +517,8 @@ pub fn node_resolve_npm_reference( .unwrap_or_else(|| ".".to_string()), &package_folder, node_module_kind, - mode_conditions(mode), + DEFAULT_CONDITIONS, + mode, npm_resolver, ) .with_context(|| { @@ -532,7 +531,10 @@ pub fn node_resolve_npm_reference( let resolved_path = match mode { NodeResolutionMode::Execution => resolved_path, NodeResolutionMode::Types => { - path_to_declaration_path(resolved_path, node_module_kind) + match path_to_declaration_path(resolved_path, node_module_kind) { + Some(path) => path, + None => return Ok(None), + } } }; let url = ModuleSpecifier::from_file_path(resolved_path).unwrap(); @@ -542,13 +544,6 @@ pub fn node_resolve_npm_reference( Ok(Some(resolve_response)) } -fn mode_conditions(mode: NodeResolutionMode) -> &'static [&'static str] { - match mode { - NodeResolutionMode::Execution => DEFAULT_CONDITIONS, - NodeResolutionMode::Types => TYPES_CONDITIONS, - } -} - pub fn node_resolve_binary_export( pkg_req: &NpmPackageReq, bin_name: Option<&str>, @@ -636,17 +631,22 @@ pub fn load_cjs_module_from_ext_node( js_runtime: &mut JsRuntime, module: &str, main: bool, + inspect_brk: bool, ) -> Result<(), AnyError> { fn escape_for_single_quote_string(text: &str) -> String { text.replace('\\', r"\\").replace('\'', r"\'") } let source_code = &format!( - r#"(function loadCjsModule(module) {{ + r#"(function loadCjsModule(module, inspectBrk) {{ + if (inspectBrk) {{ + Deno[Deno.internal].require.setInspectBrk(); + }} Deno[Deno.internal].require.Module._load(module, null, {main}); - }})('{module}');"#, + }})('{module}', {inspect_brk});"#, main = main, module = escape_for_single_quote_string(module), + inspect_brk = inspect_brk, ); js_runtime.execute_script(&located_script_name!(), source_code)?; @@ -658,6 +658,7 @@ fn package_config_resolve( package_dir: &Path, referrer_kind: NodeModuleKind, conditions: &[&str], + mode: NodeResolutionMode, npm_resolver: &dyn RequireNpmResolver, ) -> Result, AnyError> { let package_json_path = package_dir.join("package.json"); @@ -672,15 +673,15 @@ fn package_config_resolve( &referrer, referrer_kind, conditions, + mode, npm_resolver, ); match result { Ok(found) => return Ok(Some(found)), Err(exports_err) => { - let is_types = conditions == TYPES_CONDITIONS; - if is_types && package_subpath == "." { + if mode.is_types() && package_subpath == "." { if let Ok(Some(path)) = - legacy_main_resolve(&package_config, referrer_kind, conditions) + legacy_main_resolve(&package_config, referrer_kind, mode) { return Ok(Some(path)); } else { @@ -692,7 +693,7 @@ fn package_config_resolve( } } if package_subpath == "." { - return legacy_main_resolve(&package_config, referrer_kind, conditions); + return legacy_main_resolve(&package_config, referrer_kind, mode); } Ok(Some(package_dir.join(package_subpath))) @@ -778,18 +779,21 @@ fn module_resolve( specifier: &str, referrer: &ModuleSpecifier, conditions: &[&str], + mode: NodeResolutionMode, npm_resolver: &dyn RequireNpmResolver, ) -> Result, AnyError> { // note: if we're here, the referrer is an esm module let url = if should_be_treated_as_relative_or_absolute_path(specifier) { let resolved_specifier = referrer.join(specifier)?; - if conditions == TYPES_CONDITIONS { + if mode.is_types() { let file_path = to_file_path(&resolved_specifier); // todo(dsherret): the node module kind is not correct and we // should use the value provided by typescript instead let declaration_path = path_to_declaration_path(file_path, NodeModuleKind::Esm); - Some(ModuleSpecifier::from_file_path(declaration_path).unwrap()) + declaration_path.map(|declaration_path| { + ModuleSpecifier::from_file_path(declaration_path).unwrap() + }) } else { Some(resolved_specifier) } @@ -800,6 +804,7 @@ fn module_resolve( referrer, NodeModuleKind::Esm, conditions, + mode, npm_resolver, ) .map(|p| ModuleSpecifier::from_file_path(p).unwrap())?, @@ -812,6 +817,7 @@ fn module_resolve( referrer, NodeModuleKind::Esm, conditions, + mode, npm_resolver, )? .map(|p| ModuleSpecifier::from_file_path(p).unwrap()) @@ -943,6 +949,7 @@ pub fn translate_cjs_to_esm( // FIXME(bartlomieju): check if these conditions are okay, probably // should be `deno-require`, because `deno` is already used in `esm_resolver.rs` &["deno", "require", "default"], + NodeResolutionMode::Execution, npm_resolver, )?; let reexport_specifier = @@ -1013,6 +1020,7 @@ fn resolve( specifier: &str, referrer: &ModuleSpecifier, conditions: &[&str], + mode: NodeResolutionMode, npm_resolver: &dyn RequireNpmResolver, ) -> Result { if specifier.starts_with('/') { @@ -1037,7 +1045,7 @@ fn resolve( let module_dir = npm_resolver.resolve_package_folder_from_package( package_specifier.as_str(), &referrer_path, - conditions, + mode, )?; let package_json_path = module_dir.join("package.json"); @@ -1053,6 +1061,7 @@ fn resolve( referrer, NodeModuleKind::Esm, conditions, + mode, npm_resolver, ); } diff --git a/cli/npm/cache.rs b/cli/npm/cache.rs index b2c8423092..ad6ab9db2c 100644 --- a/cli/npm/cache.rs +++ b/cli/npm/cache.rs @@ -1,21 +1,26 @@ // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. +use std::collections::HashSet; use std::fs; use std::path::Path; use std::path::PathBuf; +use std::sync::Arc; use deno_ast::ModuleSpecifier; use deno_core::anyhow::bail; use deno_core::anyhow::Context; use deno_core::error::custom_error; use deno_core::error::AnyError; +use deno_core::parking_lot::Mutex; use deno_core::url::Url; +use crate::args::CacheSetting; use crate::cache::DenoDir; -use crate::file_fetcher::CacheSetting; -use crate::fs_util; use crate::http_util::HttpClient; -use crate::progress_bar::ProgressBar; +use crate::util::fs::canonicalize_path; +use crate::util::fs::hard_link_dir_recursive; +use crate::util::path::root_url_to_safe_local_dirname; +use crate::util::progress_bar::ProgressBar; use super::registry::NpmPackageVersionDistInfo; use super::semver::NpmVersion; @@ -159,7 +164,7 @@ impl ReadonlyNpmCache { std::fs::create_dir_all(root_dir) .with_context(|| format!("Error creating {}", root_dir.display()))?; } - Ok(crate::fs_util::canonicalize_path(root_dir)?) + Ok(canonicalize_path(root_dir)?) } // this may fail on readonly file systems, so just ignore if so @@ -224,7 +229,7 @@ impl ReadonlyNpmCache { pub fn registry_folder(&self, registry_url: &Url) -> PathBuf { self .root_dir - .join(fs_util::root_url_to_safe_local_dirname(registry_url)) + .join(root_url_to_safe_local_dirname(registry_url)) } pub fn resolve_package_folder_id_from_specifier( @@ -249,7 +254,7 @@ impl ReadonlyNpmCache { .root_dir_url .join(&format!( "{}/", - fs_util::root_url_to_safe_local_dirname(registry_url) + root_url_to_safe_local_dirname(registry_url) .to_string_lossy() .replace('\\', "/") )) @@ -317,6 +322,8 @@ pub struct NpmCache { cache_setting: CacheSetting, http_client: HttpClient, progress_bar: ProgressBar, + /// ensures a package is only downloaded once per run + previously_reloaded_packages: Arc>>, } impl NpmCache { @@ -331,6 +338,7 @@ impl NpmCache { cache_setting, http_client, progress_bar, + previously_reloaded_packages: Default::default(), } } @@ -338,6 +346,26 @@ impl NpmCache { self.readonly.clone() } + pub fn cache_setting(&self) -> &CacheSetting { + &self.cache_setting + } + + /// Checks if the cache should be used for the provided name and version. + /// NOTE: Subsequent calls for the same package will always return `true` + /// to ensure a package is only downloaded once per run of the CLI. This + /// prevents downloads from re-occurring when someone has `--reload` and + /// and imports a dynamic import that imports the same package again for example. + fn should_use_global_cache_for_package( + &self, + package: (&str, &NpmVersion), + ) -> bool { + self.cache_setting.should_use_for_npm_package(package.0) + || !self + .previously_reloaded_packages + .lock() + .insert(format!("{}@{}", package.0, package.1)) + } + pub async fn ensure_package( &self, package: (&str, &NpmVersion), @@ -352,10 +380,6 @@ impl NpmCache { }) } - pub fn should_use_cache_for_npm_package(&self, package_name: &str) -> bool { - self.cache_setting.should_use_for_npm_package(package_name) - } - async fn ensure_package_inner( &self, package: (&str, &NpmVersion), @@ -367,11 +391,11 @@ impl NpmCache { package.1, registry_url, ); - if package_folder.exists() + if self.should_use_global_cache_for_package(package) + && package_folder.exists() // if this file exists, then the package didn't successfully extract // the first time, or another process is currently extracting the zip file && !package_folder.join(NPM_PACKAGE_SYNC_LOCK_FILENAME).exists() - && self.should_use_cache_for_npm_package(package.0) { return Ok(()); } else if self.cache_setting == CacheSetting::Only { @@ -435,12 +459,7 @@ impl NpmCache { with_folder_sync_lock( (id.name.as_str(), &id.version), &package_folder, - || { - fs_util::hard_link_dir_recursive( - &original_package_folder, - &package_folder, - ) - }, + || hard_link_dir_recursive(&original_package_folder, &package_folder), )?; Ok(()) } diff --git a/cli/npm/registry.rs b/cli/npm/registry.rs index 3f0a841655..9ba5653662 100644 --- a/cli/npm/registry.rs +++ b/cli/npm/registry.rs @@ -2,6 +2,7 @@ use std::cmp::Ordering; use std::collections::HashMap; +use std::collections::HashSet; use std::fs; use std::io::ErrorKind; use std::path::PathBuf; @@ -20,11 +21,11 @@ use deno_core::url::Url; use deno_runtime::colors; use serde::Serialize; -use crate::file_fetcher::CacheSetting; -use crate::fs_util; -use crate::http_cache::CACHE_PERM; +use crate::args::CacheSetting; +use crate::cache::CACHE_PERM; use crate::http_util::HttpClient; -use crate::progress_bar::ProgressBar; +use crate::util::fs::atomic_write_file; +use crate::util::progress_bar::ProgressBar; use super::cache::NpmCache; use super::resolution::NpmVersionMatcher; @@ -248,7 +249,6 @@ impl RealNpmRegistryApi { pub fn new( base_url: Url, cache: NpmCache, - cache_setting: CacheSetting, http_client: HttpClient, progress_bar: ProgressBar, ) -> Self { @@ -256,7 +256,7 @@ impl RealNpmRegistryApi { base_url, cache, mem_cache: Default::default(), - cache_setting, + previously_reloaded_packages: Default::default(), http_client, progress_bar, })) @@ -286,7 +286,7 @@ struct RealNpmRegistryApiInner { base_url: Url, cache: NpmCache, mem_cache: Mutex>>>, - cache_setting: CacheSetting, + previously_reloaded_packages: Mutex>, http_client: HttpClient, progress_bar: ProgressBar, } @@ -296,12 +296,16 @@ impl RealNpmRegistryApiInner { &self, name: &str, ) -> Result>, AnyError> { - let maybe_info = self.mem_cache.lock().get(name).cloned(); - if let Some(info) = maybe_info { - Ok(info) + let maybe_maybe_info = self.mem_cache.lock().get(name).cloned(); + if let Some(maybe_info) = maybe_maybe_info { + Ok(maybe_info) } else { let mut maybe_package_info = None; - if self.cache_setting.should_use_for_npm_package(name) { + if self.cache.cache_setting().should_use_for_npm_package(name) + // if this has been previously reloaded, then try loading from the + // file system cache + || !self.previously_reloaded_packages.lock().insert(name.to_string()) + { // attempt to load from the file cache maybe_package_info = self.load_file_cached_package_info(name); } @@ -401,7 +405,7 @@ impl RealNpmRegistryApiInner { let file_cache_path = self.get_package_file_cache_path(name); let file_text = serde_json::to_string(&package_info)?; std::fs::create_dir_all(file_cache_path.parent().unwrap())?; - fs_util::atomic_write_file(&file_cache_path, file_text, CACHE_PERM)?; + atomic_write_file(&file_cache_path, file_text, CACHE_PERM)?; Ok(()) } @@ -409,15 +413,14 @@ impl RealNpmRegistryApiInner { &self, name: &str, ) -> Result, AnyError> { - if self.cache_setting == CacheSetting::Only { + if *self.cache.cache_setting() == CacheSetting::Only { return Err(custom_error( "NotCached", format!( "An npm specifier not found in cache: \"{}\", --cached-only is specified.", name ) - ) - ); + )); } let package_url = self.get_package_url(name); diff --git a/cli/npm/resolution/specifier.rs b/cli/npm/resolution/specifier.rs index b832540bd9..61adab4705 100644 --- a/cli/npm/resolution/specifier.rs +++ b/cli/npm/resolution/specifier.rs @@ -947,7 +947,6 @@ mod tests { is_dynamic: false, imports: None, resolver: None, - locker: None, module_analyzer: Some(&analyzer), reporter: None, }, diff --git a/cli/npm/resolvers/common.rs b/cli/npm/resolvers/common.rs index e3acef3f52..4f2a6d82a8 100644 --- a/cli/npm/resolvers/common.rs +++ b/cli/npm/resolvers/common.rs @@ -10,6 +10,7 @@ use deno_core::error::AnyError; use deno_core::futures; use deno_core::futures::future::BoxFuture; use deno_core::url::Url; +use deno_runtime::deno_node::NodeResolutionMode; use crate::args::Lockfile; use crate::npm::cache::should_sync_download; @@ -29,7 +30,7 @@ pub trait InnerNpmPackageResolver: Send + Sync { &self, name: &str, referrer: &ModuleSpecifier, - conditions: &[&str], + mode: NodeResolutionMode, ) -> Result; fn resolve_package_folder_from_specifier( diff --git a/cli/npm/resolvers/global.rs b/cli/npm/resolvers/global.rs index 044c889d8f..093e15deda 100644 --- a/cli/npm/resolvers/global.rs +++ b/cli/npm/resolvers/global.rs @@ -12,17 +12,17 @@ use deno_core::error::AnyError; use deno_core::futures::future::BoxFuture; use deno_core::futures::FutureExt; use deno_core::url::Url; -use deno_runtime::deno_node::PackageJson; -use deno_runtime::deno_node::TYPES_CONDITIONS; +use deno_runtime::deno_node::NodeResolutionMode; use crate::args::Lockfile; -use crate::fs_util; +use crate::npm::cache::NpmPackageCacheFolderId; use crate::npm::resolution::NpmResolution; use crate::npm::resolution::NpmResolutionSnapshot; use crate::npm::resolvers::common::cache_packages; use crate::npm::NpmCache; use crate::npm::NpmPackageId; use crate::npm::NpmPackageReq; +use crate::npm::NpmResolutionPackage; use crate::npm::RealNpmRegistryApi; use super::common::ensure_registry_read_permission; @@ -62,6 +62,17 @@ impl GlobalNpmPackageResolver { .cache .package_folder_for_id(&folder_id, &self.registry_url) } + + fn resolve_types_package( + &self, + package_name: &str, + referrer_pkg_id: &NpmPackageCacheFolderId, + ) -> Result { + let types_name = types_package_name(package_name); + self + .resolution + .resolve_package_from_package(&types_name, referrer_pkg_id) + } } impl InnerNpmPackageResolver for GlobalNpmPackageResolver { @@ -77,35 +88,25 @@ impl InnerNpmPackageResolver for GlobalNpmPackageResolver { &self, name: &str, referrer: &ModuleSpecifier, - conditions: &[&str], + mode: NodeResolutionMode, ) -> Result { let referrer_pkg_id = self .cache .resolve_package_folder_id_from_specifier(referrer, &self.registry_url)?; - let pkg_result = self - .resolution - .resolve_package_from_package(name, &referrer_pkg_id); - if conditions == TYPES_CONDITIONS && !name.starts_with("@types/") { - // When doing types resolution, the package must contain a "types" - // entry, or else it will then search for a @types package - if let Ok(pkg) = pkg_result { - let package_folder = self.package_folder(&pkg.id); - let package_json = PackageJson::load_skip_read_permission( - package_folder.join("package.json"), - )?; - if package_json.types.is_some() { - return Ok(package_folder); - } + let pkg = if mode.is_types() && !name.starts_with("@types/") { + // attempt to resolve the types package first, then fallback to the regular package + match self.resolve_types_package(name, &referrer_pkg_id) { + Ok(pkg) => pkg, + Err(_) => self + .resolution + .resolve_package_from_package(name, &referrer_pkg_id)?, } - - let name = types_package_name(name); - let pkg = self - .resolution - .resolve_package_from_package(&name, &referrer_pkg_id)?; - Ok(self.package_folder(&pkg.id)) } else { - Ok(self.package_folder(&pkg_result?.id)) - } + self + .resolution + .resolve_package_from_package(name, &referrer_pkg_id)? + }; + Ok(self.package_folder(&pkg.id)) } fn resolve_package_folder_from_specifier( @@ -125,7 +126,7 @@ impl InnerNpmPackageResolver for GlobalNpmPackageResolver { fn package_size(&self, package_id: &NpmPackageId) -> Result { let package_folder = self.package_folder(package_id); - Ok(fs_util::dir_size(&package_folder)?) + Ok(crate::util::fs::dir_size(&package_folder)?) } fn has_packages(&self) -> bool { diff --git a/cli/npm/resolvers/local.rs b/cli/npm/resolvers/local.rs index a6df641d19..69f275c709 100644 --- a/cli/npm/resolvers/local.rs +++ b/cli/npm/resolvers/local.rs @@ -10,6 +10,7 @@ use std::path::Path; use std::path::PathBuf; use std::sync::Arc; +use crate::util::fs::symlink_dir; use deno_ast::ModuleSpecifier; use deno_core::anyhow::bail; use deno_core::anyhow::Context; @@ -18,12 +19,11 @@ use deno_core::futures::future::BoxFuture; use deno_core::futures::FutureExt; use deno_core::url::Url; use deno_runtime::deno_core::futures; +use deno_runtime::deno_node::NodeResolutionMode; use deno_runtime::deno_node::PackageJson; -use deno_runtime::deno_node::TYPES_CONDITIONS; use tokio::task::JoinHandle; use crate::args::Lockfile; -use crate::fs_util; use crate::npm::cache::mixed_case_package_name_encode; use crate::npm::cache::should_sync_download; use crate::npm::cache::NpmPackageCacheFolderId; @@ -34,6 +34,8 @@ use crate::npm::NpmPackageId; use crate::npm::NpmPackageReq; use crate::npm::NpmResolutionPackage; use crate::npm::RealNpmRegistryApi; +use crate::util::fs::copy_dir_recursive; +use crate::util::fs::hard_link_dir_recursive; use super::common::ensure_registry_read_permission; use super::common::types_package_name; @@ -150,7 +152,7 @@ impl InnerNpmPackageResolver for LocalNpmPackageResolver { &self, name: &str, referrer: &ModuleSpecifier, - conditions: &[&str], + mode: NodeResolutionMode, ) -> Result { let local_path = self.resolve_folder_for_specifier(referrer)?; let package_root_path = self.resolve_package_root(&local_path); @@ -160,7 +162,7 @@ impl InnerNpmPackageResolver for LocalNpmPackageResolver { let sub_dir = join_package_name(current_folder, name); if sub_dir.is_dir() { // if doing types resolution, only resolve the package if it specifies a types property - if conditions == TYPES_CONDITIONS && !name.starts_with("@types/") { + if mode.is_types() && !name.starts_with("@types/") { let package_json = PackageJson::load_skip_read_permission( sub_dir.join("package.json"), )?; @@ -173,7 +175,7 @@ impl InnerNpmPackageResolver for LocalNpmPackageResolver { } // if doing type resolution, check for the existance of a @types package - if conditions == TYPES_CONDITIONS && !name.starts_with("@types/") { + if mode.is_types() && !name.starts_with("@types/") { let sub_dir = join_package_name(current_folder, &types_package_name(name)); if sub_dir.is_dir() { @@ -203,7 +205,7 @@ impl InnerNpmPackageResolver for LocalNpmPackageResolver { fn package_size(&self, package_id: &NpmPackageId) -> Result { let package_folder_path = self.get_package_id_folder(package_id)?; - Ok(fs_util::dir_size(&package_folder_path)?) + Ok(crate::util::fs::dir_size(&package_folder_path)?) } fn has_packages(&self) -> bool { @@ -291,7 +293,9 @@ async fn sync_resolution_with_fs( get_package_folder_id_folder_name(&package.get_package_cache_folder_id()); let folder_path = deno_local_registry_dir.join(&folder_name); let initialized_file = folder_path.join(".initialized"); - if !cache.should_use_cache_for_npm_package(&package.id.name) + if !cache + .cache_setting() + .should_use_for_npm_package(&package.id.name) || !initialized_file.exists() { let cache = cache.clone(); @@ -316,7 +320,7 @@ async fn sync_resolution_with_fs( ®istry_url, ); // for now copy, but in the future consider hard linking - fs_util::copy_dir_recursive(&cache_folder, &package_path)?; + copy_dir_recursive(&cache_folder, &package_path)?; // write out a file that indicates this folder has been initialized fs::write(initialized_file, "")?; Ok(()) @@ -354,7 +358,7 @@ async fn sync_resolution_with_fs( .join("node_modules"), &package.id.name, ); - fs_util::hard_link_dir_recursive(&source_path, &package_path)?; + hard_link_dir_recursive(&source_path, &package_path)?; // write out a file that indicates this folder has been initialized fs::write(initialized_file, "")?; } @@ -465,7 +469,7 @@ fn symlink_package_dir( #[cfg(windows)] return junction_or_symlink_dir(old_path, new_path); #[cfg(not(windows))] - fs_util::symlink_dir(old_path, new_path) + symlink_dir(old_path, new_path) } #[cfg(windows)] @@ -475,6 +479,7 @@ fn junction_or_symlink_dir( ) -> Result<(), AnyError> { // Use junctions because they're supported on ntfs file systems without // needing to elevate privileges on Windows + match junction::create(old_path, new_path) { Ok(()) => Ok(()), Err(junction_err) => { @@ -484,7 +489,7 @@ fn junction_or_symlink_dir( log::warn!("Error creating junction. {:#}", junction_err); } - match fs_util::symlink_dir(old_path, new_path) { + match symlink_dir(old_path, new_path) { Ok(()) => Ok(()), Err(symlink_err) => bail!( concat!( diff --git a/cli/npm/resolvers/mod.rs b/cli/npm/resolvers/mod.rs index 869874c8b6..a9c459d122 100644 --- a/cli/npm/resolvers/mod.rs +++ b/cli/npm/resolvers/mod.rs @@ -11,6 +11,7 @@ use deno_core::error::custom_error; use deno_core::error::AnyError; use deno_core::parking_lot::Mutex; use deno_core::serde_json; +use deno_runtime::deno_node::NodeResolutionMode; use deno_runtime::deno_node::PathClean; use deno_runtime::deno_node::RequireNpmResolver; use global::GlobalNpmPackageResolver; @@ -23,7 +24,7 @@ use std::path::PathBuf; use std::sync::Arc; use crate::args::Lockfile; -use crate::fs_util; +use crate::util::fs::canonicalize_path_maybe_not_exists; use self::common::InnerNpmPackageResolver; use self::local::LocalNpmPackageResolver; @@ -187,8 +188,12 @@ impl NpmPackageResolver { let path = self .inner .resolve_package_folder_from_deno_module(pkg_req)?; - let path = fs_util::canonicalize_path_maybe_not_exists(&path)?; - log::debug!("Resolved {} to {}", pkg_req, path.display()); + let path = canonicalize_path_maybe_not_exists(&path)?; + log::debug!( + "Resolved package folder of {} to {}", + pkg_req, + path.display() + ); Ok(path) } @@ -197,11 +202,11 @@ impl NpmPackageResolver { &self, name: &str, referrer: &ModuleSpecifier, - conditions: &[&str], + mode: NodeResolutionMode, ) -> Result { let path = self .inner - .resolve_package_folder_from_package(name, referrer, conditions)?; + .resolve_package_folder_from_package(name, referrer, mode)?; log::debug!("Resolved {} from {} to {}", name, referrer, path.display()); Ok(path) } @@ -216,7 +221,11 @@ impl NpmPackageResolver { let path = self .inner .resolve_package_folder_from_specifier(specifier)?; - log::debug!("Resolved {} to {}", specifier, path.display()); + log::debug!( + "Resolved package folder of {} to {}", + specifier, + path.display() + ); Ok(path) } @@ -330,10 +339,10 @@ impl RequireNpmResolver for NpmPackageResolver { &self, specifier: &str, referrer: &std::path::Path, - conditions: &[&str], + mode: NodeResolutionMode, ) -> Result { let referrer = path_to_specifier(referrer)?; - self.resolve_package_folder_from_package(specifier, &referrer, conditions) + self.resolve_package_folder_from_package(specifier, &referrer, mode) } fn resolve_package_folder_from_path( diff --git a/cli/ops/testing.rs b/cli/ops/testing.rs index 727ccdf662..9479ebdc13 100644 --- a/cli/ops/testing.rs +++ b/cli/ops/testing.rs @@ -1,10 +1,12 @@ // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. +use crate::tools::test::FailFastTracker; use crate::tools::test::TestDescription; use crate::tools::test::TestEvent; use crate::tools::test::TestEventSender; use crate::tools::test::TestFilter; use crate::tools::test::TestLocation; +use crate::tools::test::TestResult; use crate::tools::test::TestStepDescription; use deno_core::error::generic_error; @@ -23,7 +25,11 @@ use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use uuid::Uuid; -pub fn init(sender: TestEventSender, filter: TestFilter) -> Extension { +pub fn init( + sender: TestEventSender, + fail_fast_tracker: FailFastTracker, + filter: TestFilter, +) -> Extension { Extension::builder() .ops(vec![ op_pledge_test_permissions::decl(), @@ -32,9 +38,11 @@ pub fn init(sender: TestEventSender, filter: TestFilter) -> Extension { op_register_test::decl(), op_register_test_step::decl(), op_dispatch_test_event::decl(), + op_tests_should_stop::decl(), ]) .state(move |state| { state.put(sender.clone()); + state.put(fail_fast_tracker.clone()); state.put(filter.clone()); Ok(()) }) @@ -178,7 +186,18 @@ fn op_dispatch_test_event( state: &mut OpState, event: TestEvent, ) -> Result<(), AnyError> { + if matches!( + event, + TestEvent::Result(_, TestResult::Cancelled | TestResult::Failed(_), _) + ) { + state.borrow::().add_failure(); + } let mut sender = state.borrow::().clone(); sender.send(event).ok(); Ok(()) } + +#[op] +fn op_tests_should_stop(state: &mut OpState) -> bool { + state.borrow::().should_stop() +} diff --git a/cli/proc_state.rs b/cli/proc_state.rs index dc80ca8db7..aae606c806 100644 --- a/cli/proc_state.rs +++ b/cli/proc_state.rs @@ -11,6 +11,7 @@ use crate::cache; use crate::cache::DenoDir; use crate::cache::EmitCache; use crate::cache::FastInsecureHasher; +use crate::cache::HttpCache; use crate::cache::NodeAnalysisCache; use crate::cache::ParsedSourceCache; use crate::cache::TypeCheckCache; @@ -19,7 +20,6 @@ use crate::file_fetcher::FileFetcher; use crate::graph_util::graph_lock_or_exit; use crate::graph_util::GraphData; use crate::graph_util::ModuleEntry; -use crate::http_cache; use crate::http_util::HttpClient; use crate::node; use crate::node::NodeResolution; @@ -28,9 +28,9 @@ use crate::npm::NpmCache; use crate::npm::NpmPackageReference; use crate::npm::NpmPackageResolver; use crate::npm::RealNpmRegistryApi; -use crate::progress_bar::ProgressBar; use crate::resolver::CliResolver; use crate::tools::check; +use crate::util::progress_bar::ProgressBar; use deno_ast::MediaType; use deno_core::anyhow::anyhow; @@ -53,6 +53,7 @@ use deno_graph::source::Resolver; use deno_graph::ModuleKind; use deno_graph::Resolved; use deno_runtime::deno_broadcast_channel::InMemoryBroadcastChannel; +use deno_runtime::deno_node::NodeResolutionMode; use deno_runtime::deno_tls::rustls::RootCertStore; use deno_runtime::deno_web::BlobStore; use deno_runtime::inspector_server::InspectorServer; @@ -153,7 +154,7 @@ impl ProcState { let compiled_wasm_module_store = CompiledWasmModuleStore::default(); let dir = cli_options.resolve_deno_dir()?; let deps_cache_location = dir.deps_folder_path(); - let http_cache = http_cache::HttpCache::new(&deps_cache_location); + let http_cache = HttpCache::new(&deps_cache_location); let root_cert_store = cli_options.resolve_root_cert_store()?; let cache_usage = cli_options.cache_setting(); let progress_bar = ProgressBar::default(); @@ -225,7 +226,6 @@ impl ProcState { let api = RealNpmRegistryApi::new( registry_url, npm_cache.clone(), - cli_options.cache_setting(), http_client, progress_bar.clone(), ); @@ -329,7 +329,6 @@ impl ProcState { root_permissions.clone(), dynamic_permissions.clone(), ); - let maybe_locker = Lockfile::as_maybe_locker(self.lockfile.clone()); let maybe_imports = self.options.to_maybe_imports()?; let maybe_resolver = self.maybe_resolver.as_ref().map(|r| r.as_graph_resolver()); @@ -383,16 +382,16 @@ impl ProcState { is_dynamic, imports: maybe_imports, resolver: maybe_resolver, - locker: maybe_locker, module_analyzer: Some(&*analyzer), reporter: maybe_file_watcher_reporter, }, ) .await; - // If there was a locker, validate the integrity of all the modules in the - // locker. - graph_lock_or_exit(&graph); + // If there is a lockfile, validate the integrity of all the modules. + if let Some(lockfile) = &self.lockfile { + graph_lock_or_exit(&graph, &mut lockfile.lock()); + } // Determine any modules that have already been emitted this session and // should be skipped. @@ -515,7 +514,7 @@ impl ProcState { .handle_node_resolve_result(node::node_resolve( specifier, &referrer, - node::NodeResolutionMode::Execution, + NodeResolutionMode::Execution, &self.npm_resolver, )) .with_context(|| { @@ -548,7 +547,7 @@ impl ProcState { return self .handle_node_resolve_result(node::node_resolve_npm_reference( &reference, - node::NodeResolutionMode::Execution, + NodeResolutionMode::Execution, &self.npm_resolver, )) .with_context(|| format!("Could not resolve '{}'.", reference)); @@ -639,7 +638,6 @@ impl ProcState { roots: Vec<(ModuleSpecifier, ModuleKind)>, loader: &mut dyn Loader, ) -> Result { - let maybe_locker = Lockfile::as_maybe_locker(self.lockfile.clone()); let maybe_imports = self.options.to_maybe_imports()?; let maybe_cli_resolver = CliResolver::maybe_new( @@ -657,7 +655,6 @@ impl ProcState { is_dynamic: false, imports: maybe_imports, resolver: maybe_graph_resolver, - locker: maybe_locker, module_analyzer: Some(&*analyzer), reporter: None, }, diff --git a/cli/tests/bench_tests.rs b/cli/tests/bench_tests.rs new file mode 100644 index 0000000000..77c1e2a7ef --- /dev/null +++ b/cli/tests/bench_tests.rs @@ -0,0 +1,200 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +use deno_core::url::Url; +use test_util as util; + +mod bench { + use super::*; + + itest!(overloads { + args: "bench bench/overloads.ts", + exit_code: 0, + output: "bench/overloads.out", + }); + + itest!(meta { + args: "bench bench/meta.ts", + exit_code: 0, + output: "bench/meta.out", + }); + + itest!(pass { + args: "bench bench/pass.ts", + exit_code: 0, + output: "bench/pass.out", + }); + + itest!(ignore { + args: "bench bench/ignore.ts", + exit_code: 0, + output: "bench/ignore.out", + }); + + itest!(ignore_permissions { + args: "bench bench/ignore_permissions.ts", + exit_code: 0, + output: "bench/ignore_permissions.out", + }); + + itest!(fail { + args: "bench bench/fail.ts", + exit_code: 1, + output: "bench/fail.out", + }); + + itest!(collect { + args: "bench --ignore=bench/collect/ignore bench/collect", + exit_code: 0, + output: "bench/collect.out", + }); + + itest!(load_unload { + args: "bench bench/load_unload.ts", + exit_code: 0, + output: "bench/load_unload.out", + }); + + itest!(interval { + args: "bench bench/interval.ts", + exit_code: 0, + output: "bench/interval.out", + }); + + itest!(quiet { + args: "bench --quiet bench/quiet.ts", + exit_code: 0, + output: "bench/quiet.out", + }); + + itest!(only { + args: "bench bench/only.ts", + exit_code: 1, + output: "bench/only.out", + }); + + itest!(multifile_summary { + args: "bench bench/group_baseline.ts bench/pass.ts bench/group_baseline.ts", + exit_code: 0, + output: "bench/multifile_summary.out", + }); + + itest!(no_check { + args: "bench --no-check bench/no_check.ts", + exit_code: 1, + output: "bench/no_check.out", + }); + + itest!(allow_all { + args: "bench --allow-all bench/allow_all.ts", + exit_code: 0, + output: "bench/allow_all.out", + }); + + itest!(allow_none { + args: "bench bench/allow_none.ts", + exit_code: 1, + output: "bench/allow_none.out", + }); + + itest!(exit_sanitizer { + args: "bench bench/exit_sanitizer.ts", + output: "bench/exit_sanitizer.out", + exit_code: 1, + }); + + itest!(clear_timeout { + args: "bench bench/clear_timeout.ts", + exit_code: 0, + output: "bench/clear_timeout.out", + }); + + itest!(finally_timeout { + args: "bench bench/finally_timeout.ts", + exit_code: 1, + output: "bench/finally_timeout.out", + }); + + itest!(group_baseline { + args: "bench bench/group_baseline.ts", + exit_code: 0, + output: "bench/group_baseline.out", + }); + + itest!(unresolved_promise { + args: "bench bench/unresolved_promise.ts", + exit_code: 1, + output: "bench/unresolved_promise.out", + }); + + itest!(unhandled_rejection { + args: "bench bench/unhandled_rejection.ts", + exit_code: 1, + output: "bench/unhandled_rejection.out", + }); + + itest!(filter { + args: "bench --filter=foo bench/filter", + exit_code: 0, + output: "bench/filter.out", + }); + + itest!(no_prompt_by_default { + args: "bench --quiet bench/no_prompt_by_default.ts", + exit_code: 1, + output: "bench/no_prompt_by_default.out", + }); + + itest!(no_prompt_with_denied_perms { + args: "bench --quiet --allow-read bench/no_prompt_with_denied_perms.ts", + exit_code: 1, + output: "bench/no_prompt_with_denied_perms.out", + }); + + itest!(check_local_by_default { + args: "bench --quiet bench/check_local_by_default.ts", + output: "bench/check_local_by_default.out", + http_server: true, + }); + + itest!(check_local_by_default2 { + args: "bench --quiet bench/check_local_by_default2.ts", + output: "bench/check_local_by_default2.out", + http_server: true, + exit_code: 1, + }); + + #[test] + fn recursive_permissions_pledge() { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bench") + .arg("bench/recursive_permissions_pledge.js") + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + assert!(String::from_utf8(output.stderr).unwrap().contains( + "pledge test permissions called before restoring previous pledge" + )); + } + + #[test] + fn file_protocol() { + let file_url = + Url::from_file_path(util::testdata_path().join("bench/file_protocol.ts")) + .unwrap() + .to_string(); + + (util::CheckOutputIntegrationTest { + args_vec: vec!["bench", &file_url], + exit_code: 0, + output: "bench/file_protocol.out", + ..Default::default() + }) + .run(); + } +} diff --git a/cli/tests/bundle_tests.rs b/cli/tests/bundle_tests.rs new file mode 100644 index 0000000000..c3c9c396a0 --- /dev/null +++ b/cli/tests/bundle_tests.rs @@ -0,0 +1,473 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +use test_util as util; +use test_util::assert_contains; +use test_util::assert_ends_with; +use test_util::TempDir; + +mod bundle { + use super::*; + + #[test] + fn bundle_exports() { + // First we have to generate a bundle of some module that has exports. + let mod1 = util::testdata_path().join("subdir/mod1.ts"); + assert!(mod1.is_file()); + let t = TempDir::new(); + let bundle = t.path().join("mod1.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg(mod1) + .arg(&bundle) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + assert!(bundle.is_file()); + + // Now we try to use that bundle from another module. + let test = t.path().join("test.js"); + std::fs::write( + &test, + " + import { printHello3 } from \"./mod1.bundle.js\"; + printHello3(); ", + ) + .unwrap(); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg(&test) + .output() + .unwrap(); + // check the output of the test.ts program. + assert_ends_with!( + std::str::from_utf8(&output.stdout).unwrap().trim(), + "Hello", + ); + assert_eq!(output.stderr, b""); + } + + #[test] + fn bundle_exports_no_check() { + // First we have to generate a bundle of some module that has exports. + let mod1 = util::testdata_path().join("subdir/mod1.ts"); + assert!(mod1.is_file()); + let t = TempDir::new(); + let bundle = t.path().join("mod1.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg(mod1) + .arg(&bundle) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + assert!(bundle.is_file()); + + // Now we try to use that bundle from another module. + let test = t.path().join("test.js"); + std::fs::write( + &test, + " + import { printHello3 } from \"./mod1.bundle.js\"; + printHello3(); ", + ) + .unwrap(); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg(&test) + .output() + .unwrap(); + // check the output of the test.ts program. + assert_ends_with!( + std::str::from_utf8(&output.stdout).unwrap().trim(), + "Hello", + ); + assert_eq!(output.stderr, b""); + } + + #[test] + fn bundle_circular() { + // First we have to generate a bundle of some module that has exports. + let circular1_path = util::testdata_path().join("subdir/circular1.ts"); + assert!(circular1_path.is_file()); + let t = TempDir::new(); + let bundle_path = t.path().join("circular1.bundle.js"); + + // run this twice to ensure it works even when cached + for _ in 0..2 { + let mut deno = util::deno_cmd_with_deno_dir(&t) + .current_dir(util::testdata_path()) + .arg("bundle") + .arg(&circular1_path) + .arg(&bundle_path) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + assert!(bundle_path.is_file()); + } + + let output = util::deno_cmd_with_deno_dir(&t) + .current_dir(util::testdata_path()) + .arg("run") + .arg(&bundle_path) + .output() + .unwrap(); + // check the output of the the bundle program. + assert_ends_with!( + std::str::from_utf8(&output.stdout).unwrap().trim(), + "f2\nf1", + ); + assert_eq!(output.stderr, b""); + } + + #[test] + fn bundle_single_module() { + // First we have to generate a bundle of some module that has exports. + let single_module = util::testdata_path().join("subdir/single_module.ts"); + assert!(single_module.is_file()); + let t = TempDir::new(); + let bundle = t.path().join("single_module.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg(single_module) + .arg(&bundle) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + assert!(bundle.is_file()); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg(&bundle) + .output() + .unwrap(); + // check the output of the the bundle program. + assert_ends_with!( + std::str::from_utf8(&output.stdout).unwrap().trim(), + "Hello world!", + ); + assert_eq!(output.stderr, b""); + } + + #[test] + fn bundle_tla() { + // First we have to generate a bundle of some module that has exports. + let tla_import = util::testdata_path().join("subdir/tla.ts"); + assert!(tla_import.is_file()); + let t = TempDir::new(); + let bundle = t.path().join("tla.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg(tla_import) + .arg(&bundle) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + assert!(bundle.is_file()); + + // Now we try to use that bundle from another module. + let test = t.path().join("test.js"); + std::fs::write( + &test, + " + import { foo } from \"./tla.bundle.js\"; + console.log(foo); ", + ) + .unwrap(); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg(&test) + .output() + .unwrap(); + // check the output of the test.ts program. + assert_ends_with!( + std::str::from_utf8(&output.stdout).unwrap().trim(), + "Hello", + ); + assert_eq!(output.stderr, b""); + } + + #[test] + fn bundle_js() { + // First we have to generate a bundle of some module that has exports. + let mod6 = util::testdata_path().join("subdir/mod6.js"); + assert!(mod6.is_file()); + let t = TempDir::new(); + let bundle = t.path().join("mod6.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg(mod6) + .arg(&bundle) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + assert!(bundle.is_file()); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg(&bundle) + .output() + .unwrap(); + // check that nothing went to stderr + assert_eq!(output.stderr, b""); + } + + #[test] + fn bundle_dynamic_import() { + let _g = util::http_server(); + let dynamic_import = util::testdata_path().join("bundle/dynamic_import.ts"); + assert!(dynamic_import.is_file()); + let t = TempDir::new(); + let output_path = t.path().join("bundle_dynamic_import.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg(dynamic_import) + .arg(&output_path) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + assert!(output_path.is_file()); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-net") + .arg("--quiet") + .arg(&output_path) + .output() + .unwrap(); + // check the output of the test.ts program. + assert_ends_with!( + std::str::from_utf8(&output.stdout).unwrap().trim(), + "Hello", + ); + assert_eq!(output.stderr, b""); + } + + #[test] + fn bundle_import_map() { + let import = util::testdata_path().join("bundle/import_map/main.ts"); + let import_map_path = + util::testdata_path().join("bundle/import_map/import_map.json"); + assert!(import.is_file()); + let t = TempDir::new(); + let output_path = t.path().join("import_map.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg("--import-map") + .arg(import_map_path) + .arg(import) + .arg(&output_path) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + assert!(output_path.is_file()); + + // Now we try to use that bundle from another module. + let test = t.path().join("test.js"); + std::fs::write( + &test, + " + import { printHello3 } from \"./import_map.bundle.js\"; + printHello3(); ", + ) + .unwrap(); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--check") + .arg(&test) + .output() + .unwrap(); + // check the output of the test.ts program. + assert_ends_with!( + std::str::from_utf8(&output.stdout).unwrap().trim(), + "Hello", + ); + assert_eq!(output.stderr, b""); + } + + #[test] + fn bundle_import_map_no_check() { + let import = util::testdata_path().join("bundle/import_map/main.ts"); + let import_map_path = + util::testdata_path().join("bundle/import_map/import_map.json"); + assert!(import.is_file()); + let t = TempDir::new(); + let output_path = t.path().join("import_map.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg("--import-map") + .arg(import_map_path) + .arg(import) + .arg(&output_path) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + assert!(output_path.is_file()); + + // Now we try to use that bundle from another module. + let test = t.path().join("test.js"); + std::fs::write( + &test, + " + import { printHello3 } from \"./import_map.bundle.js\"; + printHello3(); ", + ) + .unwrap(); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg(&test) + .output() + .unwrap(); + // check the output of the test.ts program. + assert_ends_with!( + std::str::from_utf8(&output.stdout).unwrap().trim(), + "Hello", + ); + assert_eq!(output.stderr, b""); + } + + #[test] + fn bundle_json_module() { + // First we have to generate a bundle of some module that has exports. + let mod7 = util::testdata_path().join("subdir/mod7.js"); + assert!(mod7.is_file()); + let t = TempDir::new(); + let bundle = t.path().join("mod7.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg(mod7) + .arg(&bundle) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + assert!(bundle.is_file()); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg(&bundle) + .output() + .unwrap(); + // check that nothing went to stderr + assert_eq!(output.stderr, b""); + // ensure the output looks right + assert_contains!(String::from_utf8(output.stdout).unwrap(), "with space",); + } + + #[test] + fn bundle_json_module_escape_sub() { + // First we have to generate a bundle of some module that has exports. + let mod8 = util::testdata_path().join("subdir/mod8.js"); + assert!(mod8.is_file()); + let t = TempDir::new(); + let bundle = t.path().join("mod8.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg(mod8) + .arg(&bundle) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + assert!(bundle.is_file()); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg(&bundle) + .output() + .unwrap(); + // check that nothing went to stderr + assert_eq!(output.stderr, b""); + // make sure the output looks right and the escapes were effective + assert_contains!( + String::from_utf8(output.stdout).unwrap(), + "${globalThis}`and string literal`", + ); + } + + itest!(lockfile_check_error { + args: "bundle --lock=bundle/lockfile/check_error.json http://127.0.0.1:4545/subdir/mod1.ts", + output: "bundle/lockfile/check_error.out", + exit_code: 10, + http_server: true, +}); + + itest!(bundle { + args: "bundle subdir/mod1.ts", + output: "bundle/bundle.test.out", + }); + + itest!(bundle_jsx { + args: "bundle run/jsx_import_from_ts.ts", + output: "bundle/jsx.out", + }); + + itest!(error_bundle_with_bare_import { + args: "bundle bundle/bare_imports/error_with_bare_import.ts", + output: "bundle/bare_imports/error_with_bare_import.ts.out", + exit_code: 1, + }); + + itest!(ts_decorators_bundle { + args: "bundle bundle/decorators/ts_decorators.ts", + output: "bundle/decorators/ts_decorators.out", + }); + + itest!(bundle_export_specifier_with_alias { + args: "bundle bundle/file_tests-fixture16.ts", + output: "bundle/fixture16.out", + }); + + itest!(bundle_ignore_directives { + args: "bundle subdir/mod1.ts", + output: "bundle/ignore_directives.test.out", + }); + + itest!(check_local_by_default_no_errors { + args: "bundle --quiet bundle/check_local_by_default/no_errors.ts", + output: "bundle/check_local_by_default/no_errors.out", + http_server: true, + }); + + itest!(check_local_by_default_type_error { + args: "bundle --quiet bundle/check_local_by_default/type_error.ts", + output: "bundle/check_local_by_default/type_error.out", + http_server: true, + exit_code: 1, + }); +} diff --git a/cli/tests/cache_tests.rs b/cli/tests/cache_tests.rs new file mode 100644 index 0000000000..c23ee8e5c8 --- /dev/null +++ b/cli/tests/cache_tests.rs @@ -0,0 +1,102 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +mod cache { + use super::*; + itest!(_036_import_map_fetch { + args: + "cache --quiet --reload --import-map=import_maps/import_map.json import_maps/test.ts", + output: "cache/036_import_map_fetch.out", + }); + + itest!(_037_fetch_multiple { + args: "cache --reload --check=all run/fetch/test.ts run/fetch/other.ts", + http_server: true, + output: "cache/037_fetch_multiple.out", + }); + + itest!(_095_cache_with_bare_import { + args: "cache cache/095_cache_with_bare_import.ts", + output: "cache/095_cache_with_bare_import.ts.out", + exit_code: 1, + }); + + itest!(cache_extensionless { + args: "cache --reload --check=all http://localhost:4545/subdir/no_js_ext", + output: "cache/cache_extensionless.out", + http_server: true, + }); + + itest!(cache_random_extension { + args: + "cache --reload --check=all http://localhost:4545/subdir/no_js_ext@1.0.0", + output: "cache/cache_random_extension.out", + http_server: true, + }); + + itest!(performance_stats { + args: "cache --reload --check=all --log-level debug run/002_hello.ts", + output: "cache/performance_stats.out", + }); + + itest!(redirect_cache { + http_server: true, + args: + "cache --reload --check=all http://localhost:4548/subdir/redirects/a.ts", + output: "cache/redirect_cache.out", + }); + + itest!(ignore_require { + args: "cache --reload --no-check cache/ignore_require.js", + output_str: Some(""), + exit_code: 0, + }); + + // This test only runs on linux, because it hardcodes the XDG_CACHE_HOME env var + // which is only used on linux. + #[cfg(target_os = "linux")] + #[test] + fn relative_home_dir() { + use test_util as util; + use test_util::TempDir; + + let deno_dir = TempDir::new_in(&util::testdata_path()); + let path = deno_dir.path().strip_prefix(util::testdata_path()).unwrap(); + + let mut deno_cmd = util::deno_cmd(); + let output = deno_cmd + .current_dir(util::testdata_path()) + .env("XDG_CACHE_HOME", path) + .env_remove("HOME") + .env_remove("DENO_DIR") + .arg("cache") + .arg("--reload") + .arg("--no-check") + .arg("run/002_hello.ts") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b""); + } + + itest!(check_local_by_default { + args: "cache --quiet cache/check_local_by_default.ts", + output: "cache/check_local_by_default.out", + http_server: true, + }); + + itest!(check_local_by_default2 { + args: "cache --quiet cache/check_local_by_default2.ts", + output: "cache/check_local_by_default2.out", + http_server: true, + }); + + itest!(json_import { + // should not error + args: "cache --quiet cache/json_import/main.ts", + }); +} diff --git a/cli/tests/cert_tests.rs b/cli/tests/cert_tests.rs new file mode 100644 index 0000000000..e3c17b8908 --- /dev/null +++ b/cli/tests/cert_tests.rs @@ -0,0 +1,321 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +use deno_runtime::deno_net::ops_tls::TlsStream; +use deno_runtime::deno_tls::rustls; +use deno_runtime::deno_tls::rustls_pemfile; +use std::io::BufReader; +use std::io::Cursor; +use std::io::Read; +use std::process::Command; +use std::sync::Arc; +use test_util as util; +use test_util::TempDir; +use tokio::task::LocalSet; + +mod cert { + use super::*; + itest_flaky!(cafile_url_imports { + args: + "run --quiet --reload --cert tls/RootCA.pem cert/cafile_url_imports.ts", + output: "cert/cafile_url_imports.ts.out", + http_server: true, + }); + + itest_flaky!(cafile_ts_fetch { + args: + "run --quiet --reload --allow-net --cert tls/RootCA.pem cert/cafile_ts_fetch.ts", + output: "cert/cafile_ts_fetch.ts.out", + http_server: true, + }); + + itest_flaky!(cafile_eval { + args: "eval --cert tls/RootCA.pem fetch('https://localhost:5545/cert/cafile_ts_fetch.ts.out').then(r=>r.text()).then(t=>console.log(t.trimEnd()))", + output: "cert/cafile_ts_fetch.ts.out", + http_server: true, + }); + + itest_flaky!(cafile_info { + args: + "info --quiet --cert tls/RootCA.pem https://localhost:5545/cert/cafile_info.ts", + output: "cert/cafile_info.ts.out", + http_server: true, + }); + + itest_flaky!(cafile_url_imports_unsafe_ssl { + args: "run --quiet --reload --unsafely-ignore-certificate-errors=localhost cert/cafile_url_imports.ts", + output: "cert/cafile_url_imports_unsafe_ssl.ts.out", + http_server: true, + }); + + itest_flaky!(cafile_ts_fetch_unsafe_ssl { + args: + "run --quiet --reload --allow-net --unsafely-ignore-certificate-errors cert/cafile_ts_fetch.ts", + output: "cert/cafile_ts_fetch_unsafe_ssl.ts.out", + http_server: true, + }); + + itest!(deno_land_unsafe_ssl { + args: + "run --quiet --reload --allow-net --unsafely-ignore-certificate-errors=deno.land cert/deno_land_unsafe_ssl.ts", + output: "cert/deno_land_unsafe_ssl.ts.out", + }); + + itest!(ip_address_unsafe_ssl { + args: + "run --quiet --reload --allow-net --unsafely-ignore-certificate-errors=1.1.1.1 cert/ip_address_unsafe_ssl.ts", + output: "cert/ip_address_unsafe_ssl.ts.out", + }); + + itest!(localhost_unsafe_ssl { + args: + "run --quiet --reload --allow-net --unsafely-ignore-certificate-errors=deno.land cert/cafile_url_imports.ts", + output: "cert/localhost_unsafe_ssl.ts.out", + http_server: true, + exit_code: 1, + }); + + #[flaky_test::flaky_test] + fn cafile_env_fetch() { + use deno_core::url::Url; + let _g = util::http_server(); + let deno_dir = TempDir::new(); + let module_url = + Url::parse("https://localhost:5545/cert/cafile_url_imports.ts").unwrap(); + let cafile = util::testdata_path().join("tls/RootCA.pem"); + let output = Command::new(util::deno_exe_path()) + .env("DENO_DIR", deno_dir.path()) + .env("DENO_CERT", cafile) + .current_dir(util::testdata_path()) + .arg("cache") + .arg(module_url.to_string()) + .output() + .expect("Failed to spawn script"); + assert!(output.status.success()); + } + + #[flaky_test::flaky_test] + fn cafile_fetch() { + use deno_core::url::Url; + let _g = util::http_server(); + let deno_dir = TempDir::new(); + let module_url = + Url::parse("http://localhost:4545/cert/cafile_url_imports.ts").unwrap(); + let cafile = util::testdata_path().join("tls/RootCA.pem"); + let output = Command::new(util::deno_exe_path()) + .env("DENO_DIR", deno_dir.path()) + .current_dir(util::testdata_path()) + .arg("cache") + .arg("--cert") + .arg(cafile) + .arg(module_url.to_string()) + .output() + .expect("Failed to spawn script"); + assert!(output.status.success()); + let out = std::str::from_utf8(&output.stdout).unwrap(); + assert_eq!(out, ""); + } + + #[flaky_test::flaky_test] + fn cafile_install_remote_module() { + let _g = util::http_server(); + let temp_dir = TempDir::new(); + let bin_dir = temp_dir.path().join("bin"); + std::fs::create_dir(&bin_dir).unwrap(); + let deno_dir = TempDir::new(); + let cafile = util::testdata_path().join("tls/RootCA.pem"); + + let install_output = Command::new(util::deno_exe_path()) + .env("DENO_DIR", deno_dir.path()) + .current_dir(util::testdata_path()) + .arg("install") + .arg("--cert") + .arg(cafile) + .arg("--root") + .arg(temp_dir.path()) + .arg("-n") + .arg("echo_test") + .arg("https://localhost:5545/echo.ts") + .output() + .expect("Failed to spawn script"); + println!("{}", std::str::from_utf8(&install_output.stdout).unwrap()); + eprintln!("{}", std::str::from_utf8(&install_output.stderr).unwrap()); + assert!(install_output.status.success()); + + let mut echo_test_path = bin_dir.join("echo_test"); + if cfg!(windows) { + echo_test_path = echo_test_path.with_extension("cmd"); + } + assert!(echo_test_path.exists()); + + let output = Command::new(echo_test_path) + .current_dir(temp_dir.path()) + .arg("foo") + .env("PATH", util::target_dir()) + .output() + .expect("failed to spawn script"); + let stdout = std::str::from_utf8(&output.stdout).unwrap().trim(); + assert!(stdout.ends_with("foo")); + } + + #[flaky_test::flaky_test] + fn cafile_bundle_remote_exports() { + let _g = util::http_server(); + + // First we have to generate a bundle of some remote module that has exports. + let mod1 = "https://localhost:5545/subdir/mod1.ts"; + let cafile = util::testdata_path().join("tls/RootCA.pem"); + let t = TempDir::new(); + let bundle = t.path().join("mod1.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg("--cert") + .arg(cafile) + .arg(mod1) + .arg(&bundle) + .spawn() + .expect("failed to spawn script"); + let status = deno.wait().expect("failed to wait for the child process"); + assert!(status.success()); + assert!(bundle.is_file()); + + // Now we try to use that bundle from another module. + let test = t.path().join("test.js"); + std::fs::write( + &test, + " + import { printHello3 } from \"./mod1.bundle.js\"; + printHello3(); ", + ) + .expect("error writing file"); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--check") + .arg(&test) + .output() + .expect("failed to spawn script"); + // check the output of the test.ts program. + assert!(std::str::from_utf8(&output.stdout) + .unwrap() + .trim() + .ends_with("Hello")); + assert_eq!(output.stderr, b""); + } + + #[tokio::test] + async fn listen_tls_alpn() { + // TLS streams require the presence of an ambient local task set to gracefully + // close dropped connections in the background. + LocalSet::new() + .run_until(async { + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--unstable") + .arg("--quiet") + .arg("--allow-net") + .arg("--allow-read") + .arg("./cert/listen_tls_alpn.ts") + .arg("4504") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let stdout = child.stdout.as_mut().unwrap(); + let mut msg = [0; 5]; + let read = stdout.read(&mut msg).unwrap(); + assert_eq!(read, 5); + assert_eq!(&msg, b"READY"); + + let mut reader = &mut BufReader::new(Cursor::new(include_bytes!( + "./testdata/tls/RootCA.crt" + ))); + let certs = rustls_pemfile::certs(&mut reader).unwrap(); + let mut root_store = rustls::RootCertStore::empty(); + root_store.add_parsable_certificates(&certs); + let mut cfg = rustls::ClientConfig::builder() + .with_safe_defaults() + .with_root_certificates(root_store) + .with_no_client_auth(); + cfg.alpn_protocols.push(b"foobar".to_vec()); + let cfg = Arc::new(cfg); + + let hostname = rustls::ServerName::try_from("localhost").unwrap(); + + let tcp_stream = tokio::net::TcpStream::connect("localhost:4504") + .await + .unwrap(); + let mut tls_stream = + TlsStream::new_client_side(tcp_stream, cfg, hostname); + + tls_stream.handshake().await.unwrap(); + + let (_, rustls_connection) = tls_stream.get_ref(); + let alpn = rustls_connection.alpn_protocol().unwrap(); + assert_eq!(alpn, b"foobar"); + + let status = child.wait().unwrap(); + assert!(status.success()); + }) + .await; + } + + #[tokio::test] + async fn listen_tls_alpn_fail() { + // TLS streams require the presence of an ambient local task set to gracefully + // close dropped connections in the background. + LocalSet::new() + .run_until(async { + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--unstable") + .arg("--quiet") + .arg("--allow-net") + .arg("--allow-read") + .arg("./cert/listen_tls_alpn_fail.ts") + .arg("4505") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let stdout = child.stdout.as_mut().unwrap(); + let mut msg = [0; 5]; + let read = stdout.read(&mut msg).unwrap(); + assert_eq!(read, 5); + assert_eq!(&msg, b"READY"); + + let mut reader = &mut BufReader::new(Cursor::new(include_bytes!( + "./testdata/tls/RootCA.crt" + ))); + let certs = rustls_pemfile::certs(&mut reader).unwrap(); + let mut root_store = rustls::RootCertStore::empty(); + root_store.add_parsable_certificates(&certs); + let mut cfg = rustls::ClientConfig::builder() + .with_safe_defaults() + .with_root_certificates(root_store) + .with_no_client_auth(); + cfg.alpn_protocols.push(b"boofar".to_vec()); + let cfg = Arc::new(cfg); + + let hostname = rustls::ServerName::try_from("localhost").unwrap(); + + let tcp_stream = tokio::net::TcpStream::connect("localhost:4505") + .await + .unwrap(); + let mut tls_stream = + TlsStream::new_client_side(tcp_stream, cfg, hostname); + + tls_stream.handshake().await.unwrap_err(); + + let (_, rustls_connection) = tls_stream.get_ref(); + assert!(rustls_connection.alpn_protocol().is_none()); + + let status = child.wait().unwrap(); + assert!(status.success()); + }) + .await; + } +} diff --git a/cli/tests/check_tests.rs b/cli/tests/check_tests.rs new file mode 100644 index 0000000000..54f9cc272e --- /dev/null +++ b/cli/tests/check_tests.rs @@ -0,0 +1,212 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +use std::process::Command; +use std::process::Stdio; +use test_util as util; +use util::TempDir; + +mod check { + use super::*; + itest!(_095_check_with_bare_import { + args: "check cache/095_cache_with_bare_import.ts", + output: "cache/095_cache_with_bare_import.ts.out", + exit_code: 1, + }); + + itest!(check_extensionless { + args: "check --reload http://localhost:4545/subdir/no_js_ext", + output: "cache/cache_extensionless.out", + http_server: true, + }); + + itest!(check_random_extension { + args: "check --reload http://localhost:4545/subdir/no_js_ext@1.0.0", + output: "cache/cache_random_extension.out", + http_server: true, + }); + + itest!(check_all { + args: "check --quiet --all check/check_all.ts", + output: "check/check_all.out", + http_server: true, + exit_code: 1, + }); + + itest!(check_all_local { + args: "check --quiet check/check_all.ts", + output_str: Some(""), + http_server: true, + }); + + itest!(module_detection_force { + args: "check --quiet check/module_detection_force/main.ts", + output_str: Some(""), + }); + + // Regression test for https://github.com/denoland/deno/issues/14937. + itest!(declaration_header_file_with_no_exports { + args: "check --quiet check/declaration_header_file_with_no_exports.ts", + output_str: Some(""), + }); + + itest!(check_npm_install_diagnostics { + args: "check --quiet check/npm_install_diagnostics/main.ts", + output: "check/npm_install_diagnostics/main.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + exit_code: 1, + }); + + itest!(check_export_equals_declaration_file { + args: "check --quiet check/export_equals_declaration_file/main.ts", + exit_code: 0, + }); + + #[test] + fn cache_switching_config_then_no_config() { + let deno_dir = util::new_deno_dir(); + assert!(does_type_checking(&deno_dir, true)); + assert!(does_type_checking(&deno_dir, false)); + + // should now not do type checking even when it changes + // configs because it previously did + assert!(!does_type_checking(&deno_dir, true)); + assert!(!does_type_checking(&deno_dir, false)); + + fn does_type_checking(deno_dir: &util::TempDir, with_config: bool) -> bool { + let mut cmd = util::deno_cmd_with_deno_dir(deno_dir); + cmd + .current_dir(util::testdata_path()) + .stderr(Stdio::piped()) + .arg("check") + .arg("check/cache_config_on_off/main.ts"); + if with_config { + cmd + .arg("--config") + .arg("check/cache_config_on_off/deno.json"); + } + let output = cmd.spawn().unwrap().wait_with_output().unwrap(); + assert!(output.status.success()); + + let stderr = std::str::from_utf8(&output.stderr).unwrap(); + stderr.contains("Check") + } + } + + #[test] + fn reload_flag() { + // should do type checking whenever someone specifies --reload + let deno_dir = util::new_deno_dir(); + assert!(does_type_checking(&deno_dir, false)); + assert!(!does_type_checking(&deno_dir, false)); + assert!(does_type_checking(&deno_dir, true)); + assert!(does_type_checking(&deno_dir, true)); + assert!(!does_type_checking(&deno_dir, false)); + + fn does_type_checking(deno_dir: &util::TempDir, reload: bool) -> bool { + let mut cmd = util::deno_cmd_with_deno_dir(deno_dir); + cmd + .current_dir(util::testdata_path()) + .stderr(Stdio::piped()) + .arg("check") + .arg("check/cache_config_on_off/main.ts"); + if reload { + cmd.arg("--reload"); + } + let output = cmd.spawn().unwrap().wait_with_output().unwrap(); + assert!(output.status.success()); + + let stderr = std::str::from_utf8(&output.stderr).unwrap(); + stderr.contains("Check") + } + } + + #[test] + fn typecheck_declarations_ns() { + let output = util::deno_cmd() + .arg("test") + .arg("--doc") + .arg(util::root_path().join("cli/tsc/dts/lib.deno.ns.d.ts")) + .output() + .unwrap(); + println!("stdout: {}", String::from_utf8(output.stdout).unwrap()); + println!("stderr: {}", String::from_utf8(output.stderr).unwrap()); + assert!(output.status.success()); + } + + #[test] + fn typecheck_declarations_unstable() { + let output = util::deno_cmd() + .arg("test") + .arg("--doc") + .arg("--unstable") + .arg(util::root_path().join("cli/tsc/dts/lib.deno.unstable.d.ts")) + .output() + .unwrap(); + println!("stdout: {}", String::from_utf8(output.stdout).unwrap()); + println!("stderr: {}", String::from_utf8(output.stderr).unwrap()); + assert!(output.status.success()); + } + + #[test] + fn typecheck_core() { + let deno_dir = TempDir::new(); + let test_file = deno_dir.path().join("test_deno_core_types.ts"); + std::fs::write( + &test_file, + format!( + "import \"{}\";", + deno_core::resolve_path( + util::root_path() + .join("core/lib.deno_core.d.ts") + .to_str() + .unwrap() + ) + .unwrap() + ), + ) + .unwrap(); + let output = util::deno_cmd_with_deno_dir(&deno_dir) + .arg("run") + .arg(test_file.to_str().unwrap()) + .output() + .unwrap(); + println!("stdout: {}", String::from_utf8(output.stdout).unwrap()); + println!("stderr: {}", String::from_utf8(output.stderr).unwrap()); + assert!(output.status.success()); + } + + #[test] + fn ts_no_recheck_on_redirect() { + let deno_dir = util::new_deno_dir(); + let e = util::deno_exe_path(); + + let redirect_ts = util::testdata_path().join("run/017_import_redirect.ts"); + assert!(redirect_ts.is_file()); + let mut cmd = Command::new(e.clone()); + cmd.env("DENO_DIR", deno_dir.path()); + let mut initial = cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--check") + .arg(redirect_ts.clone()) + .spawn() + .expect("failed to span script"); + let status_initial = + initial.wait().expect("failed to wait for child process"); + assert!(status_initial.success()); + + let mut cmd = Command::new(e); + cmd.env("DENO_DIR", deno_dir.path()); + let output = cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--check") + .arg(redirect_ts) + .output() + .expect("failed to spawn script"); + + assert!(std::str::from_utf8(&output.stderr).unwrap().is_empty()); + } +} diff --git a/cli/tests/compile_tests.rs b/cli/tests/compile_tests.rs new file mode 100644 index 0000000000..869a8780ed --- /dev/null +++ b/cli/tests/compile_tests.rs @@ -0,0 +1,536 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +use std::fs::File; +use std::process::Command; +use test_util as util; +use test_util::TempDir; + +mod compile { + use super::*; + #[test] + fn compile() { + let dir = TempDir::new(); + let exe = if cfg!(windows) { + dir.path().join("welcome.exe") + } else { + dir.path().join("welcome") + }; + // try this twice to ensure it works with the cache + for _ in 0..2 { + let output = util::deno_cmd_with_deno_dir(&dir) + .current_dir(util::root_path()) + .arg("compile") + .arg("--unstable") + .arg("--output") + .arg(&exe) + .arg("./test_util/std/examples/welcome.ts") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let output = Command::new(&exe) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, "Welcome to Deno!\n".as_bytes()); + } + } + + #[test] + fn standalone_args() { + let dir = TempDir::new(); + let exe = if cfg!(windows) { + dir.path().join("args.exe") + } else { + dir.path().join("args") + }; + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("compile") + .arg("--unstable") + .arg("--output") + .arg(&exe) + .arg("./compile/args.ts") + .arg("a") + .arg("b") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let output = Command::new(exe) + .arg("foo") + .arg("--bar") + .arg("--unstable") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"a\nb\nfoo\n--bar\n--unstable\n"); + } + + #[test] + fn standalone_error() { + let dir = TempDir::new(); + let exe = if cfg!(windows) { + dir.path().join("error.exe") + } else { + dir.path().join("error") + }; + let testdata_path = util::testdata_path(); + let output = util::deno_cmd() + .current_dir(&testdata_path) + .arg("compile") + .arg("--unstable") + .arg("--output") + .arg(&exe) + .arg("./compile/standalone_error.ts") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let output = Command::new(exe) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + assert_eq!(output.stdout, b""); + let stderr = String::from_utf8(output.stderr).unwrap(); + let stderr = util::strip_ansi_codes(&stderr).to_string(); + // On Windows, we cannot assert the file path (because '\'). + // Instead we just check for relevant output. + assert!(stderr.contains("error: Uncaught Error: boom!")); + assert!(stderr.contains("throw new Error(\"boom!\");")); + assert!(stderr.contains("\n at boom (file://")); + assert!(stderr.contains("standalone_error.ts:2:11")); + assert!(stderr.contains("at foo (file://")); + assert!(stderr.contains("standalone_error.ts:5:5")); + assert!(stderr.contains("standalone_error.ts:7:1")); + } + + #[test] + fn standalone_error_module_with_imports() { + let dir = TempDir::new(); + let exe = if cfg!(windows) { + dir.path().join("error.exe") + } else { + dir.path().join("error") + }; + let testdata_path = util::testdata_path(); + let output = util::deno_cmd() + .current_dir(&testdata_path) + .arg("compile") + .arg("--unstable") + .arg("--output") + .arg(&exe) + .arg("./compile/standalone_error_module_with_imports_1.ts") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let output = Command::new(exe) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + println!("{:#?}", &output); + assert_eq!(output.stdout, b"hello\n"); + let stderr = String::from_utf8(output.stderr).unwrap(); + let stderr = util::strip_ansi_codes(&stderr).to_string(); + // On Windows, we cannot assert the file path (because '\'). + // Instead we just check for relevant output. + assert!(stderr.contains("error: Uncaught Error: boom!")); + assert!(stderr.contains("throw new Error(\"boom!\");")); + assert!(stderr.contains("\n at file://")); + assert!(stderr.contains("standalone_error_module_with_imports_2.ts:2:7")); + } + + #[test] + fn standalone_load_datauri() { + let dir = TempDir::new(); + let exe = if cfg!(windows) { + dir.path().join("load_datauri.exe") + } else { + dir.path().join("load_datauri") + }; + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("compile") + .arg("--unstable") + .arg("--output") + .arg(&exe) + .arg("./compile/standalone_import_datauri.ts") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let output = Command::new(exe) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Hello Deno!\n"); + } + + // https://github.com/denoland/deno/issues/13704 + #[test] + fn standalone_follow_redirects() { + let dir = TempDir::new(); + let exe = if cfg!(windows) { + dir.path().join("follow_redirects.exe") + } else { + dir.path().join("follow_redirects") + }; + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("compile") + .arg("--unstable") + .arg("--output") + .arg(&exe) + .arg("./compile/standalone_follow_redirects.ts") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let output = Command::new(exe) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Hello\n"); + } + + #[test] + fn compile_with_file_exists_error() { + let dir = TempDir::new(); + let output_path = if cfg!(windows) { + dir.path().join(r"args\") + } else { + dir.path().join("args/") + }; + let file_path = dir.path().join("args"); + File::create(&file_path).unwrap(); + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("compile") + .arg("--unstable") + .arg("--output") + .arg(&output_path) + .arg("./compile/args.ts") + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + let expected_stderr = format!( + concat!( + "Could not compile to file '{}' because its parent directory ", + "is an existing file. You can use the `--output ` flag to ", + "provide an alternative name.\n", + ), + file_path.display(), + ); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stderr.contains(&expected_stderr)); + } + + #[test] + fn compile_with_directory_exists_error() { + let dir = TempDir::new(); + let exe = if cfg!(windows) { + dir.path().join("args.exe") + } else { + dir.path().join("args") + }; + std::fs::create_dir(&exe).unwrap(); + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("compile") + .arg("--unstable") + .arg("--output") + .arg(&exe) + .arg("./compile/args.ts") + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + let expected_stderr = format!( + concat!( + "Could not compile to file '{}' because a directory exists with ", + "the same name. You can use the `--output ` flag to ", + "provide an alternative name." + ), + exe.display() + ); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stderr.contains(&expected_stderr)); + } + + #[test] + fn compile_with_conflict_file_exists_error() { + let dir = TempDir::new(); + let exe = if cfg!(windows) { + dir.path().join("args.exe") + } else { + dir.path().join("args") + }; + std::fs::write(&exe, b"SHOULD NOT BE OVERWRITTEN").unwrap(); + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("compile") + .arg("--unstable") + .arg("--output") + .arg(&exe) + .arg("./compile/args.ts") + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + let expected_stderr = format!( + concat!( + "Could not compile to file '{}' because the file already exists ", + "and cannot be overwritten. Please delete the existing file or ", + "use the `--output 1); + } + + itest!(eval_basic { + args: "eval console.log(\"hello\")", + output_str: Some("hello\n"), + }); + + // Ugly parentheses due to whitespace delimiting problem. + itest!(eval_ts { + args: "eval --quiet --ext=ts console.log((123)as(number))", // 'as' is a TS keyword only + output_str: Some("123\n"), + }); + + itest!(dyn_import_eval { + args: "eval import('./subdir/mod4.js').then(console.log)", + output: "eval/dyn_import_eval.out", + }); + + // Cannot write the expression to evaluate as "console.log(typeof gc)" + // because itest! splits args on whitespace. + itest!(v8_flags_eval { + args: "eval --v8-flags=--expose-gc console.log(typeof(gc))", + output: "run/v8_flags.js.out", + }); + + itest!(check_local_by_default { + args: "eval --quiet import('http://localhost:4545/subdir/type_error.ts').then(console.log);", + output: "eval/check_local_by_default.out", + http_server: true, + }); + + itest!(check_local_by_default2 { + args: "eval --quiet import('./eval/check_local_by_default2.ts').then(console.log);", + output: "eval/check_local_by_default2.out", + http_server: true, + }); +} diff --git a/cli/tests/flags_tests.rs b/cli/tests/flags_tests.rs new file mode 100644 index 0000000000..a3ea8f7dd8 --- /dev/null +++ b/cli/tests/flags_tests.rs @@ -0,0 +1,50 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +use test_util as util; + +mod flags { + use super::*; + + #[test] + fn help_flag() { + let status = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("--help") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + + #[test] + fn version_short_flag() { + let status = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("-V") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + + #[test] + fn version_long_flag() { + let status = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("--version") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + + itest!(types { + args: "types", + output: "types/types.out", + }); +} diff --git a/cli/tests/fmt_tests.rs b/cli/tests/fmt_tests.rs new file mode 100644 index 0000000000..6ace4ce5ba --- /dev/null +++ b/cli/tests/fmt_tests.rs @@ -0,0 +1,257 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +use test_util as util; +use test_util::TempDir; + +mod fmt { + use super::*; + + #[test] + fn fmt_test() { + let t = TempDir::new(); + let testdata_fmt_dir = util::testdata_path().join("fmt"); + let fixed_js = testdata_fmt_dir.join("badly_formatted_fixed.js"); + let badly_formatted_original_js = + testdata_fmt_dir.join("badly_formatted.mjs"); + let badly_formatted_js = t.path().join("badly_formatted.js"); + let badly_formatted_js_str = badly_formatted_js.to_str().unwrap(); + std::fs::copy(&badly_formatted_original_js, &badly_formatted_js).unwrap(); + + let fixed_md = testdata_fmt_dir.join("badly_formatted_fixed.md"); + let badly_formatted_original_md = + testdata_fmt_dir.join("badly_formatted.md"); + let badly_formatted_md = t.path().join("badly_formatted.md"); + let badly_formatted_md_str = badly_formatted_md.to_str().unwrap(); + std::fs::copy(&badly_formatted_original_md, &badly_formatted_md).unwrap(); + + let fixed_json = testdata_fmt_dir.join("badly_formatted_fixed.json"); + let badly_formatted_original_json = + testdata_fmt_dir.join("badly_formatted.json"); + let badly_formatted_json = t.path().join("badly_formatted.json"); + let badly_formatted_json_str = badly_formatted_json.to_str().unwrap(); + std::fs::copy(&badly_formatted_original_json, &badly_formatted_json) + .unwrap(); + // First, check formatting by ignoring the badly formatted file. + let status = util::deno_cmd() + .current_dir(&testdata_fmt_dir) + .arg("fmt") + .arg(format!( + "--ignore={},{},{}", + badly_formatted_js_str, + badly_formatted_md_str, + badly_formatted_json_str + )) + .arg("--check") + .arg(badly_formatted_js_str) + .arg(badly_formatted_md_str) + .arg(badly_formatted_json_str) + .spawn() + .unwrap() + .wait() + .unwrap(); + // No target files found + assert!(!status.success()); + + // Check without ignore. + let status = util::deno_cmd() + .current_dir(&testdata_fmt_dir) + .arg("fmt") + .arg("--check") + .arg(badly_formatted_js_str) + .arg(badly_formatted_md_str) + .arg(badly_formatted_json_str) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(!status.success()); + + // Format the source file. + let status = util::deno_cmd() + .current_dir(&testdata_fmt_dir) + .arg("fmt") + .arg(badly_formatted_js_str) + .arg(badly_formatted_md_str) + .arg(badly_formatted_json_str) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + let expected_js = std::fs::read_to_string(fixed_js).unwrap(); + let expected_md = std::fs::read_to_string(fixed_md).unwrap(); + let expected_json = std::fs::read_to_string(fixed_json).unwrap(); + let actual_js = std::fs::read_to_string(badly_formatted_js).unwrap(); + let actual_md = std::fs::read_to_string(badly_formatted_md).unwrap(); + let actual_json = std::fs::read_to_string(badly_formatted_json).unwrap(); + assert_eq!(expected_js, actual_js); + assert_eq!(expected_md, actual_md); + assert_eq!(expected_json, actual_json); + } + + #[test] + fn fmt_stdin_error() { + use std::io::Write; + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("fmt") + .arg("-") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let stdin = deno.stdin.as_mut().unwrap(); + let invalid_js = b"import { example }"; + stdin.write_all(invalid_js).unwrap(); + let output = deno.wait_with_output().unwrap(); + // Error message might change. Just check stdout empty, stderr not. + assert!(output.stdout.is_empty()); + assert!(!output.stderr.is_empty()); + assert!(!output.status.success()); + } + + #[test] + fn fmt_ignore_unexplicit_files() { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .env("NO_COLOR", "1") + .arg("fmt") + .arg("--check") + .arg("--ignore=./") + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + assert_eq!( + String::from_utf8_lossy(&output.stderr), + "error: No target files found.\n" + ); + } + + #[test] + fn fmt_auto_ignore_git_and_node_modules() { + use std::fs::{create_dir_all, File}; + use std::io::Write; + use std::path::PathBuf; + fn create_bad_json(t: PathBuf) { + let bad_json_path = t.join("bad.json"); + let mut bad_json_file = File::create(bad_json_path).unwrap(); + writeln!(bad_json_file, "bad json").unwrap(); + } + let temp_dir = TempDir::new(); + let t = temp_dir.path().join("target"); + let nest_git = t.join("nest").join(".git"); + let git_dir = t.join(".git"); + let nest_node_modules = t.join("nest").join("node_modules"); + let node_modules_dir = t.join("node_modules"); + create_dir_all(&nest_git).unwrap(); + create_dir_all(&git_dir).unwrap(); + create_dir_all(&nest_node_modules).unwrap(); + create_dir_all(&node_modules_dir).unwrap(); + create_bad_json(nest_git); + create_bad_json(git_dir); + create_bad_json(nest_node_modules); + create_bad_json(node_modules_dir); + let output = util::deno_cmd() + .current_dir(t) + .env("NO_COLOR", "1") + .arg("fmt") + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + assert_eq!( + String::from_utf8_lossy(&output.stderr), + "error: No target files found.\n" + ); + } + + itest!(fmt_quiet_check_fmt_dir { + args: "fmt --check --quiet fmt/regular/", + output_str: Some(""), + exit_code: 0, + }); + + itest!(fmt_check_formatted_files { + args: "fmt --check fmt/regular/formatted1.js fmt/regular/formatted2.ts fmt/regular/formatted3.markdown fmt/regular/formatted4.jsonc", + output: "fmt/expected_fmt_check_formatted_files.out", + exit_code: 0, + }); + + itest!(fmt_check_ignore { + args: "fmt --check --ignore=fmt/regular/formatted1.js fmt/regular/", + output: "fmt/expected_fmt_check_ignore.out", + exit_code: 0, + }); + + itest!(fmt_check_parse_error { + args: "fmt --check fmt/parse_error/parse_error.ts", + output: "fmt/fmt_check_parse_error.out", + exit_code: 1, + }); + + itest!(fmt_stdin { + args: "fmt -", + input: Some("const a = 1\n"), + output_str: Some("const a = 1;\n"), + }); + + itest!(fmt_stdin_markdown { + args: "fmt --ext=md -", + input: Some("# Hello Markdown\n```ts\nconsole.log( \"text\")\n```\n\n```cts\nconsole.log( 5 )\n```"), + output_str: Some("# Hello Markdown\n\n```ts\nconsole.log(\"text\");\n```\n\n```cts\nconsole.log(5);\n```\n"), +}); + + itest!(fmt_stdin_json { + args: "fmt --ext=json -", + input: Some("{ \"key\": \"value\"}"), + output_str: Some("{ \"key\": \"value\" }\n"), + }); + + itest!(fmt_stdin_check_formatted { + args: "fmt --check -", + input: Some("const a = 1;\n"), + output_str: Some(""), + }); + + itest!(fmt_stdin_check_not_formatted { + args: "fmt --check -", + input: Some("const a = 1\n"), + output_str: Some("Not formatted stdin\n"), + }); + + itest!(fmt_with_config { + args: "fmt --config fmt/with_config/deno.jsonc fmt/with_config/subdir", + output: "fmt/fmt_with_config.out", + }); + + itest!(fmt_with_config_default { + args: "fmt fmt/with_config/subdir", + output: "fmt/fmt_with_config.out", + }); + + // Check if CLI flags take precedence + itest!(fmt_with_config_and_flags { + args: "fmt --config fmt/with_config/deno.jsonc --ignore=fmt/with_config/subdir/a.ts,fmt/with_config/subdir/b.ts", + output: "fmt/fmt_with_config_and_flags.out", + }); + + itest!(fmt_with_malformed_config { + args: "fmt --config fmt/deno.malformed.jsonc", + output: "fmt/fmt_with_malformed_config.out", + exit_code: 1, + }); + + itest!(fmt_with_malformed_config2 { + args: "fmt --config fmt/deno.malformed2.jsonc", + output: "fmt/fmt_with_malformed_config2.out", + exit_code: 1, + }); +} diff --git a/cli/tests/info_tests.rs b/cli/tests/info_tests.rs new file mode 100644 index 0000000000..5818fe3be4 --- /dev/null +++ b/cli/tests/info_tests.rs @@ -0,0 +1,136 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +use test_util as util; +use test_util::TempDir; + +mod init { + use super::*; + + #[test] + fn info_with_compiled_source() { + let _g = util::http_server(); + let module_path = "http://127.0.0.1:4545/run/048_media_types_jsx.ts"; + let t = TempDir::new(); + + let mut deno = util::deno_cmd() + .env("DENO_DIR", t.path()) + .current_dir(util::testdata_path()) + .arg("cache") + .arg(module_path) + .spawn() + .unwrap(); + let status = deno.wait().unwrap(); + assert!(status.success()); + + let output = util::deno_cmd() + .env("DENO_DIR", t.path()) + .env("NO_COLOR", "1") + .current_dir(util::testdata_path()) + .arg("info") + .arg(module_path) + .output() + .unwrap(); + + let str_output = std::str::from_utf8(&output.stdout).unwrap().trim(); + eprintln!("{}", str_output); + // check the output of the test.ts program. + assert!(str_output.contains("emit: ")); + assert_eq!(output.stderr, b""); + } + + itest!(multiple_imports { + args: "info http://127.0.0.1:4545/run/019_media_types.ts", + output: "info/multiple_imports.out", + http_server: true, + }); + + itest!(info_ts_error { + args: "info info/031_info_ts_error.ts", + output: "info/031_info_ts_error.out", + }); + + itest!(info_flag { + args: "info", + output: "info/041_info_flag.out", + }); + + itest!(info_flag_location { + args: "info --location https://deno.land", + output: "info/041_info_flag_location.out", + }); + + itest!(info_json { + args: "info --json --unstable", + output: "info/info_json.out", + }); + + itest!(info_json_location { + args: "info --json --unstable --location https://deno.land", + output: "info/info_json_location.out", + }); + + itest!(info_flag_script_jsx { + args: "info http://127.0.0.1:4545/run/048_media_types_jsx.ts", + output: "info/049_info_flag_script_jsx.out", + http_server: true, + }); + + itest!(json_file { + args: "info --quiet --json --unstable info/json_output/main.ts", + output: "info/json_output/main.out", + exit_code: 0, + }); + + itest!(import_map_info { + args: + "info --quiet --import-map=import_maps/import_map.json import_maps/test.ts", + output: "info/065_import_map_info.out", + }); + + itest!(info_json_deps_order { + args: "info --unstable --json info/076_info_json_deps_order.ts", + output: "info/076_info_json_deps_order.out", + }); + + itest!(info_missing_module { + args: "info info/error_009_missing_js_module.js", + output: "info/info_missing_module.out", + }); + + itest!(info_recursive_modules { + args: "info --quiet info/info_recursive_imports_test.ts", + output: "info/info_recursive_imports_test.out", + exit_code: 0, + }); + + itest!(info_type_import { + args: "info info/info_type_import.ts", + output: "info/info_type_import.out", + }); + + itest!(_054_info_local_imports { + args: "info --quiet run/005_more_imports.ts", + output: "info/054_info_local_imports.out", + exit_code: 0, + }); + + // Tests for AssertionError where "data" is unexpectedly null when + // a file contains only triple slash references (#11196) + itest!(data_null_error { + args: "info info/data_null_error/mod.ts", + output: "info/data_null_error/data_null_error.out", + }); + + itest!(types_header_direct { + args: "info --reload run/type_directives_01.ts", + output: "info/types_header.out", + http_server: true, + }); + + itest!(with_config_override { + args: "info info/with_config/test.ts --config info/with_config/deno-override.json --import-map info/with_config/import_map.json", + output: "info/with_config/with_config.out", + }); +} diff --git a/cli/tests/init_tests.rs b/cli/tests/init_tests.rs new file mode 100644 index 0000000000..40c3c1b9ad --- /dev/null +++ b/cli/tests/init_tests.rs @@ -0,0 +1,163 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +use std::process::Stdio; +use test_util as util; +use test_util::TempDir; +use util::assert_contains; + +mod init { + use super::*; + + #[test] + fn init_subcommand_without_dir() { + let temp_dir = TempDir::new(); + let cwd = temp_dir.path(); + let deno_dir = util::new_deno_dir(); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(cwd) + .arg("init") + .stderr(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_contains!(stderr, "Project initialized"); + assert!(!stderr.contains("cd")); + assert_contains!(stderr, "deno run main.ts"); + assert_contains!(stderr, "deno test"); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(cwd) + .env("NO_COLOR", "1") + .arg("run") + .arg("main.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Add 2 + 3 = 5\n"); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(cwd) + .env("NO_COLOR", "1") + .arg("test") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_contains!(stdout, "1 passed"); + } + + #[test] + fn init_subcommand_with_dir_arg() { + let temp_dir = TempDir::new(); + let cwd = temp_dir.path(); + let deno_dir = util::new_deno_dir(); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(cwd) + .arg("init") + .arg("my_dir") + .stderr(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_contains!(stderr, "Project initialized"); + assert_contains!(stderr, "cd my_dir"); + assert_contains!(stderr, "deno run main.ts"); + assert_contains!(stderr, "deno test"); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(cwd) + .env("NO_COLOR", "1") + .arg("run") + .arg("my_dir/main.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Add 2 + 3 = 5\n"); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(cwd) + .env("NO_COLOR", "1") + .arg("test") + .arg("my_dir/main_test.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_contains!(stdout, "1 passed"); + } + + #[test] + fn init_subcommand_with_quiet_arg() { + let temp_dir = TempDir::new(); + let cwd = temp_dir.path(); + let deno_dir = util::new_deno_dir(); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(cwd) + .arg("init") + .arg("--quiet") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(stdout, ""); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(cwd) + .env("NO_COLOR", "1") + .arg("run") + .arg("main.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Add 2 + 3 = 5\n"); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(cwd) + .env("NO_COLOR", "1") + .arg("test") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_contains!(stdout, "1 passed"); + } +} diff --git a/cli/tests/inspector_tests.rs b/cli/tests/inspector_tests.rs new file mode 100644 index 0000000000..8803ba63a0 --- /dev/null +++ b/cli/tests/inspector_tests.rs @@ -0,0 +1,1323 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +use deno_core::error::AnyError; +use deno_core::futures::prelude::*; +use deno_core::futures::stream::SplitSink; +use deno_core::futures::stream::SplitStream; +use deno_core::serde_json; +use deno_core::serde_json::json; +use deno_core::url; +use deno_runtime::deno_fetch::reqwest; +use deno_runtime::deno_websocket::tokio_tungstenite; +use deno_runtime::deno_websocket::tokio_tungstenite::tungstenite; +use std::io::BufRead; +use std::process::Child; +use test_util as util; +use tokio::net::TcpStream; +use util::http_server; + +mod inspector { + use super::*; + + struct InspectorTester { + socket_tx: SplitSink< + tokio_tungstenite::WebSocketStream< + tokio_tungstenite::MaybeTlsStream, + >, + tungstenite::Message, + >, + socket_rx: SplitStream< + tokio_tungstenite::WebSocketStream< + tokio_tungstenite::MaybeTlsStream, + >, + >, + notification_filter: Box bool + 'static>, + child: Child, + stderr_lines: Box>, + stdout_lines: Box>, + } + + fn ignore_script_parsed(msg: &str) -> bool { + !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#) + } + + impl InspectorTester { + async fn create(mut child: Child, notification_filter: F) -> Self + where + F: FnMut(&str) -> bool + 'static, + { + let stdout = child.stdout.take().unwrap(); + let stdout_lines = + std::io::BufReader::new(stdout).lines().map(|r| r.unwrap()); + + let stderr = child.stderr.take().unwrap(); + let mut stderr_lines = + std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); + + let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); + + let (socket, response) = + tokio_tungstenite::connect_async(ws_url).await.unwrap(); + assert_eq!(response.status(), 101); // Switching protocols. + + let (socket_tx, socket_rx) = socket.split(); + + Self { + socket_tx, + socket_rx, + notification_filter: Box::new(notification_filter), + child, + stderr_lines: Box::new(stderr_lines), + stdout_lines: Box::new(stdout_lines), + } + } + + async fn send_many(&mut self, messages: &[serde_json::Value]) { + // TODO(bartlomieju): add graceful error handling + for msg in messages { + let result = self + .socket_tx + .send(msg.to_string().into()) + .await + .map_err(|e| e.into()); + self.handle_error(result); + } + } + + async fn send(&mut self, message: serde_json::Value) { + self.send_many(&[message]).await; + } + + fn handle_error(&mut self, result: Result) -> T { + match result { + Ok(result) => result, + Err(err) => { + let mut stdout = vec![]; + for line in self.stdout_lines.by_ref() { + stdout.push(line); + } + let mut stderr = vec![]; + for line in self.stderr_lines.by_ref() { + stderr.push(line); + } + let stdout = stdout.join("\n"); + let stderr = stderr.join("\n"); + self.child.kill().unwrap(); + + panic!( + "Inspector test failed with error: {:?}.\nstdout:\n{}\nstderr:\n{}", + err, stdout, stderr + ); + } + } + } + + async fn recv(&mut self) -> String { + loop { + let result = self.socket_rx.next().await.unwrap().map_err(|e| e.into()); + let message = self.handle_error(result).to_string(); + if (self.notification_filter)(&message) { + return message; + } + } + } + + async fn recv_as_json(&mut self) -> serde_json::Value { + let msg = self.recv().await; + serde_json::from_str(&msg).unwrap() + } + + async fn assert_received_messages( + &mut self, + responses: &[&str], + notifications: &[&str], + ) { + let expected_messages = responses.len() + notifications.len(); + let mut responses_idx = 0; + let mut notifications_idx = 0; + + for _ in 0..expected_messages { + let msg = self.recv().await; + + if msg.starts_with(r#"{"id":"#) { + assert!( + msg.starts_with(responses[responses_idx]), + "Doesn't start with {}, instead received {}", + responses[responses_idx], + msg + ); + responses_idx += 1; + } else { + assert!( + msg.starts_with(notifications[notifications_idx]), + "Doesn't start with {}, instead received {}", + notifications[notifications_idx], + msg + ); + notifications_idx += 1; + } + } + } + + fn stderr_line(&mut self) -> String { + self.stderr_lines.next().unwrap() + } + + fn stdout_line(&mut self) -> String { + self.stdout_lines.next().unwrap() + } + + fn assert_stderr_for_inspect(&mut self) { + assert_stderr( + &mut self.stderr_lines, + &["Visit chrome://inspect to connect to the debugger."], + ); + } + + fn assert_stderr_for_inspect_brk(&mut self) { + assert_stderr( + &mut self.stderr_lines, + &[ + "Visit chrome://inspect to connect to the debugger.", + "Deno is waiting for debugger to connect.", + ], + ); + } + } + + macro_rules! assert_starts_with { + ($string:expr, $($test:expr),+) => { + let string = $string; // This might be a function call or something + if !($(string.starts_with($test))||+) { + panic!("{:?} does not start with {:?}", string, [$($test),+]); + } + } + } + + fn assert_stderr( + stderr_lines: &mut impl std::iter::Iterator, + expected_lines: &[&str], + ) { + let mut expected_index = 0; + + loop { + let line = skip_check_line(stderr_lines); + + assert_eq!(line, expected_lines[expected_index]); + expected_index += 1; + + if expected_index >= expected_lines.len() { + break; + } + } + } + + fn inspect_flag_with_unique_port(flag_prefix: &str) -> String { + use std::sync::atomic::{AtomicU16, Ordering}; + static PORT: AtomicU16 = AtomicU16::new(9229); + let port = PORT.fetch_add(1, Ordering::Relaxed); + format!("{}=127.0.0.1:{}", flag_prefix, port) + } + + fn extract_ws_url_from_stderr( + stderr_lines: &mut impl std::iter::Iterator, + ) -> url::Url { + let stderr_first_line = skip_check_line(stderr_lines); + assert_starts_with!(&stderr_first_line, "Debugger listening on "); + let v: Vec<_> = stderr_first_line.match_indices("ws:").collect(); + assert_eq!(v.len(), 1); + let ws_url_index = v[0].0; + let ws_url = &stderr_first_line[ws_url_index..]; + url::Url::parse(ws_url).unwrap() + } + + fn skip_check_line( + stderr_lines: &mut impl std::iter::Iterator, + ) -> String { + loop { + let mut line = stderr_lines.next().unwrap(); + line = util::strip_ansi_codes(&line).to_string(); + + if line.starts_with("Check") { + continue; + } + + return line; + } + } + + #[tokio::test] + async fn inspector_connect() { + let script = util::testdata_path().join("inspector/inspector1.js"); + let mut child = util::deno_cmd() + .arg("run") + .arg(inspect_flag_with_unique_port("--inspect")) + .arg(script) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let stderr = child.stderr.as_mut().unwrap(); + let mut stderr_lines = + std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); + let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); + + // We use tokio_tungstenite as a websocket client because warp (which is + // a dependency of Deno) uses it. + let (_socket, response) = + tokio_tungstenite::connect_async(ws_url).await.unwrap(); + assert_eq!("101 Switching Protocols", response.status().to_string()); + child.kill().unwrap(); + child.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_break_on_first_line() { + let script = util::testdata_path().join("inspector/inspector2.js"); + let child = util::deno_cmd() + .arg("run") + .arg(inspect_flag_with_unique_port("--inspect-brk")) + .arg(script) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let mut tester = InspectorTester::create(child, ignore_script_parsed).await; + + tester.assert_stderr_for_inspect_brk(); + + tester + .send_many(&[ + json!({"id":1,"method":"Runtime.enable"}), + json!({"id":2,"method":"Debugger.enable"}), + ]) + .await; + tester.assert_received_messages( + &[ + r#"{"id":1,"result":{}}"#, + r#"{"id":2,"result":{"debuggerId":"#, + ], + &[ + r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, + ], + ) + .await; + + tester + .send(json!({"id":3,"method":"Runtime.runIfWaitingForDebugger"})) + .await; + tester + .assert_received_messages( + &[r#"{"id":3,"result":{}}"#], + &[r#"{"method":"Debugger.paused","#], + ) + .await; + + tester + .send(json!({ + "id":4, + "method":"Runtime.evaluate", + "params":{ + "expression":"Deno.core.print(\"hello from the inspector\\n\")", + "contextId":1, + "includeCommandLineAPI":true, + "silent":false, + "returnByValue":true + } + })) + .await; + tester + .assert_received_messages( + &[r#"{"id":4,"result":{"result":{"type":"undefined"}}}"#], + &[], + ) + .await; + + assert_eq!( + &tester.stdout_lines.next().unwrap(), + "hello from the inspector" + ); + + tester + .send(json!({"id":5,"method":"Debugger.resume"})) + .await; + tester + .assert_received_messages(&[r#"{"id":5,"result":{}}"#], &[]) + .await; + + assert_eq!( + &tester.stdout_lines.next().unwrap(), + "hello from the script" + ); + + tester.child.kill().unwrap(); + tester.child.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_pause() { + let script = util::testdata_path().join("inspector/inspector1.js"); + let child = util::deno_cmd() + .arg("run") + .arg(inspect_flag_with_unique_port("--inspect")) + .arg(script) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let mut tester = InspectorTester::create(child, ignore_script_parsed).await; + + tester + .send(json!({"id":6,"method":"Debugger.enable"})) + .await; + tester + .assert_received_messages(&[r#"{"id":6,"result":{"debuggerId":"#], &[]) + .await; + + tester + .send(json!({"id":31,"method":"Debugger.pause"})) + .await; + + tester + .assert_received_messages(&[r#"{"id":31,"result":{}}"#], &[]) + .await; + + tester.child.kill().unwrap(); + } + + #[tokio::test] + async fn inspector_port_collision() { + // Skip this test on WSL, which allows multiple processes to listen on the + // same port, rather than making `bind()` fail with `EADDRINUSE`. + if cfg!(target_os = "linux") + && std::env::var_os("WSL_DISTRO_NAME").is_some() + { + return; + } + + let script = util::testdata_path().join("inspector/inspector1.js"); + let inspect_flag = inspect_flag_with_unique_port("--inspect"); + + let mut child1 = util::deno_cmd() + .arg("run") + .arg(&inspect_flag) + .arg(script.clone()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let stderr_1 = child1.stderr.as_mut().unwrap(); + let mut stderr_1_lines = std::io::BufReader::new(stderr_1) + .lines() + .map(|r| r.unwrap()); + let _ = extract_ws_url_from_stderr(&mut stderr_1_lines); + + let mut child2 = util::deno_cmd() + .arg("run") + .arg(&inspect_flag) + .arg(script) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let stderr_2 = child2.stderr.as_mut().unwrap(); + let stderr_2_error_message = std::io::BufReader::new(stderr_2) + .lines() + .map(|r| r.unwrap()) + .inspect(|line| assert!(!line.contains("Debugger listening"))) + .find(|line| line.contains("Cannot start inspector server")); + assert!(stderr_2_error_message.is_some()); + + child1.kill().unwrap(); + child1.wait().unwrap(); + child2.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_does_not_hang() { + let script = util::testdata_path().join("inspector/inspector3.js"); + let child = util::deno_cmd() + .arg("run") + .arg(inspect_flag_with_unique_port("--inspect-brk")) + .env("NO_COLOR", "1") + .arg(script) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let mut tester = InspectorTester::create(child, ignore_script_parsed).await; + + tester.assert_stderr_for_inspect_brk(); + + tester + .send_many(&[ + json!({"id":1,"method":"Runtime.enable"}), + json!({"id":2,"method":"Debugger.enable"}), + ]) + .await; + tester.assert_received_messages( + &[ + r#"{"id":1,"result":{}}"#, + r#"{"id":2,"result":{"debuggerId":"# + ], + &[ + r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"# + ], + ) + .await; + + tester + .send(json!({"id":3,"method":"Runtime.runIfWaitingForDebugger"})) + .await; + tester + .assert_received_messages( + &[r#"{"id":3,"result":{}}"#], + &[r#"{"method":"Debugger.paused","#], + ) + .await; + + tester + .send(json!({"id":4,"method":"Debugger.resume"})) + .await; + tester + .assert_received_messages( + &[r#"{"id":4,"result":{}}"#], + &[r#"{"method":"Debugger.resumed","params":{}}"#], + ) + .await; + + for i in 0..128u32 { + let request_id = i + 10; + // Expect the number {i} on stdout. + let s = i.to_string(); + assert_eq!(tester.stdout_lines.next().unwrap(), s); + + tester + .assert_received_messages( + &[], + &[ + r#"{"method":"Runtime.consoleAPICalled","#, + r#"{"method":"Debugger.paused","#, + ], + ) + .await; + + tester + .send(json!({"id":request_id,"method":"Debugger.resume"})) + .await; + tester + .assert_received_messages( + &[&format!(r#"{{"id":{},"result":{{}}}}"#, request_id)], + &[r#"{"method":"Debugger.resumed","params":{}}"#], + ) + .await; + } + + // Check that we can gracefully close the websocket connection. + tester.socket_tx.close().await.unwrap(); + tester.socket_rx.for_each(|_| async {}).await; + + assert_eq!(&tester.stdout_lines.next().unwrap(), "done"); + assert!(tester.child.wait().unwrap().success()); + } + + #[tokio::test] + async fn inspector_without_brk_runs_code() { + let script = util::testdata_path().join("inspector/inspector4.js"); + let mut child = util::deno_cmd() + .arg("run") + .arg(inspect_flag_with_unique_port("--inspect")) + .arg(script) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let stderr = child.stderr.as_mut().unwrap(); + let mut stderr_lines = + std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); + let _ = extract_ws_url_from_stderr(&mut stderr_lines); + + // Check that inspector actually runs code without waiting for inspector + // connection. + let stdout = child.stdout.as_mut().unwrap(); + let mut stdout_lines = + std::io::BufReader::new(stdout).lines().map(|r| r.unwrap()); + let stdout_first_line = stdout_lines.next().unwrap(); + assert_eq!(stdout_first_line, "hello"); + + child.kill().unwrap(); + child.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_runtime_evaluate_does_not_crash() { + let child = util::deno_cmd() + .arg("repl") + .arg("--allow-read") + .arg(inspect_flag_with_unique_port("--inspect")) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let mut tester = InspectorTester::create(child, ignore_script_parsed).await; + + let stdin = tester.child.stdin.take().unwrap(); + + tester.assert_stderr_for_inspect(); + assert_starts_with!(&tester.stdout_line(), "Deno"); + assert_starts_with!(&tester.stdout_line(), "Run repl.help() for help"); + assert_eq!( + &tester.stdout_line(), + "exit using ctrl+d, ctrl+c, or close()" + ); + assert_eq!(&tester.stderr_line(), "Debugger session started."); + + tester + .send_many(&[ + json!({"id":1,"method":"Runtime.enable"}), + json!({"id":2,"method":"Debugger.enable"}), + ]) + .await; + tester.assert_received_messages( + &[ + r#"{"id":1,"result":{}}"#, + r#"{"id":2,"result":{"debuggerId":"#, + ], + &[ + r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, + ], + ) + .await; + + tester + .send(json!({ + "id":3, + "method":"Runtime.compileScript", + "params":{ + "expression":"Deno.cwd()", + "sourceURL":"", + "persistScript":false, + "executionContextId":1 + } + })) + .await; + tester + .assert_received_messages(&[r#"{"id":3,"result":{}}"#], &[]) + .await; + tester + .send(json!({ + "id":4, + "method":"Runtime.evaluate", + "params":{ + "expression":"Deno.cwd()", + "objectGroup":"console", + "includeCommandLineAPI":true, + "silent":false, + "contextId":1, + "returnByValue":true, + "generatePreview":true, + "userGesture":true, + "awaitPromise":false, + "replMode":true + } + })) + .await; + tester + .assert_received_messages( + &[r#"{"id":4,"result":{"result":{"type":"string","value":""#], + &[], + ) + .await; + tester + .send(json!({ + "id":5, + "method":"Runtime.evaluate", + "params":{ + "expression":"console.error('done');", + "objectGroup":"console", + "includeCommandLineAPI":true, + "silent":false, + "contextId":1, + "returnByValue":true, + "generatePreview":true, + "userGesture":true, + "awaitPromise":false, + "replMode":true + } + })) + .await; + tester + .assert_received_messages( + &[r#"{"id":5,"result":{"result":{"type":"undefined"}}}"#], + &[r#"{"method":"Runtime.consoleAPICalled"#], + ) + .await; + assert_eq!(&tester.stderr_line(), "done"); + drop(stdin); + tester.child.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_json() { + let script = util::testdata_path().join("inspector/inspector1.js"); + let mut child = util::deno_cmd() + .arg("run") + .arg(inspect_flag_with_unique_port("--inspect")) + .arg(script) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let stderr = child.stderr.as_mut().unwrap(); + let mut stderr_lines = + std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); + let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); + let mut url = ws_url.clone(); + let _ = url.set_scheme("http"); + url.set_path("/json"); + let resp = reqwest::get(url).await.unwrap(); + assert_eq!(resp.status(), reqwest::StatusCode::OK); + let endpoint_list: Vec = + serde_json::from_str(&resp.text().await.unwrap()).unwrap(); + let matching_endpoint = endpoint_list + .iter() + .find(|e| e["webSocketDebuggerUrl"] == ws_url.as_str()); + assert!(matching_endpoint.is_some()); + child.kill().unwrap(); + } + + #[tokio::test] + async fn inspector_json_list() { + let script = util::testdata_path().join("inspector/inspector1.js"); + let mut child = util::deno_cmd() + .arg("run") + .arg(inspect_flag_with_unique_port("--inspect")) + .arg(script) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let stderr = child.stderr.as_mut().unwrap(); + let mut stderr_lines = + std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); + let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); + let mut url = ws_url.clone(); + let _ = url.set_scheme("http"); + url.set_path("/json/list"); + let resp = reqwest::get(url).await.unwrap(); + assert_eq!(resp.status(), reqwest::StatusCode::OK); + let endpoint_list: Vec = + serde_json::from_str(&resp.text().await.unwrap()).unwrap(); + let matching_endpoint = endpoint_list + .iter() + .find(|e| e["webSocketDebuggerUrl"] == ws_url.as_str()); + assert!(matching_endpoint.is_some()); + child.kill().unwrap(); + } + + #[tokio::test] + async fn inspector_connect_non_ws() { + // https://github.com/denoland/deno/issues/11449 + // Verify we don't panic if non-WS connection is being established + let script = util::testdata_path().join("inspector/inspector1.js"); + let mut child = util::deno_cmd() + .arg("run") + .arg(inspect_flag_with_unique_port("--inspect")) + .arg(script) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let stderr = child.stderr.as_mut().unwrap(); + let mut stderr_lines = + std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); + let mut ws_url = extract_ws_url_from_stderr(&mut stderr_lines); + // Change scheme to URL and try send a request. We're not interested + // in the request result, just that the process doesn't panic. + ws_url.set_scheme("http").unwrap(); + let resp = reqwest::get(ws_url).await.unwrap(); + assert_eq!("400 Bad Request", resp.status().to_string()); + child.kill().unwrap(); + child.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_break_on_first_line_in_test() { + let script = util::testdata_path().join("inspector/inspector_test.js"); + let child = util::deno_cmd() + .arg("test") + .arg("--quiet") + .arg(inspect_flag_with_unique_port("--inspect-brk")) + .arg(script) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let mut tester = InspectorTester::create(child, ignore_script_parsed).await; + + tester.assert_stderr_for_inspect_brk(); + + tester + .send_many(&[ + json!({"id":1,"method":"Runtime.enable"}), + json!({"id":2,"method":"Debugger.enable"}), + ]) + .await; + tester.assert_received_messages( + &[ + r#"{"id":1,"result":{}}"#, + r#"{"id":2,"result":{"debuggerId":"#, + ], + &[ + r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, + ], + ) + .await; + + tester + .send(json!({"id":3,"method":"Runtime.runIfWaitingForDebugger"})) + .await; + tester + .assert_received_messages( + &[r#"{"id":3,"result":{}}"#], + &[r#"{"method":"Debugger.paused","#], + ) + .await; + + tester + .send(json!({ + "id":4, + "method":"Runtime.evaluate", + "params":{ + "expression":"1 + 1", + "contextId":1, + "includeCommandLineAPI":true, + "silent":false, + "returnByValue":true + } + })) + .await; + tester.assert_received_messages( + &[r#"{"id":4,"result":{"result":{"type":"number","value":2,"description":"2"}}}"#], + &[], + ) + .await; + + tester + .send(json!({"id":5,"method":"Debugger.resume"})) + .await; + tester + .assert_received_messages(&[r#"{"id":5,"result":{}}"#], &[]) + .await; + + assert_starts_with!(&tester.stdout_line(), "running 1 test from"); + assert!(&tester.stdout_line().contains("basic test ... ok")); + + tester.child.kill().unwrap(); + tester.child.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_with_ts_files() { + let script = util::testdata_path().join("inspector/test.ts"); + let child = util::deno_cmd() + .arg("run") + .arg("--check") + .arg(inspect_flag_with_unique_port("--inspect-brk")) + .arg(script) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + fn notification_filter(msg: &str) -> bool { + (msg.starts_with(r#"{"method":"Debugger.scriptParsed","#) + && msg.contains("testdata/inspector")) + || !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#) + } + + let mut tester = InspectorTester::create(child, notification_filter).await; + + tester.assert_stderr_for_inspect_brk(); + + tester + .send_many(&[ + json!({"id":1,"method":"Runtime.enable"}), + json!({"id":2,"method":"Debugger.enable"}), + ]) + .await; + tester.assert_received_messages( + &[ + r#"{"id":1,"result":{}}"#, + ], + &[ + r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, + ], + ) + .await; + + // receive messages with sources from this test + let script1 = tester.recv().await; + assert!(script1.contains("testdata/inspector/test.ts")); + let script1_id = { + let v: serde_json::Value = serde_json::from_str(&script1).unwrap(); + v["params"]["scriptId"].as_str().unwrap().to_string() + }; + let script2 = tester.recv().await; + assert!(script2.contains("testdata/inspector/foo.ts")); + let script2_id = { + let v: serde_json::Value = serde_json::from_str(&script2).unwrap(); + v["params"]["scriptId"].as_str().unwrap().to_string() + }; + let script3 = tester.recv().await; + assert!(script3.contains("testdata/inspector/bar.js")); + let script3_id = { + let v: serde_json::Value = serde_json::from_str(&script3).unwrap(); + v["params"]["scriptId"].as_str().unwrap().to_string() + }; + + tester + .assert_received_messages(&[r#"{"id":2,"result":{"debuggerId":"#], &[]) + .await; + + tester + .send(json!({"id":3,"method":"Runtime.runIfWaitingForDebugger"})) + .await; + tester + .assert_received_messages( + &[r#"{"id":3,"result":{}}"#], + &[r#"{"method":"Debugger.paused","#], + ) + .await; + + tester.send_many( + &[ + json!({"id":4,"method":"Debugger.getScriptSource","params":{"scriptId":script1_id.as_str()}}), + json!({"id":5,"method":"Debugger.getScriptSource","params":{"scriptId":script2_id.as_str()}}), + json!({"id":6,"method":"Debugger.getScriptSource","params":{"scriptId":script3_id.as_str()}}), + ]) + .await; + tester.assert_received_messages( + &[ + r#"{"id":4,"result":{"scriptSource":"import { foo } from \"./foo.ts\";\nimport { bar } from \"./bar.js\";\nconsole.log(foo());\nconsole.log(bar());\n//# sourceMappingURL=data:application/json;base64,"#, + r#"{"id":5,"result":{"scriptSource":"class Foo {\n hello() {\n return \"hello\";\n }\n}\nexport function foo() {\n const f = new Foo();\n return f.hello();\n}\n//# sourceMappingURL=data:application/json;base64,"#, + r#"{"id":6,"result":{"scriptSource":"export function bar() {\n return \"world\";\n}\n"#, + ], + &[], + ) + .await; + + tester + .send(json!({"id":7,"method":"Debugger.resume"})) + .await; + tester + .assert_received_messages(&[r#"{"id":7,"result":{}}"#], &[]) + .await; + + assert_eq!(&tester.stdout_line(), "hello"); + assert_eq!(&tester.stdout_line(), "world"); + + tester.assert_received_messages( + &[], + &[ + r#"{"method":"Debugger.resumed","params":{}}"#, + r#"{"method":"Runtime.consoleAPICalled","#, + r#"{"method":"Runtime.consoleAPICalled","#, + r#"{"method":"Runtime.executionContextDestroyed","params":{"executionContextId":1}}"#, + ], + ) + .await; + + assert_eq!( + &tester.stdout_line(), + "Program finished. Waiting for inspector to disconnect to exit the process..." + ); + + tester.child.kill().unwrap(); + tester.child.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_memory() { + let script = util::testdata_path().join("inspector/memory.js"); + let child = util::deno_cmd() + .arg("run") + .arg(inspect_flag_with_unique_port("--inspect-brk")) + .arg(script) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let mut tester = InspectorTester::create(child, ignore_script_parsed).await; + + tester.assert_stderr_for_inspect_brk(); + + tester + .send_many(&[ + json!({"id":1,"method":"Runtime.enable"}), + json!({"id":2,"method":"Debugger.enable"}), + ]) + .await; + tester.assert_received_messages( + &[ + r#"{"id":1,"result":{}}"#, + r#"{"id":2,"result":{"debuggerId":"#, + ], + &[ + r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, + ], + ) + .await; + + tester + .send_many(&[ + json!({"id":3,"method":"Runtime.runIfWaitingForDebugger"}), + json!({"id":4,"method":"HeapProfiler.enable"}), + ]) + .await; + tester + .assert_received_messages( + &[r#"{"id":3,"result":{}}"#, r#"{"id":4,"result":{}}"#], + &[r#"{"method":"Debugger.paused","#], + ) + .await; + + tester + .send(json!({"id":5,"method":"Runtime.getHeapUsage", "params": {}})) + .await; + + let json_msg = tester.recv_as_json().await; + assert_eq!(json_msg["id"].as_i64().unwrap(), 5); + let result = &json_msg["result"]; + assert!( + result["usedSize"].as_i64().unwrap() + <= result["totalSize"].as_i64().unwrap() + ); + + tester + .send(json!({ + "id":6, + "method":"HeapProfiler.takeHeapSnapshot", + "params": { + "reportProgress": true, + "treatGlobalObjectsAsRoots": true, + "captureNumberValue": false + } + })) + .await; + + let mut progress_report_completed = false; + loop { + let msg = tester.recv().await; + + // TODO(bartlomieju): can be abstracted + if !progress_report_completed + && msg.starts_with( + r#"{"method":"HeapProfiler.reportHeapSnapshotProgress","params""#, + ) + { + let json_msg: serde_json::Value = serde_json::from_str(&msg).unwrap(); + if let Some(finished) = json_msg["params"].get("finished") { + progress_report_completed = finished.as_bool().unwrap(); + } + continue; + } + + if msg.starts_with(r#"{"method":"HeapProfiler.reportHeapSnapshotProgress","params":{"done":"#,) { + continue; + } + + if msg.starts_with(r#"{"id":6,"result":{}}"#) { + assert!(progress_report_completed); + break; + } + } + + tester.child.kill().unwrap(); + tester.child.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_profile() { + let script = util::testdata_path().join("inspector/memory.js"); + let child = util::deno_cmd() + .arg("run") + .arg(inspect_flag_with_unique_port("--inspect-brk")) + .arg(script) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let mut tester = InspectorTester::create(child, ignore_script_parsed).await; + + tester.assert_stderr_for_inspect_brk(); + + tester + .send_many(&[ + json!({"id":1,"method":"Runtime.enable"}), + json!({"id":2,"method":"Debugger.enable"}), + ]) + .await; + tester.assert_received_messages( + &[ + r#"{"id":1,"result":{}}"#, + r#"{"id":2,"result":{"debuggerId":"#, + ], + &[ + r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, + ], + ) + .await; + + tester + .send_many(&[ + json!({"id":3,"method":"Runtime.runIfWaitingForDebugger"}), + json!({"id":4,"method":"Profiler.enable"}), + ]) + .await; + tester + .assert_received_messages( + &[r#"{"id":3,"result":{}}"#, r#"{"id":4,"result":{}}"#], + &[r#"{"method":"Debugger.paused","#], + ) + .await; + + tester.send_many( + &[ + json!({"id":5,"method":"Profiler.setSamplingInterval","params":{"interval": 100}}), + json!({"id":6,"method":"Profiler.start","params":{}}), + ], + ).await; + tester + .assert_received_messages( + &[r#"{"id":5,"result":{}}"#, r#"{"id":6,"result":{}}"#], + &[], + ) + .await; + + tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; + + tester + .send(json!({"id":7,"method":"Profiler.stop", "params": {}})) + .await; + let json_msg = tester.recv_as_json().await; + assert_eq!(json_msg["id"].as_i64().unwrap(), 7); + let result = &json_msg["result"]; + let profile = &result["profile"]; + assert!( + profile["startTime"].as_i64().unwrap() + < profile["endTime"].as_i64().unwrap() + ); + profile["samples"].as_array().unwrap(); + profile["nodes"].as_array().unwrap(); + + tester.child.kill().unwrap(); + tester.child.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_break_on_first_line_npm_esm() { + let _server = http_server(); + + let child = util::deno_cmd() + .arg("run") + .arg("--quiet") + .arg(inspect_flag_with_unique_port("--inspect-brk")) + .arg("npm:@denotest/bin/cli-esm") + .arg("this") + .arg("is") + .arg("a") + .arg("test") + .envs(util::env_vars_for_npm_tests()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let mut tester = InspectorTester::create(child, ignore_script_parsed).await; + + tester.assert_stderr_for_inspect_brk(); + + tester + .send_many(&[ + json!({"id":1,"method":"Runtime.enable"}), + json!({"id":2,"method":"Debugger.enable"}), + ]) + .await; + tester.assert_received_messages( + &[ + r#"{"id":1,"result":{}}"#, + r#"{"id":2,"result":{"debuggerId":"#, + ], + &[ + r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, + ], + ) + .await; + + tester + .send(json!({"id":3,"method":"Runtime.runIfWaitingForDebugger"})) + .await; + tester + .assert_received_messages( + &[r#"{"id":3,"result":{}}"#], + &[r#"{"method":"Debugger.paused","#], + ) + .await; + + tester + .send(json!({"id":4,"method":"Debugger.resume"})) + .await; + tester + .assert_received_messages(&[r#"{"id":4,"result":{}}"#], &[]) + .await; + + assert_eq!(&tester.stdout_line(), "this"); + assert_eq!(&tester.stdout_line(), "is"); + assert_eq!(&tester.stdout_line(), "a"); + assert_eq!(&tester.stdout_line(), "test"); + + tester.child.kill().unwrap(); + tester.child.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_break_on_first_line_npm_cjs() { + let _server = http_server(); + let child = util::deno_cmd() + .arg("run") + .arg("--quiet") + .arg(inspect_flag_with_unique_port("--inspect-brk")) + .arg("npm:@denotest/bin/cli-cjs") + .arg("this") + .arg("is") + .arg("a") + .arg("test") + .envs(util::env_vars_for_npm_tests()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let mut tester = InspectorTester::create(child, ignore_script_parsed).await; + + tester.assert_stderr_for_inspect_brk(); + + tester + .send_many(&[ + json!({"id":1,"method":"Runtime.enable"}), + json!({"id":2,"method":"Debugger.enable"}), + ]) + .await; + tester.assert_received_messages( + &[ + r#"{"id":1,"result":{}}"#, + r#"{"id":2,"result":{"debuggerId":"#, + ], + &[ + r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, + ], + ) + .await; + + tester + .send(json!({"id":3,"method":"Runtime.runIfWaitingForDebugger"})) + .await; + tester + .assert_received_messages( + &[r#"{"id":3,"result":{}}"#], + &[r#"{"method":"Debugger.paused","#], + ) + .await; + + tester + .send(json!({"id":4,"method":"Debugger.resume"})) + .await; + tester + .assert_received_messages(&[r#"{"id":4,"result":{}}"#], &[]) + .await; + + assert_eq!(&tester.stdout_line(), "this"); + assert_eq!(&tester.stdout_line(), "is"); + assert_eq!(&tester.stdout_line(), "a"); + assert_eq!(&tester.stdout_line(), "test"); + + tester.child.kill().unwrap(); + tester.child.wait().unwrap(); + } + + #[tokio::test] + async fn inspector_error_with_npm_import() { + let script = + util::testdata_path().join("inspector/error_with_npm_import.js"); + let _server = http_server(); + + let child = util::deno_cmd() + .arg("run") + .arg("--quiet") + .arg("-A") + .arg(inspect_flag_with_unique_port("--inspect-brk")) + .arg(script) + .envs(util::env_vars_for_npm_tests()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let mut tester = InspectorTester::create(child, ignore_script_parsed).await; + + tester.assert_stderr_for_inspect_brk(); + + tester + .send_many(&[ + json!({"id":1,"method":"Runtime.enable"}), + json!({"id":2,"method":"Debugger.enable"}), + ]) + .await; + tester.assert_received_messages( + &[ + r#"{"id":1,"result":{}}"#, + r#"{"id":2,"result":{"debuggerId":"#, + ], + &[ + r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, + ], + ) + .await; + + tester + .send(json!({"id":3,"method":"Runtime.runIfWaitingForDebugger"})) + .await; + tester + .assert_received_messages( + &[r#"{"id":3,"result":{}}"#], + &[r#"{"method":"Debugger.paused","#], + ) + .await; + + tester + .send(json!({"id":4,"method":"Debugger.resume"})) + .await; + tester + .assert_received_messages(&[r#"{"id":4,"result":{}}"#], &[]) + .await; + + // TODO(bartlomieju): this is a partial fix, we should assert that + // "Runtime.exceptionThrown" notification was sent, but a bindings for this + // notification is not yet there + assert_eq!(&tester.stderr_line(), "Debugger session started."); + assert_eq!(&tester.stderr_line(), "error: Uncaught Error: boom!"); + + assert_eq!(tester.child.wait().unwrap().code(), Some(1)); + } +} diff --git a/cli/tests/install_tests.rs b/cli/tests/install_tests.rs new file mode 100644 index 0000000000..4016b63733 --- /dev/null +++ b/cli/tests/install_tests.rs @@ -0,0 +1,220 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +use std::fs; +use std::process::Command; +use test_util as util; +use test_util::assert_contains; +use test_util::assert_ends_with; +use test_util::TempDir; + +mod install { + use super::*; + + #[test] + fn install_basic() { + let _guard = util::http_server(); + let temp_dir = TempDir::new(); + let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); + + let status = util::deno_cmd() + .current_dir(temp_dir.path()) + .arg("install") + .arg("--check") + .arg("--name") + .arg("echo_test") + .arg("http://localhost:4545/echo.ts") + .envs([ + ("HOME", temp_dir_str.as_str()), + ("USERPROFILE", temp_dir_str.as_str()), + ("DENO_INSTALL_ROOT", ""), + ]) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + + let mut file_path = temp_dir.path().join(".deno/bin/echo_test"); + assert!(file_path.exists()); + + if cfg!(windows) { + file_path = file_path.with_extension("cmd"); + } + + let content = fs::read_to_string(file_path).unwrap(); + // ensure there's a trailing newline so the shell script can be + // more versatile. + assert_eq!(content.chars().last().unwrap(), '\n'); + + if cfg!(windows) { + assert_contains!( + content, + r#""run" "--check" "http://localhost:4545/echo.ts""# + ); + } else { + assert_contains!( + content, + r#"run --check 'http://localhost:4545/echo.ts'"# + ); + } + } + + #[test] + fn install_custom_dir_env_var() { + let _guard = util::http_server(); + let temp_dir = TempDir::new(); + let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); + + let status = util::deno_cmd() + .current_dir(util::root_path()) // different cwd + .arg("install") + .arg("--check") + .arg("--name") + .arg("echo_test") + .arg("http://localhost:4545/echo.ts") + .envs([ + ("HOME", temp_dir_str.as_str()), + ("USERPROFILE", temp_dir_str.as_str()), + ("DENO_INSTALL_ROOT", temp_dir_str.as_str()), + ]) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + + let mut file_path = temp_dir.path().join("bin/echo_test"); + assert!(file_path.exists()); + + if cfg!(windows) { + file_path = file_path.with_extension("cmd"); + } + + let content = fs::read_to_string(file_path).unwrap(); + if cfg!(windows) { + assert_contains!( + content, + r#""run" "--check" "http://localhost:4545/echo.ts""# + ); + } else { + assert_contains!( + content, + r#"run --check 'http://localhost:4545/echo.ts'"# + ); + } + } + + #[test] + fn installer_test_local_module_run() { + let temp_dir = TempDir::new(); + let bin_dir = temp_dir.path().join("bin"); + std::fs::create_dir(&bin_dir).unwrap(); + let status = util::deno_cmd() + .current_dir(util::root_path()) + .arg("install") + .arg("--name") + .arg("echo_test") + .arg("--root") + .arg(temp_dir.path()) + .arg(util::testdata_path().join("echo.ts")) + .arg("hello") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + let mut file_path = bin_dir.join("echo_test"); + if cfg!(windows) { + file_path = file_path.with_extension("cmd"); + } + assert!(file_path.exists()); + // NOTE: using file_path here instead of exec_name, because tests + // shouldn't mess with user's PATH env variable + let output = Command::new(file_path) + .current_dir(temp_dir.path()) + .arg("foo") + .env("PATH", util::target_dir()) + .output() + .unwrap(); + let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); + assert_ends_with!(stdout_str, "hello, foo"); + } + + #[test] + fn installer_test_remote_module_run() { + let _g = util::http_server(); + let temp_dir = TempDir::new(); + let bin_dir = temp_dir.path().join("bin"); + std::fs::create_dir(&bin_dir).unwrap(); + let status = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("install") + .arg("--name") + .arg("echo_test") + .arg("--root") + .arg(temp_dir.path()) + .arg("http://localhost:4545/echo.ts") + .arg("hello") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + let mut file_path = bin_dir.join("echo_test"); + if cfg!(windows) { + file_path = file_path.with_extension("cmd"); + } + assert!(file_path.exists()); + let output = Command::new(file_path) + .current_dir(temp_dir.path()) + .arg("foo") + .env("PATH", util::target_dir()) + .output() + .unwrap(); + assert_ends_with!( + std::str::from_utf8(&output.stdout).unwrap().trim(), + "hello, foo", + ); + } + + #[test] + fn check_local_by_default() { + let _guard = util::http_server(); + let temp_dir = TempDir::new(); + let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); + + let status = util::deno_cmd() + .current_dir(temp_dir.path()) + .arg("install") + .arg(util::testdata_path().join("./install/check_local_by_default.ts")) + .envs([ + ("HOME", temp_dir_str.as_str()), + ("USERPROFILE", temp_dir_str.as_str()), + ("DENO_INSTALL_ROOT", ""), + ]) + .status() + .unwrap(); + assert!(status.success()); + } + + #[test] + fn check_local_by_default2() { + let _guard = util::http_server(); + let temp_dir = TempDir::new(); + let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); + + let status = util::deno_cmd() + .current_dir(temp_dir.path()) + .arg("install") + .arg(util::testdata_path().join("./install/check_local_by_default2.ts")) + .envs([ + ("HOME", temp_dir_str.as_str()), + ("NO_COLOR", "1"), + ("USERPROFILE", temp_dir_str.as_str()), + ("DENO_INSTALL_ROOT", ""), + ]) + .status() + .unwrap(); + assert!(status.success()); + } +} diff --git a/cli/tests/integration/bench_tests.rs b/cli/tests/integration/bench_tests.rs deleted file mode 100644 index d3fa5791a7..0000000000 --- a/cli/tests/integration/bench_tests.rs +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use crate::itest; -use deno_core::url::Url; -use test_util as util; - -itest!(overloads { - args: "bench bench/overloads.ts", - exit_code: 0, - output: "bench/overloads.out", -}); - -itest!(meta { - args: "bench bench/meta.ts", - exit_code: 0, - output: "bench/meta.out", -}); - -itest!(pass { - args: "bench bench/pass.ts", - exit_code: 0, - output: "bench/pass.out", -}); - -itest!(ignore { - args: "bench bench/ignore.ts", - exit_code: 0, - output: "bench/ignore.out", -}); - -itest!(ignore_permissions { - args: "bench bench/ignore_permissions.ts", - exit_code: 0, - output: "bench/ignore_permissions.out", -}); - -itest!(fail { - args: "bench bench/fail.ts", - exit_code: 1, - output: "bench/fail.out", -}); - -itest!(collect { - args: "bench --ignore=bench/collect/ignore bench/collect", - exit_code: 0, - output: "bench/collect.out", -}); - -itest!(load_unload { - args: "bench bench/load_unload.ts", - exit_code: 0, - output: "bench/load_unload.out", -}); - -itest!(interval { - args: "bench bench/interval.ts", - exit_code: 0, - output: "bench/interval.out", -}); - -itest!(quiet { - args: "bench --quiet bench/quiet.ts", - exit_code: 0, - output: "bench/quiet.out", -}); - -itest!(only { - args: "bench bench/only.ts", - exit_code: 1, - output: "bench/only.out", -}); - -itest!(multifile_summary { - args: "bench bench/group_baseline.ts bench/pass.ts bench/group_baseline.ts", - exit_code: 0, - output: "bench/multifile_summary.out", -}); - -itest!(no_check { - args: "bench --no-check bench/no_check.ts", - exit_code: 1, - output: "bench/no_check.out", -}); - -itest!(allow_all { - args: "bench --allow-all bench/allow_all.ts", - exit_code: 0, - output: "bench/allow_all.out", -}); - -itest!(allow_none { - args: "bench bench/allow_none.ts", - exit_code: 1, - output: "bench/allow_none.out", -}); - -itest!(exit_sanitizer { - args: "bench bench/exit_sanitizer.ts", - output: "bench/exit_sanitizer.out", - exit_code: 1, -}); - -itest!(clear_timeout { - args: "bench bench/clear_timeout.ts", - exit_code: 0, - output: "bench/clear_timeout.out", -}); - -itest!(finally_timeout { - args: "bench bench/finally_timeout.ts", - exit_code: 1, - output: "bench/finally_timeout.out", -}); - -itest!(group_baseline { - args: "bench bench/group_baseline.ts", - exit_code: 0, - output: "bench/group_baseline.out", -}); - -itest!(unresolved_promise { - args: "bench bench/unresolved_promise.ts", - exit_code: 1, - output: "bench/unresolved_promise.out", -}); - -itest!(unhandled_rejection { - args: "bench bench/unhandled_rejection.ts", - exit_code: 1, - output: "bench/unhandled_rejection.out", -}); - -itest!(filter { - args: "bench --filter=foo bench/filter", - exit_code: 0, - output: "bench/filter.out", -}); - -itest!(no_prompt_by_default { - args: "bench --quiet bench/no_prompt_by_default.ts", - exit_code: 1, - output: "bench/no_prompt_by_default.out", -}); - -itest!(no_prompt_with_denied_perms { - args: "bench --quiet --allow-read bench/no_prompt_with_denied_perms.ts", - exit_code: 1, - output: "bench/no_prompt_with_denied_perms.out", -}); - -itest!(check_local_by_default { - args: "bench --quiet bench/check_local_by_default.ts", - output: "bench/check_local_by_default.out", - http_server: true, -}); - -itest!(check_local_by_default2 { - args: "bench --quiet bench/check_local_by_default2.ts", - output: "bench/check_local_by_default2.out", - http_server: true, - exit_code: 1, -}); - -#[test] -fn recursive_permissions_pledge() { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bench") - .arg("bench/recursive_permissions_pledge.js") - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - assert!(String::from_utf8(output.stderr).unwrap().contains( - "pledge test permissions called before restoring previous pledge" - )); -} - -#[test] -fn file_protocol() { - let file_url = - Url::from_file_path(util::testdata_path().join("bench/file_protocol.ts")) - .unwrap() - .to_string(); - - (util::CheckOutputIntegrationTest { - args_vec: vec!["bench", &file_url], - exit_code: 0, - output: "bench/file_protocol.out", - ..Default::default() - }) - .run(); -} diff --git a/cli/tests/integration/bundle_tests.rs b/cli/tests/integration/bundle_tests.rs deleted file mode 100644 index ff5a51e981..0000000000 --- a/cli/tests/integration/bundle_tests.rs +++ /dev/null @@ -1,468 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use crate::itest; -use test_util as util; -use test_util::assert_contains; -use test_util::assert_ends_with; -use test_util::TempDir; - -#[test] -fn bundle_exports() { - // First we have to generate a bundle of some module that has exports. - let mod1 = util::testdata_path().join("subdir/mod1.ts"); - assert!(mod1.is_file()); - let t = TempDir::new(); - let bundle = t.path().join("mod1.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg(mod1) - .arg(&bundle) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - assert!(bundle.is_file()); - - // Now we try to use that bundle from another module. - let test = t.path().join("test.js"); - std::fs::write( - &test, - " - import { printHello3 } from \"./mod1.bundle.js\"; - printHello3(); ", - ) - .unwrap(); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg(&test) - .output() - .unwrap(); - // check the output of the test.ts program. - assert_ends_with!( - std::str::from_utf8(&output.stdout).unwrap().trim(), - "Hello", - ); - assert_eq!(output.stderr, b""); -} - -#[test] -fn bundle_exports_no_check() { - // First we have to generate a bundle of some module that has exports. - let mod1 = util::testdata_path().join("subdir/mod1.ts"); - assert!(mod1.is_file()); - let t = TempDir::new(); - let bundle = t.path().join("mod1.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg(mod1) - .arg(&bundle) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - assert!(bundle.is_file()); - - // Now we try to use that bundle from another module. - let test = t.path().join("test.js"); - std::fs::write( - &test, - " - import { printHello3 } from \"./mod1.bundle.js\"; - printHello3(); ", - ) - .unwrap(); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg(&test) - .output() - .unwrap(); - // check the output of the test.ts program. - assert_ends_with!( - std::str::from_utf8(&output.stdout).unwrap().trim(), - "Hello", - ); - assert_eq!(output.stderr, b""); -} - -#[test] -fn bundle_circular() { - // First we have to generate a bundle of some module that has exports. - let circular1_path = util::testdata_path().join("subdir/circular1.ts"); - assert!(circular1_path.is_file()); - let t = TempDir::new(); - let bundle_path = t.path().join("circular1.bundle.js"); - - // run this twice to ensure it works even when cached - for _ in 0..2 { - let mut deno = util::deno_cmd_with_deno_dir(&t) - .current_dir(util::testdata_path()) - .arg("bundle") - .arg(&circular1_path) - .arg(&bundle_path) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - assert!(bundle_path.is_file()); - } - - let output = util::deno_cmd_with_deno_dir(&t) - .current_dir(util::testdata_path()) - .arg("run") - .arg(&bundle_path) - .output() - .unwrap(); - // check the output of the the bundle program. - assert_ends_with!( - std::str::from_utf8(&output.stdout).unwrap().trim(), - "f2\nf1", - ); - assert_eq!(output.stderr, b""); -} - -#[test] -fn bundle_single_module() { - // First we have to generate a bundle of some module that has exports. - let single_module = util::testdata_path().join("subdir/single_module.ts"); - assert!(single_module.is_file()); - let t = TempDir::new(); - let bundle = t.path().join("single_module.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg(single_module) - .arg(&bundle) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - assert!(bundle.is_file()); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg(&bundle) - .output() - .unwrap(); - // check the output of the the bundle program. - assert_ends_with!( - std::str::from_utf8(&output.stdout).unwrap().trim(), - "Hello world!", - ); - assert_eq!(output.stderr, b""); -} - -#[test] -fn bundle_tla() { - // First we have to generate a bundle of some module that has exports. - let tla_import = util::testdata_path().join("subdir/tla.ts"); - assert!(tla_import.is_file()); - let t = TempDir::new(); - let bundle = t.path().join("tla.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg(tla_import) - .arg(&bundle) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - assert!(bundle.is_file()); - - // Now we try to use that bundle from another module. - let test = t.path().join("test.js"); - std::fs::write( - &test, - " - import { foo } from \"./tla.bundle.js\"; - console.log(foo); ", - ) - .unwrap(); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg(&test) - .output() - .unwrap(); - // check the output of the test.ts program. - assert_ends_with!( - std::str::from_utf8(&output.stdout).unwrap().trim(), - "Hello", - ); - assert_eq!(output.stderr, b""); -} - -#[test] -fn bundle_js() { - // First we have to generate a bundle of some module that has exports. - let mod6 = util::testdata_path().join("subdir/mod6.js"); - assert!(mod6.is_file()); - let t = TempDir::new(); - let bundle = t.path().join("mod6.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg(mod6) - .arg(&bundle) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - assert!(bundle.is_file()); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg(&bundle) - .output() - .unwrap(); - // check that nothing went to stderr - assert_eq!(output.stderr, b""); -} - -#[test] -fn bundle_dynamic_import() { - let _g = util::http_server(); - let dynamic_import = util::testdata_path().join("bundle/dynamic_import.ts"); - assert!(dynamic_import.is_file()); - let t = TempDir::new(); - let output_path = t.path().join("bundle_dynamic_import.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg(dynamic_import) - .arg(&output_path) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - assert!(output_path.is_file()); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-net") - .arg("--quiet") - .arg(&output_path) - .output() - .unwrap(); - // check the output of the test.ts program. - assert_ends_with!( - std::str::from_utf8(&output.stdout).unwrap().trim(), - "Hello", - ); - assert_eq!(output.stderr, b""); -} - -#[test] -fn bundle_import_map() { - let import = util::testdata_path().join("bundle/import_map/main.ts"); - let import_map_path = - util::testdata_path().join("bundle/import_map/import_map.json"); - assert!(import.is_file()); - let t = TempDir::new(); - let output_path = t.path().join("import_map.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg("--import-map") - .arg(import_map_path) - .arg(import) - .arg(&output_path) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - assert!(output_path.is_file()); - - // Now we try to use that bundle from another module. - let test = t.path().join("test.js"); - std::fs::write( - &test, - " - import { printHello3 } from \"./import_map.bundle.js\"; - printHello3(); ", - ) - .unwrap(); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--check") - .arg(&test) - .output() - .unwrap(); - // check the output of the test.ts program. - assert_ends_with!( - std::str::from_utf8(&output.stdout).unwrap().trim(), - "Hello", - ); - assert_eq!(output.stderr, b""); -} - -#[test] -fn bundle_import_map_no_check() { - let import = util::testdata_path().join("bundle/import_map/main.ts"); - let import_map_path = - util::testdata_path().join("bundle/import_map/import_map.json"); - assert!(import.is_file()); - let t = TempDir::new(); - let output_path = t.path().join("import_map.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg("--import-map") - .arg(import_map_path) - .arg(import) - .arg(&output_path) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - assert!(output_path.is_file()); - - // Now we try to use that bundle from another module. - let test = t.path().join("test.js"); - std::fs::write( - &test, - " - import { printHello3 } from \"./import_map.bundle.js\"; - printHello3(); ", - ) - .unwrap(); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg(&test) - .output() - .unwrap(); - // check the output of the test.ts program. - assert_ends_with!( - std::str::from_utf8(&output.stdout).unwrap().trim(), - "Hello", - ); - assert_eq!(output.stderr, b""); -} - -#[test] -fn bundle_json_module() { - // First we have to generate a bundle of some module that has exports. - let mod7 = util::testdata_path().join("subdir/mod7.js"); - assert!(mod7.is_file()); - let t = TempDir::new(); - let bundle = t.path().join("mod7.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg(mod7) - .arg(&bundle) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - assert!(bundle.is_file()); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg(&bundle) - .output() - .unwrap(); - // check that nothing went to stderr - assert_eq!(output.stderr, b""); - // ensure the output looks right - assert_contains!(String::from_utf8(output.stdout).unwrap(), "with space",); -} - -#[test] -fn bundle_json_module_escape_sub() { - // First we have to generate a bundle of some module that has exports. - let mod8 = util::testdata_path().join("subdir/mod8.js"); - assert!(mod8.is_file()); - let t = TempDir::new(); - let bundle = t.path().join("mod8.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg(mod8) - .arg(&bundle) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - assert!(bundle.is_file()); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg(&bundle) - .output() - .unwrap(); - // check that nothing went to stderr - assert_eq!(output.stderr, b""); - // make sure the output looks right and the escapes were effective - assert_contains!( - String::from_utf8(output.stdout).unwrap(), - "${globalThis}`and string literal`", - ); -} - -itest!(lockfile_check_error { - args: "bundle --lock=bundle/lockfile/check_error.json http://127.0.0.1:4545/subdir/mod1.ts", - output: "bundle/lockfile/check_error.out", - exit_code: 10, - http_server: true, -}); - -itest!(bundle { - args: "bundle subdir/mod1.ts", - output: "bundle/bundle.test.out", -}); - -itest!(bundle_jsx { - args: "bundle run/jsx_import_from_ts.ts", - output: "bundle/jsx.out", -}); - -itest!(error_bundle_with_bare_import { - args: "bundle bundle/bare_imports/error_with_bare_import.ts", - output: "bundle/bare_imports/error_with_bare_import.ts.out", - exit_code: 1, -}); - -itest!(ts_decorators_bundle { - args: "bundle bundle/decorators/ts_decorators.ts", - output: "bundle/decorators/ts_decorators.out", -}); - -itest!(bundle_export_specifier_with_alias { - args: "bundle bundle/file_tests-fixture16.ts", - output: "bundle/fixture16.out", -}); - -itest!(bundle_ignore_directives { - args: "bundle subdir/mod1.ts", - output: "bundle/ignore_directives.test.out", -}); - -itest!(check_local_by_default_no_errors { - args: "bundle --quiet bundle/check_local_by_default/no_errors.ts", - output: "bundle/check_local_by_default/no_errors.out", - http_server: true, -}); - -itest!(check_local_by_default_type_error { - args: "bundle --quiet bundle/check_local_by_default/type_error.ts", - output: "bundle/check_local_by_default/type_error.out", - http_server: true, - exit_code: 1, -}); diff --git a/cli/tests/integration/cache_tests.rs b/cli/tests/integration/cache_tests.rs deleted file mode 100644 index 3fca335a97..0000000000 --- a/cli/tests/integration/cache_tests.rs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use crate::itest; - -itest!(_036_import_map_fetch { - args: - "cache --quiet --reload --import-map=import_maps/import_map.json import_maps/test.ts", - output: "cache/036_import_map_fetch.out", -}); - -itest!(_037_fetch_multiple { - args: "cache --reload --check=all run/fetch/test.ts run/fetch/other.ts", - http_server: true, - output: "cache/037_fetch_multiple.out", -}); - -itest!(_095_cache_with_bare_import { - args: "cache cache/095_cache_with_bare_import.ts", - output: "cache/095_cache_with_bare_import.ts.out", - exit_code: 1, -}); - -itest!(cache_extensionless { - args: "cache --reload --check=all http://localhost:4545/subdir/no_js_ext", - output: "cache/cache_extensionless.out", - http_server: true, -}); - -itest!(cache_random_extension { - args: - "cache --reload --check=all http://localhost:4545/subdir/no_js_ext@1.0.0", - output: "cache/cache_random_extension.out", - http_server: true, -}); - -itest!(performance_stats { - args: "cache --reload --check=all --log-level debug run/002_hello.ts", - output: "cache/performance_stats.out", -}); - -itest!(redirect_cache { - http_server: true, - args: - "cache --reload --check=all http://localhost:4548/subdir/redirects/a.ts", - output: "cache/redirect_cache.out", -}); - -itest!(ignore_require { - args: "cache --reload --no-check cache/ignore_require.js", - output_str: Some(""), - exit_code: 0, -}); - -// This test only runs on linux, because it hardcodes the XDG_CACHE_HOME env var -// which is only used on linux. -#[cfg(target_os = "linux")] -#[test] -fn relative_home_dir() { - use test_util as util; - use test_util::TempDir; - - let deno_dir = TempDir::new_in(&util::testdata_path()); - let path = deno_dir.path().strip_prefix(util::testdata_path()).unwrap(); - - let mut deno_cmd = util::deno_cmd(); - let output = deno_cmd - .current_dir(util::testdata_path()) - .env("XDG_CACHE_HOME", path) - .env_remove("HOME") - .env_remove("DENO_DIR") - .arg("cache") - .arg("--reload") - .arg("--no-check") - .arg("run/002_hello.ts") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b""); -} - -itest!(check_local_by_default { - args: "cache --quiet cache/check_local_by_default.ts", - output: "cache/check_local_by_default.out", - http_server: true, -}); - -itest!(check_local_by_default2 { - args: "cache --quiet cache/check_local_by_default2.ts", - output: "cache/check_local_by_default2.out", - http_server: true, -}); - -itest!(json_import { - // should not error - args: "cache --quiet cache/json_import/main.ts", -}); diff --git a/cli/tests/integration/cert_tests.rs b/cli/tests/integration/cert_tests.rs deleted file mode 100644 index fd19c1cc18..0000000000 --- a/cli/tests/integration/cert_tests.rs +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use crate::itest; -use deno_runtime::deno_net::ops_tls::TlsStream; -use deno_runtime::deno_tls::rustls; -use deno_runtime::deno_tls::rustls_pemfile; -use std::io::BufReader; -use std::io::Cursor; -use std::io::Read; -use std::process::Command; -use std::sync::Arc; -use test_util as util; -use test_util::TempDir; -use tokio::task::LocalSet; - -itest_flaky!(cafile_url_imports { - args: "run --quiet --reload --cert tls/RootCA.pem cert/cafile_url_imports.ts", - output: "cert/cafile_url_imports.ts.out", - http_server: true, -}); - -itest_flaky!(cafile_ts_fetch { - args: - "run --quiet --reload --allow-net --cert tls/RootCA.pem cert/cafile_ts_fetch.ts", - output: "cert/cafile_ts_fetch.ts.out", - http_server: true, -}); - -itest_flaky!(cafile_eval { - args: "eval --cert tls/RootCA.pem fetch('https://localhost:5545/cert/cafile_ts_fetch.ts.out').then(r=>r.text()).then(t=>console.log(t.trimEnd()))", - output: "cert/cafile_ts_fetch.ts.out", - http_server: true, -}); - -itest_flaky!(cafile_info { - args: - "info --quiet --cert tls/RootCA.pem https://localhost:5545/cert/cafile_info.ts", - output: "cert/cafile_info.ts.out", - http_server: true, -}); - -itest_flaky!(cafile_url_imports_unsafe_ssl { - args: "run --quiet --reload --unsafely-ignore-certificate-errors=localhost cert/cafile_url_imports.ts", - output: "cert/cafile_url_imports_unsafe_ssl.ts.out", - http_server: true, -}); - -itest_flaky!(cafile_ts_fetch_unsafe_ssl { - args: - "run --quiet --reload --allow-net --unsafely-ignore-certificate-errors cert/cafile_ts_fetch.ts", - output: "cert/cafile_ts_fetch_unsafe_ssl.ts.out", - http_server: true, -}); - -itest!(deno_land_unsafe_ssl { - args: - "run --quiet --reload --allow-net --unsafely-ignore-certificate-errors=deno.land cert/deno_land_unsafe_ssl.ts", - output: "cert/deno_land_unsafe_ssl.ts.out", -}); - -itest!(ip_address_unsafe_ssl { - args: - "run --quiet --reload --allow-net --unsafely-ignore-certificate-errors=1.1.1.1 cert/ip_address_unsafe_ssl.ts", - output: "cert/ip_address_unsafe_ssl.ts.out", -}); - -itest!(localhost_unsafe_ssl { - args: - "run --quiet --reload --allow-net --unsafely-ignore-certificate-errors=deno.land cert/cafile_url_imports.ts", - output: "cert/localhost_unsafe_ssl.ts.out", - http_server: true, - exit_code: 1, -}); - -#[flaky_test::flaky_test] -fn cafile_env_fetch() { - use deno_core::url::Url; - let _g = util::http_server(); - let deno_dir = TempDir::new(); - let module_url = - Url::parse("https://localhost:5545/cert/cafile_url_imports.ts").unwrap(); - let cafile = util::testdata_path().join("tls/RootCA.pem"); - let output = Command::new(util::deno_exe_path()) - .env("DENO_DIR", deno_dir.path()) - .env("DENO_CERT", cafile) - .current_dir(util::testdata_path()) - .arg("cache") - .arg(module_url.to_string()) - .output() - .expect("Failed to spawn script"); - assert!(output.status.success()); -} - -#[flaky_test::flaky_test] -fn cafile_fetch() { - use deno_core::url::Url; - let _g = util::http_server(); - let deno_dir = TempDir::new(); - let module_url = - Url::parse("http://localhost:4545/cert/cafile_url_imports.ts").unwrap(); - let cafile = util::testdata_path().join("tls/RootCA.pem"); - let output = Command::new(util::deno_exe_path()) - .env("DENO_DIR", deno_dir.path()) - .current_dir(util::testdata_path()) - .arg("cache") - .arg("--cert") - .arg(cafile) - .arg(module_url.to_string()) - .output() - .expect("Failed to spawn script"); - assert!(output.status.success()); - let out = std::str::from_utf8(&output.stdout).unwrap(); - assert_eq!(out, ""); -} - -#[flaky_test::flaky_test] -fn cafile_install_remote_module() { - let _g = util::http_server(); - let temp_dir = TempDir::new(); - let bin_dir = temp_dir.path().join("bin"); - std::fs::create_dir(&bin_dir).unwrap(); - let deno_dir = TempDir::new(); - let cafile = util::testdata_path().join("tls/RootCA.pem"); - - let install_output = Command::new(util::deno_exe_path()) - .env("DENO_DIR", deno_dir.path()) - .current_dir(util::testdata_path()) - .arg("install") - .arg("--cert") - .arg(cafile) - .arg("--root") - .arg(temp_dir.path()) - .arg("-n") - .arg("echo_test") - .arg("https://localhost:5545/echo.ts") - .output() - .expect("Failed to spawn script"); - println!("{}", std::str::from_utf8(&install_output.stdout).unwrap()); - eprintln!("{}", std::str::from_utf8(&install_output.stderr).unwrap()); - assert!(install_output.status.success()); - - let mut echo_test_path = bin_dir.join("echo_test"); - if cfg!(windows) { - echo_test_path = echo_test_path.with_extension("cmd"); - } - assert!(echo_test_path.exists()); - - let output = Command::new(echo_test_path) - .current_dir(temp_dir.path()) - .arg("foo") - .env("PATH", util::target_dir()) - .output() - .expect("failed to spawn script"); - let stdout = std::str::from_utf8(&output.stdout).unwrap().trim(); - assert!(stdout.ends_with("foo")); -} - -#[flaky_test::flaky_test] -fn cafile_bundle_remote_exports() { - let _g = util::http_server(); - - // First we have to generate a bundle of some remote module that has exports. - let mod1 = "https://localhost:5545/subdir/mod1.ts"; - let cafile = util::testdata_path().join("tls/RootCA.pem"); - let t = TempDir::new(); - let bundle = t.path().join("mod1.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg("--cert") - .arg(cafile) - .arg(mod1) - .arg(&bundle) - .spawn() - .expect("failed to spawn script"); - let status = deno.wait().expect("failed to wait for the child process"); - assert!(status.success()); - assert!(bundle.is_file()); - - // Now we try to use that bundle from another module. - let test = t.path().join("test.js"); - std::fs::write( - &test, - " - import { printHello3 } from \"./mod1.bundle.js\"; - printHello3(); ", - ) - .expect("error writing file"); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--check") - .arg(&test) - .output() - .expect("failed to spawn script"); - // check the output of the test.ts program. - assert!(std::str::from_utf8(&output.stdout) - .unwrap() - .trim() - .ends_with("Hello")); - assert_eq!(output.stderr, b""); -} - -#[tokio::test] -async fn listen_tls_alpn() { - // TLS streams require the presence of an ambient local task set to gracefully - // close dropped connections in the background. - LocalSet::new() - .run_until(async { - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--unstable") - .arg("--quiet") - .arg("--allow-net") - .arg("--allow-read") - .arg("./cert/listen_tls_alpn.ts") - .arg("4504") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let stdout = child.stdout.as_mut().unwrap(); - let mut msg = [0; 5]; - let read = stdout.read(&mut msg).unwrap(); - assert_eq!(read, 5); - assert_eq!(&msg, b"READY"); - - let mut reader = &mut BufReader::new(Cursor::new(include_bytes!( - "../testdata/tls/RootCA.crt" - ))); - let certs = rustls_pemfile::certs(&mut reader).unwrap(); - let mut root_store = rustls::RootCertStore::empty(); - root_store.add_parsable_certificates(&certs); - let mut cfg = rustls::ClientConfig::builder() - .with_safe_defaults() - .with_root_certificates(root_store) - .with_no_client_auth(); - cfg.alpn_protocols.push(b"foobar".to_vec()); - let cfg = Arc::new(cfg); - - let hostname = rustls::ServerName::try_from("localhost").unwrap(); - - let tcp_stream = tokio::net::TcpStream::connect("localhost:4504") - .await - .unwrap(); - let mut tls_stream = - TlsStream::new_client_side(tcp_stream, cfg, hostname); - - tls_stream.handshake().await.unwrap(); - - let (_, rustls_connection) = tls_stream.get_ref(); - let alpn = rustls_connection.alpn_protocol().unwrap(); - assert_eq!(alpn, b"foobar"); - - let status = child.wait().unwrap(); - assert!(status.success()); - }) - .await; -} - -#[tokio::test] -async fn listen_tls_alpn_fail() { - // TLS streams require the presence of an ambient local task set to gracefully - // close dropped connections in the background. - LocalSet::new() - .run_until(async { - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--unstable") - .arg("--quiet") - .arg("--allow-net") - .arg("--allow-read") - .arg("./cert/listen_tls_alpn_fail.ts") - .arg("4505") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let stdout = child.stdout.as_mut().unwrap(); - let mut msg = [0; 5]; - let read = stdout.read(&mut msg).unwrap(); - assert_eq!(read, 5); - assert_eq!(&msg, b"READY"); - - let mut reader = &mut BufReader::new(Cursor::new(include_bytes!( - "../testdata/tls/RootCA.crt" - ))); - let certs = rustls_pemfile::certs(&mut reader).unwrap(); - let mut root_store = rustls::RootCertStore::empty(); - root_store.add_parsable_certificates(&certs); - let mut cfg = rustls::ClientConfig::builder() - .with_safe_defaults() - .with_root_certificates(root_store) - .with_no_client_auth(); - cfg.alpn_protocols.push(b"boofar".to_vec()); - let cfg = Arc::new(cfg); - - let hostname = rustls::ServerName::try_from("localhost").unwrap(); - - let tcp_stream = tokio::net::TcpStream::connect("localhost:4505") - .await - .unwrap(); - let mut tls_stream = - TlsStream::new_client_side(tcp_stream, cfg, hostname); - - tls_stream.handshake().await.unwrap_err(); - - let (_, rustls_connection) = tls_stream.get_ref(); - assert!(rustls_connection.alpn_protocol().is_none()); - - let status = child.wait().unwrap(); - assert!(status.success()); - }) - .await; -} diff --git a/cli/tests/integration/check_tests.rs b/cli/tests/integration/check_tests.rs deleted file mode 100644 index 4b3e512c46..0000000000 --- a/cli/tests/integration/check_tests.rs +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use std::process::Command; -use std::process::Stdio; - -use crate::itest; - -use test_util as util; -use util::TempDir; - -itest!(_095_check_with_bare_import { - args: "check cache/095_cache_with_bare_import.ts", - output: "cache/095_cache_with_bare_import.ts.out", - exit_code: 1, -}); - -itest!(check_extensionless { - args: "check --reload http://localhost:4545/subdir/no_js_ext", - output: "cache/cache_extensionless.out", - http_server: true, -}); - -itest!(check_random_extension { - args: "check --reload http://localhost:4545/subdir/no_js_ext@1.0.0", - output: "cache/cache_random_extension.out", - http_server: true, -}); - -itest!(check_all { - args: "check --quiet --remote check/check_all.ts", - output: "check/check_all.out", - http_server: true, - exit_code: 1, -}); - -itest!(check_all_local { - args: "check --quiet check/check_all.ts", - output_str: Some(""), - http_server: true, -}); - -itest!(module_detection_force { - args: "check --quiet check/module_detection_force/main.ts", - output_str: Some(""), -}); - -// Regression test for https://github.com/denoland/deno/issues/14937. -itest!(declaration_header_file_with_no_exports { - args: "check --quiet check/declaration_header_file_with_no_exports.ts", - output_str: Some(""), -}); - -itest!(check_npm_install_diagnostics { - args: "check --quiet check/npm_install_diagnostics/main.ts", - output: "check/npm_install_diagnostics/main.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], - exit_code: 1, -}); - -itest!(check_export_equals_declaration_file { - args: "check --quiet check/export_equals_declaration_file/main.ts", - exit_code: 0, -}); - -#[test] -fn cache_switching_config_then_no_config() { - let deno_dir = util::new_deno_dir(); - assert!(does_type_checking(&deno_dir, true)); - assert!(does_type_checking(&deno_dir, false)); - - // should now not do type checking even when it changes - // configs because it previously did - assert!(!does_type_checking(&deno_dir, true)); - assert!(!does_type_checking(&deno_dir, false)); - - fn does_type_checking(deno_dir: &util::TempDir, with_config: bool) -> bool { - let mut cmd = util::deno_cmd_with_deno_dir(deno_dir); - cmd - .current_dir(util::testdata_path()) - .stderr(Stdio::piped()) - .arg("check") - .arg("check/cache_config_on_off/main.ts"); - if with_config { - cmd - .arg("--config") - .arg("check/cache_config_on_off/deno.json"); - } - let output = cmd.spawn().unwrap().wait_with_output().unwrap(); - assert!(output.status.success()); - - let stderr = std::str::from_utf8(&output.stderr).unwrap(); - stderr.contains("Check") - } -} - -#[test] -fn reload_flag() { - // should do type checking whenever someone specifies --reload - let deno_dir = util::new_deno_dir(); - assert!(does_type_checking(&deno_dir, false)); - assert!(!does_type_checking(&deno_dir, false)); - assert!(does_type_checking(&deno_dir, true)); - assert!(does_type_checking(&deno_dir, true)); - assert!(!does_type_checking(&deno_dir, false)); - - fn does_type_checking(deno_dir: &util::TempDir, reload: bool) -> bool { - let mut cmd = util::deno_cmd_with_deno_dir(deno_dir); - cmd - .current_dir(util::testdata_path()) - .stderr(Stdio::piped()) - .arg("check") - .arg("check/cache_config_on_off/main.ts"); - if reload { - cmd.arg("--reload"); - } - let output = cmd.spawn().unwrap().wait_with_output().unwrap(); - assert!(output.status.success()); - - let stderr = std::str::from_utf8(&output.stderr).unwrap(); - stderr.contains("Check") - } -} - -#[test] -fn typecheck_declarations_ns() { - let output = util::deno_cmd() - .arg("test") - .arg("--doc") - .arg(util::root_path().join("cli/tsc/dts/lib.deno.ns.d.ts")) - .output() - .unwrap(); - println!("stdout: {}", String::from_utf8(output.stdout).unwrap()); - println!("stderr: {}", String::from_utf8(output.stderr).unwrap()); - assert!(output.status.success()); -} - -#[test] -fn typecheck_declarations_unstable() { - let output = util::deno_cmd() - .arg("test") - .arg("--doc") - .arg("--unstable") - .arg(util::root_path().join("cli/tsc/dts/lib.deno.unstable.d.ts")) - .output() - .unwrap(); - println!("stdout: {}", String::from_utf8(output.stdout).unwrap()); - println!("stderr: {}", String::from_utf8(output.stderr).unwrap()); - assert!(output.status.success()); -} - -#[test] -fn typecheck_core() { - let deno_dir = TempDir::new(); - let test_file = deno_dir.path().join("test_deno_core_types.ts"); - std::fs::write( - &test_file, - format!( - "import \"{}\";", - deno_core::resolve_path( - util::root_path() - .join("core/lib.deno_core.d.ts") - .to_str() - .unwrap() - ) - .unwrap() - ), - ) - .unwrap(); - let output = util::deno_cmd_with_deno_dir(&deno_dir) - .arg("run") - .arg(test_file.to_str().unwrap()) - .output() - .unwrap(); - println!("stdout: {}", String::from_utf8(output.stdout).unwrap()); - println!("stderr: {}", String::from_utf8(output.stderr).unwrap()); - assert!(output.status.success()); -} - -#[test] -fn ts_no_recheck_on_redirect() { - let deno_dir = util::new_deno_dir(); - let e = util::deno_exe_path(); - - let redirect_ts = util::testdata_path().join("run/017_import_redirect.ts"); - assert!(redirect_ts.is_file()); - let mut cmd = Command::new(e.clone()); - cmd.env("DENO_DIR", deno_dir.path()); - let mut initial = cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--check") - .arg(redirect_ts.clone()) - .spawn() - .expect("failed to span script"); - let status_initial = - initial.wait().expect("failed to wait for child process"); - assert!(status_initial.success()); - - let mut cmd = Command::new(e); - cmd.env("DENO_DIR", deno_dir.path()); - let output = cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--check") - .arg(redirect_ts) - .output() - .expect("failed to spawn script"); - - assert!(std::str::from_utf8(&output.stderr).unwrap().is_empty()); -} diff --git a/cli/tests/integration/compile_tests.rs b/cli/tests/integration/compile_tests.rs deleted file mode 100644 index dea17e5986..0000000000 --- a/cli/tests/integration/compile_tests.rs +++ /dev/null @@ -1,533 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use std::fs::File; -use std::process::Command; -use test_util as util; -use test_util::TempDir; - -#[test] -fn compile() { - let dir = TempDir::new(); - let exe = if cfg!(windows) { - dir.path().join("welcome.exe") - } else { - dir.path().join("welcome") - }; - // try this twice to ensure it works with the cache - for _ in 0..2 { - let output = util::deno_cmd_with_deno_dir(&dir) - .current_dir(util::root_path()) - .arg("compile") - .arg("--unstable") - .arg("--output") - .arg(&exe) - .arg("./test_util/std/examples/welcome.ts") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let output = Command::new(&exe) - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, "Welcome to Deno!\n".as_bytes()); - } -} - -#[test] -fn standalone_args() { - let dir = TempDir::new(); - let exe = if cfg!(windows) { - dir.path().join("args.exe") - } else { - dir.path().join("args") - }; - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("compile") - .arg("--unstable") - .arg("--output") - .arg(&exe) - .arg("./compile/args.ts") - .arg("a") - .arg("b") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let output = Command::new(exe) - .arg("foo") - .arg("--bar") - .arg("--unstable") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"a\nb\nfoo\n--bar\n--unstable\n"); -} - -#[test] -fn standalone_error() { - let dir = TempDir::new(); - let exe = if cfg!(windows) { - dir.path().join("error.exe") - } else { - dir.path().join("error") - }; - let testdata_path = util::testdata_path(); - let output = util::deno_cmd() - .current_dir(&testdata_path) - .arg("compile") - .arg("--unstable") - .arg("--output") - .arg(&exe) - .arg("./compile/standalone_error.ts") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let output = Command::new(exe) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - assert_eq!(output.stdout, b""); - let stderr = String::from_utf8(output.stderr).unwrap(); - let stderr = util::strip_ansi_codes(&stderr).to_string(); - // On Windows, we cannot assert the file path (because '\'). - // Instead we just check for relevant output. - assert!(stderr.contains("error: Uncaught Error: boom!")); - assert!(stderr.contains("throw new Error(\"boom!\");")); - assert!(stderr.contains("\n at boom (file://")); - assert!(stderr.contains("standalone_error.ts:2:11")); - assert!(stderr.contains("at foo (file://")); - assert!(stderr.contains("standalone_error.ts:5:5")); - assert!(stderr.contains("standalone_error.ts:7:1")); -} - -#[test] -fn standalone_error_module_with_imports() { - let dir = TempDir::new(); - let exe = if cfg!(windows) { - dir.path().join("error.exe") - } else { - dir.path().join("error") - }; - let testdata_path = util::testdata_path(); - let output = util::deno_cmd() - .current_dir(&testdata_path) - .arg("compile") - .arg("--unstable") - .arg("--output") - .arg(&exe) - .arg("./compile/standalone_error_module_with_imports_1.ts") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let output = Command::new(exe) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - println!("{:#?}", &output); - assert_eq!(output.stdout, b"hello\n"); - let stderr = String::from_utf8(output.stderr).unwrap(); - let stderr = util::strip_ansi_codes(&stderr).to_string(); - // On Windows, we cannot assert the file path (because '\'). - // Instead we just check for relevant output. - assert!(stderr.contains("error: Uncaught Error: boom!")); - assert!(stderr.contains("throw new Error(\"boom!\");")); - assert!(stderr.contains("\n at file://")); - assert!(stderr.contains("standalone_error_module_with_imports_2.ts:2:7")); -} - -#[test] -fn standalone_load_datauri() { - let dir = TempDir::new(); - let exe = if cfg!(windows) { - dir.path().join("load_datauri.exe") - } else { - dir.path().join("load_datauri") - }; - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("compile") - .arg("--unstable") - .arg("--output") - .arg(&exe) - .arg("./compile/standalone_import_datauri.ts") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let output = Command::new(exe) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Hello Deno!\n"); -} - -// https://github.com/denoland/deno/issues/13704 -#[test] -fn standalone_follow_redirects() { - let dir = TempDir::new(); - let exe = if cfg!(windows) { - dir.path().join("follow_redirects.exe") - } else { - dir.path().join("follow_redirects") - }; - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("compile") - .arg("--unstable") - .arg("--output") - .arg(&exe) - .arg("./compile/standalone_follow_redirects.ts") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let output = Command::new(exe) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Hello\n"); -} - -#[test] -fn compile_with_file_exists_error() { - let dir = TempDir::new(); - let output_path = if cfg!(windows) { - dir.path().join(r"args\") - } else { - dir.path().join("args/") - }; - let file_path = dir.path().join("args"); - File::create(&file_path).unwrap(); - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("compile") - .arg("--unstable") - .arg("--output") - .arg(&output_path) - .arg("./compile/args.ts") - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - let expected_stderr = format!( - concat!( - "Could not compile to file '{}' because its parent directory ", - "is an existing file. You can use the `--output ` flag to ", - "provide an alternative name.\n", - ), - file_path.display(), - ); - let stderr = String::from_utf8(output.stderr).unwrap(); - assert!(stderr.contains(&expected_stderr)); -} - -#[test] -fn compile_with_directory_exists_error() { - let dir = TempDir::new(); - let exe = if cfg!(windows) { - dir.path().join("args.exe") - } else { - dir.path().join("args") - }; - std::fs::create_dir(&exe).unwrap(); - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("compile") - .arg("--unstable") - .arg("--output") - .arg(&exe) - .arg("./compile/args.ts") - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - let expected_stderr = format!( - concat!( - "Could not compile to file '{}' because a directory exists with ", - "the same name. You can use the `--output ` flag to ", - "provide an alternative name." - ), - exe.display() - ); - let stderr = String::from_utf8(output.stderr).unwrap(); - assert!(stderr.contains(&expected_stderr)); -} - -#[test] -fn compile_with_conflict_file_exists_error() { - let dir = TempDir::new(); - let exe = if cfg!(windows) { - dir.path().join("args.exe") - } else { - dir.path().join("args") - }; - std::fs::write(&exe, b"SHOULD NOT BE OVERWRITTEN").unwrap(); - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("compile") - .arg("--unstable") - .arg("--output") - .arg(&exe) - .arg("./compile/args.ts") - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - let expected_stderr = format!( - concat!( - "Could not compile to file '{}' because the file already exists ", - "and cannot be overwritten. Please delete the existing file or ", - "use the `--output 1); -} - -itest!(eval_basic { - args: "eval console.log(\"hello\")", - output_str: Some("hello\n"), -}); - -// Ugly parentheses due to whitespace delimiting problem. -itest!(eval_ts { - args: "eval --quiet --ext=ts console.log((123)as(number))", // 'as' is a TS keyword only - output_str: Some("123\n"), -}); - -itest!(dyn_import_eval { - args: "eval import('./subdir/mod4.js').then(console.log)", - output: "eval/dyn_import_eval.out", -}); - -// Cannot write the expression to evaluate as "console.log(typeof gc)" -// because itest! splits args on whitespace. -itest!(v8_flags_eval { - args: "eval --v8-flags=--expose-gc console.log(typeof(gc))", - output: "run/v8_flags.js.out", -}); - -itest!(check_local_by_default { - args: "eval --quiet import('http://localhost:4545/subdir/type_error.ts').then(console.log);", - output: "eval/check_local_by_default.out", - http_server: true, -}); - -itest!(check_local_by_default2 { - args: "eval --quiet import('./eval/check_local_by_default2.ts').then(console.log);", - output: "eval/check_local_by_default2.out", - http_server: true, -}); diff --git a/cli/tests/integration/flags_tests.rs b/cli/tests/integration/flags_tests.rs deleted file mode 100644 index 5e3814e223..0000000000 --- a/cli/tests/integration/flags_tests.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use crate::itest; -use test_util as util; - -#[test] -fn help_flag() { - let status = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("--help") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); -} - -#[test] -fn version_short_flag() { - let status = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("-V") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); -} - -#[test] -fn version_long_flag() { - let status = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("--version") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); -} - -itest!(types { - args: "types", - output: "types/types.out", -}); diff --git a/cli/tests/integration/fmt_tests.rs b/cli/tests/integration/fmt_tests.rs deleted file mode 100644 index 53b45de199..0000000000 --- a/cli/tests/integration/fmt_tests.rs +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use crate::itest; -use test_util as util; -use test_util::TempDir; - -#[test] -fn fmt_test() { - let t = TempDir::new(); - let testdata_fmt_dir = util::testdata_path().join("fmt"); - let fixed_js = testdata_fmt_dir.join("badly_formatted_fixed.js"); - let badly_formatted_original_js = - testdata_fmt_dir.join("badly_formatted.mjs"); - let badly_formatted_js = t.path().join("badly_formatted.js"); - let badly_formatted_js_str = badly_formatted_js.to_str().unwrap(); - std::fs::copy(&badly_formatted_original_js, &badly_formatted_js).unwrap(); - - let fixed_md = testdata_fmt_dir.join("badly_formatted_fixed.md"); - let badly_formatted_original_md = testdata_fmt_dir.join("badly_formatted.md"); - let badly_formatted_md = t.path().join("badly_formatted.md"); - let badly_formatted_md_str = badly_formatted_md.to_str().unwrap(); - std::fs::copy(&badly_formatted_original_md, &badly_formatted_md).unwrap(); - - let fixed_json = testdata_fmt_dir.join("badly_formatted_fixed.json"); - let badly_formatted_original_json = - testdata_fmt_dir.join("badly_formatted.json"); - let badly_formatted_json = t.path().join("badly_formatted.json"); - let badly_formatted_json_str = badly_formatted_json.to_str().unwrap(); - std::fs::copy(&badly_formatted_original_json, &badly_formatted_json).unwrap(); - // First, check formatting by ignoring the badly formatted file. - let status = util::deno_cmd() - .current_dir(&testdata_fmt_dir) - .arg("fmt") - .arg(format!( - "--ignore={},{},{}", - badly_formatted_js_str, badly_formatted_md_str, badly_formatted_json_str - )) - .arg("--check") - .arg(badly_formatted_js_str) - .arg(badly_formatted_md_str) - .arg(badly_formatted_json_str) - .spawn() - .unwrap() - .wait() - .unwrap(); - // No target files found - assert!(!status.success()); - - // Check without ignore. - let status = util::deno_cmd() - .current_dir(&testdata_fmt_dir) - .arg("fmt") - .arg("--check") - .arg(badly_formatted_js_str) - .arg(badly_formatted_md_str) - .arg(badly_formatted_json_str) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(!status.success()); - - // Format the source file. - let status = util::deno_cmd() - .current_dir(&testdata_fmt_dir) - .arg("fmt") - .arg(badly_formatted_js_str) - .arg(badly_formatted_md_str) - .arg(badly_formatted_json_str) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - let expected_js = std::fs::read_to_string(fixed_js).unwrap(); - let expected_md = std::fs::read_to_string(fixed_md).unwrap(); - let expected_json = std::fs::read_to_string(fixed_json).unwrap(); - let actual_js = std::fs::read_to_string(badly_formatted_js).unwrap(); - let actual_md = std::fs::read_to_string(badly_formatted_md).unwrap(); - let actual_json = std::fs::read_to_string(badly_formatted_json).unwrap(); - assert_eq!(expected_js, actual_js); - assert_eq!(expected_md, actual_md); - assert_eq!(expected_json, actual_json); -} - -#[test] -fn fmt_stdin_error() { - use std::io::Write; - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("fmt") - .arg("-") - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let stdin = deno.stdin.as_mut().unwrap(); - let invalid_js = b"import { example }"; - stdin.write_all(invalid_js).unwrap(); - let output = deno.wait_with_output().unwrap(); - // Error message might change. Just check stdout empty, stderr not. - assert!(output.stdout.is_empty()); - assert!(!output.stderr.is_empty()); - assert!(!output.status.success()); -} - -#[test] -fn fmt_ignore_unexplicit_files() { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .env("NO_COLOR", "1") - .arg("fmt") - .arg("--check") - .arg("--ignore=./") - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - assert_eq!( - String::from_utf8_lossy(&output.stderr), - "error: No target files found.\n" - ); -} - -#[test] -fn fmt_auto_ignore_git_and_node_modules() { - use std::fs::{create_dir_all, File}; - use std::io::Write; - use std::path::PathBuf; - fn create_bad_json(t: PathBuf) { - let bad_json_path = t.join("bad.json"); - let mut bad_json_file = File::create(bad_json_path).unwrap(); - writeln!(bad_json_file, "bad json").unwrap(); - } - let temp_dir = TempDir::new(); - let t = temp_dir.path().join("target"); - let nest_git = t.join("nest").join(".git"); - let git_dir = t.join(".git"); - let nest_node_modules = t.join("nest").join("node_modules"); - let node_modules_dir = t.join("node_modules"); - create_dir_all(&nest_git).unwrap(); - create_dir_all(&git_dir).unwrap(); - create_dir_all(&nest_node_modules).unwrap(); - create_dir_all(&node_modules_dir).unwrap(); - create_bad_json(nest_git); - create_bad_json(git_dir); - create_bad_json(nest_node_modules); - create_bad_json(node_modules_dir); - let output = util::deno_cmd() - .current_dir(t) - .env("NO_COLOR", "1") - .arg("fmt") - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - assert_eq!( - String::from_utf8_lossy(&output.stderr), - "error: No target files found.\n" - ); -} - -itest!(fmt_quiet_check_fmt_dir { - args: "fmt --check --quiet fmt/regular/", - output_str: Some(""), - exit_code: 0, -}); - -itest!(fmt_check_formatted_files { - args: "fmt --check fmt/regular/formatted1.js fmt/regular/formatted2.ts fmt/regular/formatted3.markdown fmt/regular/formatted4.jsonc", - output: "fmt/expected_fmt_check_formatted_files.out", - exit_code: 0, - }); - -itest!(fmt_check_ignore { - args: "fmt --check --ignore=fmt/regular/formatted1.js fmt/regular/", - output: "fmt/expected_fmt_check_ignore.out", - exit_code: 0, -}); - -itest!(fmt_check_parse_error { - args: "fmt --check fmt/parse_error/parse_error.ts", - output: "fmt/fmt_check_parse_error.out", - exit_code: 1, -}); - -itest!(fmt_stdin { - args: "fmt -", - input: Some("const a = 1\n"), - output_str: Some("const a = 1;\n"), -}); - -itest!(fmt_stdin_markdown { - args: "fmt --ext=md -", - input: Some("# Hello Markdown\n```ts\nconsole.log( \"text\")\n```\n\n```cts\nconsole.log( 5 )\n```"), - output_str: Some("# Hello Markdown\n\n```ts\nconsole.log(\"text\");\n```\n\n```cts\nconsole.log(5);\n```\n"), -}); - -itest!(fmt_stdin_json { - args: "fmt --ext=json -", - input: Some("{ \"key\": \"value\"}"), - output_str: Some("{ \"key\": \"value\" }\n"), -}); - -itest!(fmt_stdin_check_formatted { - args: "fmt --check -", - input: Some("const a = 1;\n"), - output_str: Some(""), -}); - -itest!(fmt_stdin_check_not_formatted { - args: "fmt --check -", - input: Some("const a = 1\n"), - output_str: Some("Not formatted stdin\n"), -}); - -itest!(fmt_with_config { - args: "fmt --config fmt/with_config/deno.jsonc fmt/with_config/subdir", - output: "fmt/fmt_with_config.out", -}); - -itest!(fmt_with_config_default { - args: "fmt fmt/with_config/subdir", - output: "fmt/fmt_with_config.out", -}); - -// Check if CLI flags take precedence -itest!(fmt_with_config_and_flags { - args: "fmt --config fmt/with_config/deno.jsonc --ignore=fmt/with_config/subdir/a.ts,fmt/with_config/subdir/b.ts", - output: "fmt/fmt_with_config_and_flags.out", -}); - -itest!(fmt_with_malformed_config { - args: "fmt --config fmt/deno.malformed.jsonc", - output: "fmt/fmt_with_malformed_config.out", - exit_code: 1, -}); - -itest!(fmt_with_malformed_config2 { - args: "fmt --config fmt/deno.malformed2.jsonc", - output: "fmt/fmt_with_malformed_config2.out", - exit_code: 1, -}); diff --git a/cli/tests/integration/info_tests.rs b/cli/tests/integration/info_tests.rs deleted file mode 100644 index 0d2d81cc08..0000000000 --- a/cli/tests/integration/info_tests.rs +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use crate::itest; - -use test_util as util; -use test_util::TempDir; - -#[test] -fn info_with_compiled_source() { - let _g = util::http_server(); - let module_path = "http://127.0.0.1:4545/run/048_media_types_jsx.ts"; - let t = TempDir::new(); - - let mut deno = util::deno_cmd() - .env("DENO_DIR", t.path()) - .current_dir(util::testdata_path()) - .arg("cache") - .arg(module_path) - .spawn() - .unwrap(); - let status = deno.wait().unwrap(); - assert!(status.success()); - - let output = util::deno_cmd() - .env("DENO_DIR", t.path()) - .env("NO_COLOR", "1") - .current_dir(util::testdata_path()) - .arg("info") - .arg(module_path) - .output() - .unwrap(); - - let str_output = std::str::from_utf8(&output.stdout).unwrap().trim(); - eprintln!("{}", str_output); - // check the output of the test.ts program. - assert!(str_output.contains("emit: ")); - assert_eq!(output.stderr, b""); -} - -itest!(multiple_imports { - args: "info http://127.0.0.1:4545/run/019_media_types.ts", - output: "info/multiple_imports.out", - http_server: true, -}); - -itest!(info_ts_error { - args: "info info/031_info_ts_error.ts", - output: "info/031_info_ts_error.out", -}); - -itest!(info_flag { - args: "info", - output: "info/041_info_flag.out", -}); - -itest!(info_flag_location { - args: "info --location https://deno.land", - output: "info/041_info_flag_location.out", -}); - -itest!(info_json { - args: "info --json --unstable", - output: "info/info_json.out", -}); - -itest!(info_json_location { - args: "info --json --unstable --location https://deno.land", - output: "info/info_json_location.out", -}); - -itest!(info_flag_script_jsx { - args: "info http://127.0.0.1:4545/run/048_media_types_jsx.ts", - output: "info/049_info_flag_script_jsx.out", - http_server: true, -}); - -itest!(json_file { - args: "info --quiet --json --unstable info/json_output/main.ts", - output: "info/json_output/main.out", - exit_code: 0, -}); - -itest!(import_map_info { - args: - "info --quiet --import-map=import_maps/import_map.json import_maps/test.ts", - output: "info/065_import_map_info.out", -}); - -itest!(info_json_deps_order { - args: "info --unstable --json info/076_info_json_deps_order.ts", - output: "info/076_info_json_deps_order.out", -}); - -itest!(info_missing_module { - args: "info info/error_009_missing_js_module.js", - output: "info/info_missing_module.out", -}); - -itest!(info_recursive_modules { - args: "info --quiet info/info_recursive_imports_test.ts", - output: "info/info_recursive_imports_test.out", - exit_code: 0, -}); - -itest!(info_type_import { - args: "info info/info_type_import.ts", - output: "info/info_type_import.out", -}); - -itest!(_054_info_local_imports { - args: "info --quiet run/005_more_imports.ts", - output: "info/054_info_local_imports.out", - exit_code: 0, -}); - -// Tests for AssertionError where "data" is unexpectedly null when -// a file contains only triple slash references (#11196) -itest!(data_null_error { - args: "info info/data_null_error/mod.ts", - output: "info/data_null_error/data_null_error.out", -}); - -itest!(types_header_direct { - args: "info --reload run/type_directives_01.ts", - output: "info/types_header.out", - http_server: true, -}); - -itest!(with_config_override { - args: "info info/with_config/test.ts --config info/with_config/deno-override.json --import-map info/with_config/import_map.json", - output: "info/with_config/with_config.out", -}); diff --git a/cli/tests/integration/init_tests.rs b/cli/tests/integration/init_tests.rs deleted file mode 100644 index e597e117c0..0000000000 --- a/cli/tests/integration/init_tests.rs +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use std::process::Stdio; -use test_util as util; -use test_util::TempDir; -use util::assert_contains; - -#[test] -fn init_subcommand_without_dir() { - let temp_dir = TempDir::new(); - let cwd = temp_dir.path(); - let deno_dir = util::new_deno_dir(); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(cwd) - .arg("init") - .stderr(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let stderr = String::from_utf8(output.stderr).unwrap(); - assert_contains!(stderr, "Project initialized"); - assert!(!stderr.contains("cd")); - assert_contains!(stderr, "deno run main.ts"); - assert_contains!(stderr, "deno test"); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(cwd) - .env("NO_COLOR", "1") - .arg("run") - .arg("main.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Add 2 + 3 = 5\n"); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(cwd) - .env("NO_COLOR", "1") - .arg("test") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let stdout = String::from_utf8(output.stdout).unwrap(); - assert_contains!(stdout, "1 passed"); -} - -#[test] -fn init_subcommand_with_dir_arg() { - let temp_dir = TempDir::new(); - let cwd = temp_dir.path(); - let deno_dir = util::new_deno_dir(); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(cwd) - .arg("init") - .arg("my_dir") - .stderr(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let stderr = String::from_utf8(output.stderr).unwrap(); - assert_contains!(stderr, "Project initialized"); - assert_contains!(stderr, "cd my_dir"); - assert_contains!(stderr, "deno run main.ts"); - assert_contains!(stderr, "deno test"); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(cwd) - .env("NO_COLOR", "1") - .arg("run") - .arg("my_dir/main.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Add 2 + 3 = 5\n"); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(cwd) - .env("NO_COLOR", "1") - .arg("test") - .arg("my_dir/main_test.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let stdout = String::from_utf8(output.stdout).unwrap(); - assert_contains!(stdout, "1 passed"); -} - -#[test] -fn init_subcommand_with_quiet_arg() { - let temp_dir = TempDir::new(); - let cwd = temp_dir.path(); - let deno_dir = util::new_deno_dir(); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(cwd) - .arg("init") - .arg("--quiet") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let stdout = String::from_utf8(output.stdout).unwrap(); - assert_eq!(stdout, ""); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(cwd) - .env("NO_COLOR", "1") - .arg("run") - .arg("main.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Add 2 + 3 = 5\n"); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(cwd) - .env("NO_COLOR", "1") - .arg("test") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let stdout = String::from_utf8(output.stdout).unwrap(); - assert_contains!(stdout, "1 passed"); -} diff --git a/cli/tests/integration/inspector_tests.rs b/cli/tests/integration/inspector_tests.rs deleted file mode 100644 index 4b9f95f7fa..0000000000 --- a/cli/tests/integration/inspector_tests.rs +++ /dev/null @@ -1,1118 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use deno_core::futures; -use deno_core::futures::prelude::*; -use deno_core::futures::stream::SplitSink; -use deno_core::serde_json; -use deno_core::url; -use deno_runtime::deno_fetch::reqwest; -use deno_runtime::deno_websocket::tokio_tungstenite; -use deno_runtime::deno_websocket::tokio_tungstenite::tungstenite; -use std::io::BufRead; -use std::pin::Pin; -use test_util as util; -use tokio::net::TcpStream; - -macro_rules! assert_starts_with { - ($string:expr, $($test:expr),+) => { - let string = $string; // This might be a function call or something - if !($(string.starts_with($test))||+) { - panic!("{:?} does not start with {:?}", string, [$($test),+]); - } - } -} - -fn inspect_flag_with_unique_port(flag_prefix: &str) -> String { - use std::sync::atomic::{AtomicU16, Ordering}; - static PORT: AtomicU16 = AtomicU16::new(9229); - let port = PORT.fetch_add(1, Ordering::Relaxed); - format!("{}=127.0.0.1:{}", flag_prefix, port) -} - -fn extract_ws_url_from_stderr( - stderr_lines: &mut impl std::iter::Iterator, -) -> url::Url { - let stderr_first_line = skip_check_line(stderr_lines); - assert_starts_with!(&stderr_first_line, "Debugger listening on "); - let v: Vec<_> = stderr_first_line.match_indices("ws:").collect(); - assert_eq!(v.len(), 1); - let ws_url_index = v[0].0; - let ws_url = &stderr_first_line[ws_url_index..]; - url::Url::parse(ws_url).unwrap() -} - -fn skip_check_line( - stderr_lines: &mut impl std::iter::Iterator, -) -> String { - loop { - let mut line = stderr_lines.next().unwrap(); - line = util::strip_ansi_codes(&line).to_string(); - - if line.starts_with("Check") { - continue; - } - - return line; - } -} - -fn assert_stderr( - stderr_lines: &mut impl std::iter::Iterator, - expected_lines: &[&str], -) { - let mut expected_index = 0; - - loop { - let line = skip_check_line(stderr_lines); - - assert_eq!(line, expected_lines[expected_index]); - expected_index += 1; - - if expected_index >= expected_lines.len() { - break; - } - } -} - -fn assert_stderr_for_inspect( - stderr_lines: &mut impl std::iter::Iterator, -) { - assert_stderr( - stderr_lines, - &["Visit chrome://inspect to connect to the debugger."], - ); -} - -fn assert_stderr_for_inspect_brk( - stderr_lines: &mut impl std::iter::Iterator, -) { - assert_stderr( - stderr_lines, - &[ - "Visit chrome://inspect to connect to the debugger.", - "Deno is waiting for debugger to connect.", - ], - ); -} - -async fn assert_inspector_messages( - socket_tx: &mut SplitSink< - tokio_tungstenite::WebSocketStream< - tokio_tungstenite::MaybeTlsStream, - >, - tungstenite::Message, - >, - messages: &[&str], - socket_rx: &mut Pin>>, - responses: &[&str], - notifications: &[&str], -) { - for msg in messages { - socket_tx.send(msg.to_string().into()).await.unwrap(); - } - - let expected_messages = responses.len() + notifications.len(); - let mut responses_idx = 0; - let mut notifications_idx = 0; - - for _ in 0..expected_messages { - let msg = socket_rx.next().await.unwrap(); - - if msg.starts_with(r#"{"id":"#) { - assert!( - msg.starts_with(responses[responses_idx]), - "Doesn't start with {}, instead received {}", - responses[responses_idx], - msg - ); - responses_idx += 1; - } else { - assert!( - msg.starts_with(notifications[notifications_idx]), - "Doesn't start with {}, instead received {}", - notifications[notifications_idx], - msg - ); - notifications_idx += 1; - } - } -} - -#[tokio::test] -async fn inspector_connect() { - let script = util::testdata_path().join("inspector/inspector1.js"); - let mut child = util::deno_cmd() - .arg("run") - .arg(inspect_flag_with_unique_port("--inspect")) - .arg(script) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - - // We use tokio_tungstenite as a websocket client because warp (which is - // a dependency of Deno) uses it. - let (_socket, response) = - tokio_tungstenite::connect_async(ws_url).await.unwrap(); - assert_eq!("101 Switching Protocols", response.status().to_string()); - child.kill().unwrap(); - child.wait().unwrap(); -} - -#[tokio::test] -async fn inspector_break_on_first_line() { - let script = util::testdata_path().join("inspector/inspector2.js"); - let mut child = util::deno_cmd() - .arg("run") - .arg(inspect_flag_with_unique_port("--inspect-brk")) - .arg(script) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - - let (socket, response) = - tokio_tungstenite::connect_async(ws_url).await.unwrap(); - assert_eq!(response.status(), 101); // Switching protocols. - - let (mut socket_tx, socket_rx) = socket.split(); - let mut socket_rx = socket_rx - .map(|msg| msg.unwrap().to_string()) - .filter(|msg| { - let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#); - futures::future::ready(pass) - }) - .boxed_local(); - - let stdout = child.stdout.as_mut().unwrap(); - let mut stdout_lines = - std::io::BufReader::new(stdout).lines().map(|r| r.unwrap()); - - assert_stderr_for_inspect_brk(&mut stderr_lines); - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":1,"method":"Runtime.enable"}"#, - r#"{"id":2,"method":"Debugger.enable"}"#, - ], - &mut socket_rx, - &[ - r#"{"id":1,"result":{}}"#, - r#"{"id":2,"result":{"debuggerId":"#, - ], - &[ - r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, - ], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#], - &mut socket_rx, - &[r#"{"id":3,"result":{}}"#], - &[r#"{"method":"Debugger.paused","#], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":4,"method":"Runtime.evaluate","params":{"expression":"Deno.core.print(\"hello from the inspector\\n\")","contextId":1,"includeCommandLineAPI":true,"silent":false,"returnByValue":true}}"#, - ], - &mut socket_rx, - &[r#"{"id":4,"result":{"result":{"type":"undefined"}}}"#], - &[], - ) - .await; - - assert_eq!(&stdout_lines.next().unwrap(), "hello from the inspector"); - - assert_inspector_messages( - &mut socket_tx, - &[r#"{"id":5,"method":"Debugger.resume"}"#], - &mut socket_rx, - &[r#"{"id":5,"result":{}}"#], - &[], - ) - .await; - - assert_eq!(&stdout_lines.next().unwrap(), "hello from the script"); - - child.kill().unwrap(); - child.wait().unwrap(); -} - -#[tokio::test] -async fn inspector_pause() { - let script = util::testdata_path().join("inspector/inspector1.js"); - let mut child = util::deno_cmd() - .arg("run") - .arg(inspect_flag_with_unique_port("--inspect")) - .arg(script) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - - // We use tokio_tungstenite as a websocket client because warp (which is - // a dependency of Deno) uses it. - let (mut socket, _) = tokio_tungstenite::connect_async(ws_url).await.unwrap(); - - /// Returns the next websocket message as a string ignoring - /// Debugger.scriptParsed messages. - async fn ws_read_msg( - socket: &mut tokio_tungstenite::WebSocketStream< - tokio_tungstenite::MaybeTlsStream, - >, - ) -> String { - use deno_core::futures::stream::StreamExt; - while let Some(msg) = socket.next().await { - let msg = msg.unwrap().to_string(); - // FIXME(bartlomieju): fails because there's a file loaded - // called 150_errors.js - // assert!(!msg.contains("error")); - if !msg.contains("Debugger.scriptParsed") { - return msg; - } - } - unreachable!() - } - - socket - .send(r#"{"id":6,"method":"Debugger.enable"}"#.into()) - .await - .unwrap(); - - let msg = ws_read_msg(&mut socket).await; - println!("response msg 1 {}", msg); - assert_starts_with!(msg, r#"{"id":6,"result":{"debuggerId":"#); - - socket - .send(r#"{"id":31,"method":"Debugger.pause"}"#.into()) - .await - .unwrap(); - - let msg = ws_read_msg(&mut socket).await; - println!("response msg 2 {}", msg); - assert_eq!(msg, r#"{"id":31,"result":{}}"#); - - child.kill().unwrap(); -} - -#[tokio::test] -async fn inspector_port_collision() { - // Skip this test on WSL, which allows multiple processes to listen on the - // same port, rather than making `bind()` fail with `EADDRINUSE`. - if cfg!(target_os = "linux") && std::env::var_os("WSL_DISTRO_NAME").is_some() - { - return; - } - - let script = util::testdata_path().join("inspector/inspector1.js"); - let inspect_flag = inspect_flag_with_unique_port("--inspect"); - - let mut child1 = util::deno_cmd() - .arg("run") - .arg(&inspect_flag) - .arg(script.clone()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr_1 = child1.stderr.as_mut().unwrap(); - let mut stderr_1_lines = std::io::BufReader::new(stderr_1) - .lines() - .map(|r| r.unwrap()); - let _ = extract_ws_url_from_stderr(&mut stderr_1_lines); - - let mut child2 = util::deno_cmd() - .arg("run") - .arg(&inspect_flag) - .arg(script) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr_2 = child2.stderr.as_mut().unwrap(); - let stderr_2_error_message = std::io::BufReader::new(stderr_2) - .lines() - .map(|r| r.unwrap()) - .inspect(|line| assert!(!line.contains("Debugger listening"))) - .find(|line| line.contains("Cannot start inspector server")); - assert!(stderr_2_error_message.is_some()); - - child1.kill().unwrap(); - child1.wait().unwrap(); - child2.wait().unwrap(); -} - -#[tokio::test] -async fn inspector_does_not_hang() { - let script = util::testdata_path().join("inspector/inspector3.js"); - let mut child = util::deno_cmd() - .arg("run") - .arg(inspect_flag_with_unique_port("--inspect-brk")) - .env("NO_COLOR", "1") - .arg(script) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - - let (socket, response) = - tokio_tungstenite::connect_async(ws_url).await.unwrap(); - assert_eq!(response.status(), 101); // Switching protocols. - - let (mut socket_tx, socket_rx) = socket.split(); - let mut socket_rx = socket_rx - .map(|msg| msg.unwrap().to_string()) - .filter(|msg| { - let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#); - futures::future::ready(pass) - }) - .boxed_local(); - - let stdout = child.stdout.as_mut().unwrap(); - let mut stdout_lines = - std::io::BufReader::new(stdout).lines().map(|r| r.unwrap()); - - assert_stderr_for_inspect_brk(&mut stderr_lines); - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":1,"method":"Runtime.enable"}"#, - r#"{"id":2,"method":"Debugger.enable"}"#, - ], - &mut socket_rx, - &[ - r#"{"id":1,"result":{}}"#, - r#"{"id":2,"result":{"debuggerId":"# - ], - &[ - r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"# - ], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#], - &mut socket_rx, - &[r#"{"id":3,"result":{}}"#], - &[r#"{"method":"Debugger.paused","#], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[r#"{"id":4,"method":"Debugger.resume"}"#], - &mut socket_rx, - &[r#"{"id":4,"result":{}}"#], - &[r#"{"method":"Debugger.resumed","params":{}}"#], - ) - .await; - - for i in 0..128u32 { - let request_id = i + 10; - // Expect the number {i} on stdout. - let s = i.to_string(); - assert_eq!(stdout_lines.next().unwrap(), s); - - assert_inspector_messages( - &mut socket_tx, - &[], - &mut socket_rx, - &[], - &[ - r#"{"method":"Runtime.consoleAPICalled","#, - r#"{"method":"Debugger.paused","#, - ], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[&format!( - r#"{{"id":{},"method":"Debugger.resume"}}"#, - request_id - )], - &mut socket_rx, - &[&format!(r#"{{"id":{},"result":{{}}}}"#, request_id)], - &[r#"{"method":"Debugger.resumed","params":{}}"#], - ) - .await; - } - - // Check that we can gracefully close the websocket connection. - socket_tx.close().await.unwrap(); - socket_rx.for_each(|_| async {}).await; - - assert_eq!(&stdout_lines.next().unwrap(), "done"); - assert!(child.wait().unwrap().success()); -} - -#[tokio::test] -async fn inspector_without_brk_runs_code() { - let script = util::testdata_path().join("inspector/inspector4.js"); - let mut child = util::deno_cmd() - .arg("run") - .arg(inspect_flag_with_unique_port("--inspect")) - .arg(script) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let _ = extract_ws_url_from_stderr(&mut stderr_lines); - - // Check that inspector actually runs code without waiting for inspector - // connection. - let stdout = child.stdout.as_mut().unwrap(); - let mut stdout_lines = - std::io::BufReader::new(stdout).lines().map(|r| r.unwrap()); - let stdout_first_line = stdout_lines.next().unwrap(); - assert_eq!(stdout_first_line, "hello"); - - child.kill().unwrap(); - child.wait().unwrap(); -} - -#[tokio::test] -async fn inspector_runtime_evaluate_does_not_crash() { - let mut child = util::deno_cmd() - .arg("repl") - .arg(inspect_flag_with_unique_port("--inspect")) - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = std::io::BufReader::new(stderr) - .lines() - .map(|r| r.unwrap()) - .filter(|s| s.as_str() != "Debugger session started."); - let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - - let (socket, response) = - tokio_tungstenite::connect_async(ws_url).await.unwrap(); - assert_eq!(response.status(), 101); // Switching protocols. - - let (mut socket_tx, socket_rx) = socket.split(); - let mut socket_rx = socket_rx - .map(|msg| msg.unwrap().to_string()) - .filter(|msg| { - let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#); - futures::future::ready(pass) - }) - .boxed_local(); - - let stdin = child.stdin.take().unwrap(); - - let stdout = child.stdout.as_mut().unwrap(); - let mut stdout_lines = std::io::BufReader::new(stdout) - .lines() - .map(|r| r.unwrap()) - .filter(|s| !s.starts_with("Deno ")); - - assert_stderr_for_inspect(&mut stderr_lines); - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":1,"method":"Runtime.enable"}"#, - r#"{"id":2,"method":"Debugger.enable"}"#, - ], - &mut socket_rx, - &[ - r#"{"id":1,"result":{}}"#, - r#"{"id":2,"result":{"debuggerId":"#, - ], - &[ - r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, - ], - ) - .await; - - assert_eq!(&stdout_lines.next().unwrap(), "Run repl.help() for help"); - assert_eq!( - &stdout_lines.next().unwrap(), - "exit using ctrl+d, ctrl+c, or close()" - ); - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":3,"method":"Runtime.compileScript","params":{"expression":"Deno.cwd()","sourceURL":"","persistScript":false,"executionContextId":1}}"#, - ], - &mut socket_rx, - &[r#"{"id":3,"result":{}}"#], &[] - ).await; - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":4,"method":"Runtime.evaluate","params":{"expression":"Deno.cwd()","objectGroup":"console","includeCommandLineAPI":true,"silent":false,"contextId":1,"returnByValue":true,"generatePreview":true,"userGesture":true,"awaitPromise":false,"replMode":true}}"#, - ], - &mut socket_rx, - &[r#"{"id":4,"result":{"result":{"type":"string","value":""#], - &[], - ).await; - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":5,"method":"Runtime.evaluate","params":{"expression":"console.error('done');","objectGroup":"console","includeCommandLineAPI":true,"silent":false,"contextId":1,"returnByValue":true,"generatePreview":true,"userGesture":true,"awaitPromise":false,"replMode":true}}"#, - ], - &mut socket_rx, - &[r#"{"id":5,"result":{"result":{"type":"undefined"}}}"#], - &[r#"{"method":"Runtime.consoleAPICalled"#], - ).await; - - assert_eq!(&stderr_lines.next().unwrap(), "done"); - - drop(stdin); - child.wait().unwrap(); -} - -#[tokio::test] -async fn inspector_json() { - let script = util::testdata_path().join("inspector/inspector1.js"); - let mut child = util::deno_cmd() - .arg("run") - .arg(inspect_flag_with_unique_port("--inspect")) - .arg(script) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - let mut url = ws_url.clone(); - let _ = url.set_scheme("http"); - url.set_path("/json"); - let resp = reqwest::get(url).await.unwrap(); - assert_eq!(resp.status(), reqwest::StatusCode::OK); - let endpoint_list: Vec = - serde_json::from_str(&resp.text().await.unwrap()).unwrap(); - let matching_endpoint = endpoint_list - .iter() - .find(|e| e["webSocketDebuggerUrl"] == ws_url.as_str()); - assert!(matching_endpoint.is_some()); - child.kill().unwrap(); -} - -#[tokio::test] -async fn inspector_json_list() { - let script = util::testdata_path().join("inspector/inspector1.js"); - let mut child = util::deno_cmd() - .arg("run") - .arg(inspect_flag_with_unique_port("--inspect")) - .arg(script) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - let mut url = ws_url.clone(); - let _ = url.set_scheme("http"); - url.set_path("/json/list"); - let resp = reqwest::get(url).await.unwrap(); - assert_eq!(resp.status(), reqwest::StatusCode::OK); - let endpoint_list: Vec = - serde_json::from_str(&resp.text().await.unwrap()).unwrap(); - let matching_endpoint = endpoint_list - .iter() - .find(|e| e["webSocketDebuggerUrl"] == ws_url.as_str()); - assert!(matching_endpoint.is_some()); - child.kill().unwrap(); -} - -#[tokio::test] -async fn inspector_connect_non_ws() { - // https://github.com/denoland/deno/issues/11449 - // Verify we don't panic if non-WS connection is being established - let script = util::testdata_path().join("inspector/inspector1.js"); - let mut child = util::deno_cmd() - .arg("run") - .arg(inspect_flag_with_unique_port("--inspect")) - .arg(script) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let mut ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - // Change scheme to URL and try send a request. We're not interested - // in the request result, just that the process doesn't panic. - ws_url.set_scheme("http").unwrap(); - let resp = reqwest::get(ws_url).await.unwrap(); - assert_eq!("400 Bad Request", resp.status().to_string()); - child.kill().unwrap(); - child.wait().unwrap(); -} - -#[tokio::test] -#[ignore] // https://github.com/denoland/deno/issues/13491 -async fn inspector_break_on_first_line_in_test() { - let script = util::testdata_path().join("inspector/inspector_test.js"); - let mut child = util::deno_cmd() - .arg("test") - .arg(inspect_flag_with_unique_port("--inspect-brk")) - .arg(script) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - - let (socket, response) = - tokio_tungstenite::connect_async(ws_url).await.unwrap(); - assert_eq!(response.status(), 101); // Switching protocols. - - let (mut socket_tx, socket_rx) = socket.split(); - let mut socket_rx = socket_rx - .map(|msg| msg.unwrap().to_string()) - .filter(|msg| { - let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#); - futures::future::ready(pass) - }) - .boxed_local(); - - let stdout = child.stdout.as_mut().unwrap(); - let mut stdout_lines = - std::io::BufReader::new(stdout).lines().map(|r| r.unwrap()); - - assert_stderr_for_inspect_brk(&mut stderr_lines); - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":1,"method":"Runtime.enable"}"#, - r#"{"id":2,"method":"Debugger.enable"}"#, - ], - &mut socket_rx, - &[ - r#"{"id":1,"result":{}}"#, - r#"{"id":2,"result":{"debuggerId":"#, - ], - &[ - r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, - ], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#], - &mut socket_rx, - &[r#"{"id":3,"result":{}}"#], - &[r#"{"method":"Debugger.paused","#], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":4,"method":"Runtime.evaluate","params":{"expression":"Deno.core.print(\"hello from the inspector\\n\")","contextId":1,"includeCommandLineAPI":true,"silent":false,"returnByValue":true}}"#, - ], - &mut socket_rx, - &[r#"{"id":4,"result":{"result":{"type":"undefined"}}}"#], - &[], - ) - .await; - - assert_eq!(&stdout_lines.next().unwrap(), "hello from the inspector"); - - assert_inspector_messages( - &mut socket_tx, - &[r#"{"id":5,"method":"Debugger.resume"}"#], - &mut socket_rx, - &[r#"{"id":5,"result":{}}"#], - &[], - ) - .await; - - assert_starts_with!(&stdout_lines.next().unwrap(), "running 1 test from"); - assert!(&stdout_lines - .next() - .unwrap() - .contains("test has finished running")); - - child.kill().unwrap(); - child.wait().unwrap(); -} - -#[tokio::test] -async fn inspector_with_ts_files() { - let script = util::testdata_path().join("inspector/test.ts"); - let mut child = util::deno_cmd() - .arg("run") - .arg("--check") - .arg(inspect_flag_with_unique_port("--inspect-brk")) - .arg(script) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - - let (socket, response) = - tokio_tungstenite::connect_async(ws_url).await.unwrap(); - assert_eq!(response.status(), 101); // Switching protocols. - - let (mut socket_tx, socket_rx) = socket.split(); - let mut socket_rx = socket_rx - .map(|msg| msg.unwrap().to_string()) - .filter(|msg| { - let pass = (msg.starts_with(r#"{"method":"Debugger.scriptParsed","#) - && msg.contains("testdata/inspector")) - || !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#); - futures::future::ready(pass) - }) - .boxed_local(); - - let stdout = child.stdout.as_mut().unwrap(); - let mut stdout_lines = - std::io::BufReader::new(stdout).lines().map(|r| r.unwrap()); - - assert_stderr_for_inspect_brk(&mut stderr_lines); - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":1,"method":"Runtime.enable"}"#, - r#"{"id":2,"method":"Debugger.enable"}"#, - ], - &mut socket_rx, - &[ - r#"{"id":1,"result":{}}"#, - ], - &[ - r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, - ], - ) - .await; - - // receive messages with sources from this test - let script1 = socket_rx.next().await.unwrap(); - assert!(script1.contains("testdata/inspector/test.ts")); - let script1_id = { - let v: serde_json::Value = serde_json::from_str(&script1).unwrap(); - v["params"]["scriptId"].as_str().unwrap().to_string() - }; - let script2 = socket_rx.next().await.unwrap(); - assert!(script2.contains("testdata/inspector/foo.ts")); - let script2_id = { - let v: serde_json::Value = serde_json::from_str(&script2).unwrap(); - v["params"]["scriptId"].as_str().unwrap().to_string() - }; - let script3 = socket_rx.next().await.unwrap(); - assert!(script3.contains("testdata/inspector/bar.js")); - let script3_id = { - let v: serde_json::Value = serde_json::from_str(&script3).unwrap(); - v["params"]["scriptId"].as_str().unwrap().to_string() - }; - - assert_inspector_messages( - &mut socket_tx, - &[], - &mut socket_rx, - &[r#"{"id":2,"result":{"debuggerId":"#], - &[], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#], - &mut socket_rx, - &[r#"{"id":3,"result":{}}"#], - &[r#"{"method":"Debugger.paused","#], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[ - &format!(r#"{{"id":4,"method":"Debugger.getScriptSource","params":{{"scriptId":"{}"}}}}"#, script1_id), - &format!(r#"{{"id":5,"method":"Debugger.getScriptSource","params":{{"scriptId":"{}"}}}}"#, script2_id), - &format!(r#"{{"id":6,"method":"Debugger.getScriptSource","params":{{"scriptId":"{}"}}}}"#, script3_id), - ], - &mut socket_rx, - &[ - r#"{"id":4,"result":{"scriptSource":"import { foo } from \"./foo.ts\";\nimport { bar } from \"./bar.js\";\nconsole.log(foo());\nconsole.log(bar());\n//# sourceMappingURL=data:application/json;base64,"#, - r#"{"id":5,"result":{"scriptSource":"class Foo {\n hello() {\n return \"hello\";\n }\n}\nexport function foo() {\n const f = new Foo();\n return f.hello();\n}\n//# sourceMappingURL=data:application/json;base64,"#, - r#"{"id":6,"result":{"scriptSource":"export function bar() {\n return \"world\";\n}\n"#, - ], - &[], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[r#"{"id":7,"method":"Debugger.resume"}"#], - &mut socket_rx, - &[r#"{"id":7,"result":{}}"#], - &[], - ) - .await; - - assert_eq!(&stdout_lines.next().unwrap(), "hello"); - assert_eq!(&stdout_lines.next().unwrap(), "world"); - - child.kill().unwrap(); - child.wait().unwrap(); -} - -#[tokio::test] -async fn inspector_memory() { - let script = util::testdata_path().join("inspector/memory.js"); - let mut child = util::deno_cmd() - .arg("run") - .arg(inspect_flag_with_unique_port("--inspect-brk")) - .arg(script) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - - let (socket, response) = - tokio_tungstenite::connect_async(ws_url).await.unwrap(); - assert_eq!(response.status(), 101); // Switching protocols. - - let (mut socket_tx, socket_rx) = socket.split(); - let mut socket_rx = socket_rx - .map(|msg| msg.unwrap().to_string()) - .filter(|msg| { - let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#); - futures::future::ready(pass) - }) - .boxed_local(); - - assert_stderr_for_inspect_brk(&mut stderr_lines); - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":1,"method":"Runtime.enable"}"#, - r#"{"id":2,"method":"Debugger.enable"}"#, - - ], - &mut socket_rx, - &[ - r#"{"id":1,"result":{}}"#, - r#"{"id":2,"result":{"debuggerId":"#, - ], - &[ - r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, - ], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#, - r#"{"id":4,"method":"HeapProfiler.enable"}"#, - ], - &mut socket_rx, - &[r#"{"id":3,"result":{}}"#, r#"{"id":4,"result":{}}"#], - &[r#"{"method":"Debugger.paused","#], - ) - .await; - - socket_tx - .send( - r#"{"id":5,"method":"Runtime.getHeapUsage", "params": {}}"# - .to_string() - .into(), - ) - .await - .unwrap(); - let msg = socket_rx.next().await.unwrap(); - let json_msg: serde_json::Value = serde_json::from_str(&msg).unwrap(); - assert_eq!(json_msg["id"].as_i64().unwrap(), 5); - let result = &json_msg["result"]; - assert!( - result["usedSize"].as_i64().unwrap() - <= result["totalSize"].as_i64().unwrap() - ); - - socket_tx.send( - r#"{"id":6,"method":"HeapProfiler.takeHeapSnapshot","params": {"reportProgress": true, "treatGlobalObjectsAsRoots": true, "captureNumberValue": false}}"# - .to_string().into() - ).await.unwrap(); - - let mut progress_report_completed = false; - loop { - let msg = socket_rx.next().await.unwrap(); - - if !progress_report_completed - && msg.starts_with( - r#"{"method":"HeapProfiler.reportHeapSnapshotProgress","params""#, - ) - { - let json_msg: serde_json::Value = serde_json::from_str(&msg).unwrap(); - if let Some(finished) = json_msg["params"].get("finished") { - progress_report_completed = finished.as_bool().unwrap(); - } - continue; - } - - if msg.starts_with(r#"{"method":"HeapProfiler.reportHeapSnapshotProgress","params":{"done":"#,) { - continue; - } - - if msg.starts_with(r#"{"id":6,"result":{}}"#) { - assert!(progress_report_completed); - break; - } - } - - child.kill().unwrap(); - child.wait().unwrap(); -} - -#[tokio::test] -async fn inspector_profile() { - let script = util::testdata_path().join("inspector/memory.js"); - let mut child = util::deno_cmd() - .arg("run") - .arg(inspect_flag_with_unique_port("--inspect-brk")) - .arg(script) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stderr = child.stderr.as_mut().unwrap(); - let mut stderr_lines = - std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); - let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); - - let (socket, response) = - tokio_tungstenite::connect_async(ws_url).await.unwrap(); - assert_eq!(response.status(), 101); // Switching protocols. - - let (mut socket_tx, socket_rx) = socket.split(); - let mut socket_rx = socket_rx - .map(|msg| msg.unwrap().to_string()) - .filter(|msg| { - let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#); - futures::future::ready(pass) - }) - .boxed_local(); - - assert_stderr_for_inspect_brk(&mut stderr_lines); - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":1,"method":"Runtime.enable"}"#, - r#"{"id":2,"method":"Debugger.enable"}"#, - - ], - &mut socket_rx, - &[ - r#"{"id":1,"result":{}}"#, - r#"{"id":2,"result":{"debuggerId":"#, - ], - &[ - r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, - ], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#, - r#"{"id":4,"method":"Profiler.enable"}"#, - ], - &mut socket_rx, - &[r#"{"id":3,"result":{}}"#, r#"{"id":4,"result":{}}"#], - &[r#"{"method":"Debugger.paused","#], - ) - .await; - - assert_inspector_messages( - &mut socket_tx, - &[ - r#"{"id":5,"method":"Profiler.setSamplingInterval","params":{"interval": 100}}"#, - r#"{"id":6,"method":"Profiler.start","params":{}}"#, - ], - &mut socket_rx, - &[r#"{"id":5,"result":{}}"#, r#"{"id":6,"result":{}}"#], - &[], - ) - .await; - - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; - - socket_tx - .send( - r#"{"id":7,"method":"Profiler.stop", "params": {}}"#.to_string().into(), - ) - .await - .unwrap(); - let msg = socket_rx.next().await.unwrap(); - let json_msg: serde_json::Value = serde_json::from_str(&msg).unwrap(); - assert_eq!(json_msg["id"].as_i64().unwrap(), 7); - let result = &json_msg["result"]; - let profile = &result["profile"]; - assert!( - profile["startTime"].as_i64().unwrap() - < profile["endTime"].as_i64().unwrap() - ); - profile["samples"].as_array().unwrap(); - profile["nodes"].as_array().unwrap(); - - child.kill().unwrap(); - child.wait().unwrap(); -} diff --git a/cli/tests/integration/install_tests.rs b/cli/tests/integration/install_tests.rs deleted file mode 100644 index 2db32bd285..0000000000 --- a/cli/tests/integration/install_tests.rs +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use std::fs; -use std::process::Command; -use test_util as util; -use test_util::assert_contains; -use test_util::assert_ends_with; -use test_util::TempDir; - -#[test] -fn install_basic() { - let _guard = util::http_server(); - let temp_dir = TempDir::new(); - let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); - - let status = util::deno_cmd() - .current_dir(temp_dir.path()) - .arg("install") - .arg("--check") - .arg("--name") - .arg("echo_test") - .arg("http://localhost:4545/echo.ts") - .envs([ - ("HOME", temp_dir_str.as_str()), - ("USERPROFILE", temp_dir_str.as_str()), - ("DENO_INSTALL_ROOT", ""), - ]) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - - let mut file_path = temp_dir.path().join(".deno/bin/echo_test"); - assert!(file_path.exists()); - - if cfg!(windows) { - file_path = file_path.with_extension("cmd"); - } - - let content = fs::read_to_string(file_path).unwrap(); - // ensure there's a trailing newline so the shell script can be - // more versatile. - assert_eq!(content.chars().last().unwrap(), '\n'); - - if cfg!(windows) { - assert_contains!( - content, - r#""run" "--check" "http://localhost:4545/echo.ts""# - ); - } else { - assert_contains!(content, r#"run --check 'http://localhost:4545/echo.ts'"#); - } -} - -#[test] -fn install_custom_dir_env_var() { - let _guard = util::http_server(); - let temp_dir = TempDir::new(); - let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); - - let status = util::deno_cmd() - .current_dir(util::root_path()) // different cwd - .arg("install") - .arg("--check") - .arg("--name") - .arg("echo_test") - .arg("http://localhost:4545/echo.ts") - .envs([ - ("HOME", temp_dir_str.as_str()), - ("USERPROFILE", temp_dir_str.as_str()), - ("DENO_INSTALL_ROOT", temp_dir_str.as_str()), - ]) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - - let mut file_path = temp_dir.path().join("bin/echo_test"); - assert!(file_path.exists()); - - if cfg!(windows) { - file_path = file_path.with_extension("cmd"); - } - - let content = fs::read_to_string(file_path).unwrap(); - if cfg!(windows) { - assert_contains!( - content, - r#""run" "--check" "http://localhost:4545/echo.ts""# - ); - } else { - assert_contains!(content, r#"run --check 'http://localhost:4545/echo.ts'"#); - } -} - -#[test] -fn installer_test_local_module_run() { - let temp_dir = TempDir::new(); - let bin_dir = temp_dir.path().join("bin"); - std::fs::create_dir(&bin_dir).unwrap(); - let status = util::deno_cmd() - .current_dir(util::root_path()) - .arg("install") - .arg("--name") - .arg("echo_test") - .arg("--root") - .arg(temp_dir.path()) - .arg(util::testdata_path().join("echo.ts")) - .arg("hello") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - let mut file_path = bin_dir.join("echo_test"); - if cfg!(windows) { - file_path = file_path.with_extension("cmd"); - } - assert!(file_path.exists()); - // NOTE: using file_path here instead of exec_name, because tests - // shouldn't mess with user's PATH env variable - let output = Command::new(file_path) - .current_dir(temp_dir.path()) - .arg("foo") - .env("PATH", util::target_dir()) - .output() - .unwrap(); - let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); - assert_ends_with!(stdout_str, "hello, foo"); -} - -#[test] -fn installer_test_remote_module_run() { - let _g = util::http_server(); - let temp_dir = TempDir::new(); - let bin_dir = temp_dir.path().join("bin"); - std::fs::create_dir(&bin_dir).unwrap(); - let status = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("install") - .arg("--name") - .arg("echo_test") - .arg("--root") - .arg(temp_dir.path()) - .arg("http://localhost:4545/echo.ts") - .arg("hello") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - let mut file_path = bin_dir.join("echo_test"); - if cfg!(windows) { - file_path = file_path.with_extension("cmd"); - } - assert!(file_path.exists()); - let output = Command::new(file_path) - .current_dir(temp_dir.path()) - .arg("foo") - .env("PATH", util::target_dir()) - .output() - .unwrap(); - assert_ends_with!( - std::str::from_utf8(&output.stdout).unwrap().trim(), - "hello, foo", - ); -} - -#[test] -fn check_local_by_default() { - let _guard = util::http_server(); - let temp_dir = TempDir::new(); - let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); - - let status = util::deno_cmd() - .current_dir(temp_dir.path()) - .arg("install") - .arg(util::testdata_path().join("./install/check_local_by_default.ts")) - .envs([ - ("HOME", temp_dir_str.as_str()), - ("USERPROFILE", temp_dir_str.as_str()), - ("DENO_INSTALL_ROOT", ""), - ]) - .status() - .unwrap(); - assert!(status.success()); -} - -#[test] -fn check_local_by_default2() { - let _guard = util::http_server(); - let temp_dir = TempDir::new(); - let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); - - let status = util::deno_cmd() - .current_dir(temp_dir.path()) - .arg("install") - .arg(util::testdata_path().join("./install/check_local_by_default2.ts")) - .envs([ - ("HOME", temp_dir_str.as_str()), - ("NO_COLOR", "1"), - ("USERPROFILE", temp_dir_str.as_str()), - ("DENO_INSTALL_ROOT", ""), - ]) - .status() - .unwrap(); - assert!(status.success()); -} diff --git a/cli/tests/integration/lint_tests.rs b/cli/tests/integration/lint_tests.rs deleted file mode 100644 index 70a3cbbd47..0000000000 --- a/cli/tests/integration/lint_tests.rs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use crate::itest; -use test_util as util; - -#[test] -fn ignore_unexplicit_files() { - let output = util::deno_cmd() - .current_dir(util::root_path()) - .env("NO_COLOR", "1") - .arg("lint") - .arg("--unstable") - .arg("--ignore=./") - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - assert_eq!( - String::from_utf8_lossy(&output.stderr), - "error: No target files found.\n" - ); -} - -itest!(all { - args: "lint lint/without_config/file1.js lint/without_config/file2.ts lint/without_config/ignored_file.ts", - output: "lint/expected.out", - exit_code: 1, -}); - -itest!(quiet { - args: "lint --quiet lint/without_config/file1.js", - output: "lint/expected_quiet.out", - exit_code: 1, -}); - -itest!(json { - args: - "lint --json lint/without_config/file1.js lint/without_config/file2.ts lint/without_config/ignored_file.ts lint/without_config/malformed.js", - output: "lint/expected_json.out", - exit_code: 1, -}); - -itest!(compact { - args: - "lint --compact lint/without_config/file1.js lint/without_config/ignored_file.tss", - output: "lint/expected_compact.out", - exit_code: 1, -}); - -itest!(ignore { - args: - "lint --ignore=lint/without_config/file1.js,lint/without_config/malformed.js,lint/without_config/lint_with_config/ lint/without_config/", - output: "lint/expected_ignore.out", - exit_code: 1, -}); - -itest!(glob { - args: "lint --ignore=lint/without_config/malformed.js,lint/with_config/ lint/without_config/", - output: "lint/expected_glob.out", - exit_code: 1, -}); - -itest!(stdin { - args: "lint -", - input: Some("let _a: any;"), - output: "lint/expected_from_stdin.out", - exit_code: 1, -}); - -itest!(stdin_json { - args: "lint --json -", - input: Some("let _a: any;"), - output: "lint/expected_from_stdin_json.out", - exit_code: 1, -}); - -itest!(rules { - args: "lint --rules", - output: "lint/expected_rules.out", - exit_code: 0, -}); - -// Make sure that the rules are printed if quiet option is enabled. -itest!(rules_quiet { - args: "lint --rules -q", - output: "lint/expected_rules.out", - exit_code: 0, -}); - -itest!(lint_with_config { - args: "lint --config lint/Deno.jsonc lint/with_config/", - output: "lint/with_config.out", - exit_code: 1, -}); - -itest!(lint_with_report_config { - args: "lint --config lint/Deno.compact.format.jsonc lint/with_config/", - output: "lint/with_report_config_compact.out", - exit_code: 1, -}); - -// Check if CLI flags take precedence -itest!(lint_with_report_config_override { - args: "lint --config lint/Deno.compact.format.jsonc lint/with_config/ --json", - output: "lint/with_report_config_override.out", - exit_code: 1, -}); - -itest!(lint_with_config_and_flags { - args: "lint --config lint/Deno.jsonc --ignore=lint/with_config/a.ts", - output: "lint/with_config_and_flags.out", - exit_code: 1, -}); - -itest!(lint_with_config_without_tags { - args: "lint --config lint/Deno.no_tags.jsonc lint/with_config/", - output: "lint/with_config_without_tags.out", - exit_code: 1, -}); - -itest!(lint_with_malformed_config { - args: "lint --config lint/Deno.malformed.jsonc", - output: "lint/with_malformed_config.out", - exit_code: 1, -}); - -itest!(lint_with_malformed_config2 { - args: "lint --config lint/Deno.malformed2.jsonc", - output: "lint/with_malformed_config2.out", - exit_code: 1, -}); diff --git a/cli/tests/integration/lsp_tests.rs b/cli/tests/integration/lsp_tests.rs deleted file mode 100644 index f123f71a37..0000000000 --- a/cli/tests/integration/lsp_tests.rs +++ /dev/null @@ -1,6265 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use deno_ast::ModuleSpecifier; -use deno_core::serde::de::DeserializeOwned; -use deno_core::serde::Deserialize; -use deno_core::serde::Serialize; -use deno_core::serde_json; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; -use deno_core::url::Url; -use pretty_assertions::assert_eq; -use std::collections::HashSet; -use std::fs; -use test_util::deno_exe_path; -use test_util::http_server; -use test_util::lsp::LspClient; -use test_util::testdata_path; -use test_util::TempDir; -use tower_lsp::lsp_types as lsp; - -fn load_fixture(path: &str) -> Value { - load_fixture_as(path) -} - -fn load_fixture_as(path: &str) -> T -where - T: DeserializeOwned, -{ - let fixture_str = load_fixture_str(path); - serde_json::from_str::(&fixture_str).unwrap() -} - -fn load_fixture_str(path: &str) -> String { - let fixtures_path = testdata_path().join("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, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", load_fixture(init_path)) - .unwrap(); - client.write_notification("initialized", json!({})).unwrap(); - client -} - -fn did_open( - client: &mut LspClient, - params: V, -) -> Vec -where - V: Serialize, -{ - client - .write_notification("textDocument/didOpen", params) - .unwrap(); - - handle_configuration_request( - client, - json!([{ - "enable": true, - "codeLens": { - "test": true - } - }]), - ); - read_diagnostics(client).0 -} - -fn handle_configuration_request(client: &mut LspClient, result: Value) { - let (id, method, _) = client.read_request::().unwrap(); - assert_eq!(method, "workspace/configuration"); - client.write_response(id, result).unwrap(); -} - -fn read_diagnostics(client: &mut LspClient) -> CollectedDiagnostics { - // diagnostics come in batches of three unless they're cancelled - let mut diagnostics = vec![]; - for _ in 0..3 { - let (method, response) = client - .read_notification::() - .unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - diagnostics.push(response.unwrap()); - } - CollectedDiagnostics(diagnostics) -} - -fn shutdown(client: &mut LspClient) { - client - .write_request::<_, _, Value>("shutdown", json!(null)) - .unwrap(); - client.write_notification("exit", json!(null)).unwrap(); -} - -pub fn ensure_directory_specifier( - mut specifier: ModuleSpecifier, -) -> ModuleSpecifier { - let path = specifier.path(); - if !path.ends_with('/') { - let new_path = format!("{}/", path); - specifier.set_path(&new_path); - } - specifier -} - -struct TestSession { - client: LspClient, - open_file_count: usize, -} - -impl TestSession { - pub fn from_file(init_path: &str) -> Self { - Self::from_client(init(init_path)) - } - - pub fn from_client(client: LspClient) -> Self { - Self { - client, - open_file_count: 0, - } - } - - pub fn did_open(&mut self, params: V) -> CollectedDiagnostics - where - V: Serialize, - { - self - .client - .write_notification("textDocument/didOpen", params) - .unwrap(); - - let (id, method, _) = self.client.read_request::().unwrap(); - assert_eq!(method, "workspace/configuration"); - self - .client - .write_response( - id, - json!([{ - "enable": true, - "codeLens": { - "test": true - } - }]), - ) - .unwrap(); - - self.open_file_count += 1; - self.read_diagnostics() - } - - pub fn read_diagnostics(&mut self) -> CollectedDiagnostics { - let mut all_diagnostics = Vec::new(); - for _ in 0..self.open_file_count { - all_diagnostics.extend(read_diagnostics(&mut self.client).0); - } - CollectedDiagnostics(all_diagnostics) - } - - pub fn shutdown_and_exit(&mut self) { - shutdown(&mut self.client); - } -} - -#[derive(Debug, Clone)] -struct CollectedDiagnostics(Vec); - -impl CollectedDiagnostics { - /// Gets the diagnostics that the editor will see after all the publishes. - pub fn viewed(&self) -> Vec { - self - .viewed_messages() - .into_iter() - .flat_map(|m| m.diagnostics) - .collect() - } - - /// Gets the messages that the editor will see after all the publishes. - pub fn viewed_messages(&self) -> Vec { - // go over the publishes in reverse order in order to get - // the final messages that will be shown in the editor - let mut messages = Vec::new(); - let mut had_specifier = HashSet::new(); - for message in self.0.iter().rev() { - if had_specifier.insert(message.uri.clone()) { - messages.insert(0, message.clone()); - } - } - messages - } - - pub fn with_source(&self, source: &str) -> lsp::PublishDiagnosticsParams { - self - .viewed_messages() - .iter() - .find(|p| { - p.diagnostics - .iter() - .any(|d| d.source == Some(source.to_string())) - }) - .map(ToOwned::to_owned) - .unwrap() - } - - pub fn with_file_and_source( - &self, - specifier: &str, - source: &str, - ) -> lsp::PublishDiagnosticsParams { - let specifier = ModuleSpecifier::parse(specifier).unwrap(); - self - .viewed_messages() - .iter() - .find(|p| { - p.uri == specifier - && p - .diagnostics - .iter() - .any(|d| d.source == Some(source.to_string())) - }) - .map(ToOwned::to_owned) - .unwrap() - } -} - -#[test] -fn lsp_startup_shutdown() { - let mut client = init("initialize_params.json"); - shutdown(&mut client); -} - -#[test] -fn lsp_init_tsconfig() { - let temp_dir = TempDir::new(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); - let tsconfig = - serde_json::to_vec_pretty(&load_fixture("lib.tsconfig.json")).unwrap(); - fs::write(temp_dir.path().join("lib.tsconfig.json"), tsconfig).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!("./lib.tsconfig.json")); - params.initialization_options = Some(Value::Object(map)); - } - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - - client.write_notification("initialized", json!({})).unwrap(); - - let diagnostics = did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "location.pathname;\n" - } - }), - ); - - let diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics); - assert_eq!(diagnostics.count(), 0); - - 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(); - 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, false).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_tsconfig_bad_config_path() { - let mut client = init("initialize_params_bad_config_option.json"); - let (method, maybe_params) = client.read_notification().unwrap(); - assert_eq!(method, "window/showMessage"); - assert_eq!(maybe_params, Some(lsp::ShowMessageParams { - typ: lsp::MessageType::WARNING, - message: "The path to the configuration file (\"bad_tsconfig.json\") is not resolvable.".to_string() - })); - let diagnostics = did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "console.log(Deno.args);\n" - } - }), - ); - let diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics); - assert_eq!(diagnostics.count(), 0); -} - -#[test] -fn lsp_triple_slash_types() { - let temp_dir = TempDir::new(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).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()); - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).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": "/// \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_import_map() { - let temp_dir = TempDir::new(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); - let import_map = - serde_json::to_vec_pretty(&load_fixture("import-map.json")).unwrap(); - fs::write(temp_dir.path().join("import-map.json"), import_map).unwrap(); - fs::create_dir(temp_dir.path().join("lib")).unwrap(); - fs::write( - temp_dir.path().join("lib").join("b.ts"), - r#"export const b = "b";"#, - ) - .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("importMap".to_string(), json!("import-map.json")); - params.initialization_options = Some(Value::Object(map)); - } - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - - client.write_notification("initialized", json!({})).unwrap(); - let uri = Url::from_file_path(temp_dir.path().join("a.ts")).unwrap(); - - let diagnostics = did_open( - &mut client, - json!({ - "textDocument": { - "uri": uri, - "languageId": "typescript", - "version": 1, - "text": "import { b } from \"/~/b.ts\";\n\nconsole.log(b);\n" - } - }), - ); - - let diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics); - assert_eq!(diagnostics.count(), 0); - - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": uri - }, - "position": { - "line": 2, - "character": 12 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value":"(alias) const b: \"b\"\nimport b" - }, - "" - ], - "range": { - "start": { - "line": 2, - "character": 12 - }, - "end": { - "line": 2, - "character": 13 - } - } - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_import_map_data_url() { - let mut client = init("initialize_params_import_map.json"); - let diagnostics = did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "import example from \"example\";\n" - } - }), - ); - - let mut diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics); - // This indicates that the import map from initialize_params_import_map.json - // is applied correctly. - assert!(diagnostics.any(|diagnostic| diagnostic.code - == Some(lsp::NumberOrString::String("no-cache".to_string())) - && diagnostic - .message - .contains("https://deno.land/x/example/mod.ts"))); - shutdown(&mut client); -} - -#[test] -fn lsp_import_map_config_file() { - let temp_dir = TempDir::new(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); - - let deno_import_map_jsonc = - serde_json::to_vec_pretty(&load_fixture("deno.import_map.jsonc")).unwrap(); - fs::write( - temp_dir.path().join("deno.import_map.jsonc"), - deno_import_map_jsonc, - ) - .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!("./deno.import_map.jsonc")); - params.initialization_options = Some(Value::Object(map)); - } - let import_map = - serde_json::to_vec_pretty(&load_fixture("import-map.json")).unwrap(); - fs::write(temp_dir.path().join("import-map.json"), import_map).unwrap(); - fs::create_dir(temp_dir.path().join("lib")).unwrap(); - fs::write( - temp_dir.path().join("lib").join("b.ts"), - r#"export const b = "b";"#, - ) - .unwrap(); - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - - client.write_notification("initialized", json!({})).unwrap(); - let uri = Url::from_file_path(temp_dir.path().join("a.ts")).unwrap(); - - let diagnostics = did_open( - &mut client, - json!({ - "textDocument": { - "uri": uri, - "languageId": "typescript", - "version": 1, - "text": "import { b } from \"/~/b.ts\";\n\nconsole.log(b);\n" - } - }), - ); - - let diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics); - assert_eq!(diagnostics.count(), 0); - - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": uri - }, - "position": { - "line": 2, - "character": 12 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value":"(alias) const b: \"b\"\nimport b" - }, - "" - ], - "range": { - "start": { - "line": 2, - "character": 12 - }, - "end": { - "line": 2, - "character": 13 - } - } - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_deno_task() { - let temp_dir = TempDir::new(); - let workspace_root = temp_dir.path().canonicalize().unwrap(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); - fs::write( - workspace_root.join("deno.jsonc"), - r#"{ - "tasks": { - "build": "deno test", - "some:test": "deno bundle mod.ts" - } - }"#, - ) - .unwrap(); - - params.root_uri = Some(Url::from_file_path(workspace_root).unwrap()); - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>("deno/task", json!(null)) - .unwrap(); - - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!([ - { - "name": "build", - "detail": "deno test" - }, - { - "name": "some:test", - "detail": "deno bundle mod.ts" - } - ])) - ); -} - -#[test] -fn lsp_import_assertions() { - let mut client = init("initialize_params_import_map.json"); - client - .write_notification( - "textDocument/didOpen", - json!({ - "textDocument": { - "uri": "file:///a/test.json", - "languageId": "json", - "version": 1, - "text": "{\"a\":1}" - } - }), - ) - .unwrap(); - handle_configuration_request( - &mut client, - json!([{ - "enable": true, - "codeLens": { - "test": true - } - }]), - ); - - let diagnostics = CollectedDiagnostics(did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/a.ts", - "languageId": "typescript", - "version": 1, - "text": "import a from \"./test.json\";\n\nconsole.log(a);\n" - } - }), - )); - - assert_eq!( - json!( - diagnostics - .with_file_and_source("file:///a/a.ts", "deno") - .diagnostics - ), - json!([ - { - "range": { - "start": { - "line": 0, - "character": 14 - }, - "end": { - "line": 0, - "character": 27 - } - }, - "severity": 1, - "code": "no-assert-type", - "source": "deno", - "message": "The module is a JSON module and not being imported with an import assertion. Consider adding `assert { type: \"json\" }` to the import statement." - } - ]) - ); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeAction", - load_fixture("code_action_params_import_assertion.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_action_response_import_assertion.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_import_map_import_completions() { - let temp_dir = TempDir::new(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); - let import_map = - serde_json::to_vec_pretty(&load_fixture("import-map-completions.json")) - .unwrap(); - fs::write(temp_dir.path().join("import-map.json"), import_map).unwrap(); - fs::create_dir(temp_dir.path().join("lib")).unwrap(); - fs::write( - temp_dir.path().join("lib").join("b.ts"), - r#"export const b = "b";"#, - ) - .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("importMap".to_string(), json!("import-map.json")); - params.initialization_options = Some(Value::Object(map)); - } - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - - client.write_notification("initialized", json!({})).unwrap(); - let uri = Url::from_file_path(temp_dir.path().join("a.ts")).unwrap(); - - did_open( - &mut client, - json!({ - "textDocument": { - "uri": uri, - "languageId": "typescript", - "version": 1, - "text": "import * as a from \"/~/b.ts\";\nimport * as b from \"\"" - } - }), - ); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/completion", - json!({ - "textDocument": { - "uri": uri - }, - "position": { - "line": 1, - "character": 20 - }, - "context": { - "triggerKind": 2, - "triggerCharacter": "\"" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "isIncomplete": false, - "items": [ - { - "label": ".", - "kind": 19, - "detail": "(local)", - "sortText": "1", - "insertText": ".", - "commitCharacters": ["\"", "'"], - }, - { - "label": "..", - "kind": 19, - "detail": "(local)", - "sortText": "1", - "insertText": "..", - "commitCharacters": ["\"", "'"], - }, - { - "label": "std", - "kind": 19, - "detail": "(import map)", - "sortText": "std", - "insertText": "std", - "commitCharacters": ["\"", "'"], - }, - { - "label": "fs", - "kind": 17, - "detail": "(import map)", - "sortText": "fs", - "insertText": "fs", - "commitCharacters": ["\"", "'"], - }, - { - "label": "/~", - "kind": 19, - "detail": "(import map)", - "sortText": "/~", - "insertText": "/~", - "commitCharacters": ["\"", "'"], - } - ] - })) - ); - - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": uri, - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 1, - "character": 20 - }, - "end": { - "line": 1, - "character": 20 - } - }, - "text": "/~/" - } - ] - }), - ) - .unwrap(); - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/completion", - json!({ - "textDocument": { - "uri": uri - }, - "position": { - "line": 1, - "character": 23 - }, - "context": { - "triggerKind": 2, - "triggerCharacter": "/" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "isIncomplete": false, - "items": [ - { - "label": "b.ts", - "kind": 9, - "detail": "(import map)", - "sortText": "1", - "filterText": "/~/b.ts", - "textEdit": { - "range": { - "start": { - "line": 1, - "character": 20 - }, - "end": { - "line": 1, - "character": 23 - } - }, - "newText": "/~/b.ts" - }, - "commitCharacters": ["\"", "'"], - } - ] - })) - ); - - shutdown(&mut client); -} - -#[test] -fn lsp_hover() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "console.log(Deno.args);\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 19 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value": "const Deno.args: string[]" - }, - "Returns the script arguments to the program.\n\nGive the following command line invocation of Deno:\n\n```sh\ndeno run --allow-read https://deno.land/std/examples/cat.ts /etc/passwd\n```\n\nThen `Deno.args` will contain:\n\n```\n[ \"/etc/passwd\" ]\n```\n\nIf you are looking for a structured way to parse arguments, there is the\n[`std/flags`](https://deno.land/std/flags) module as part of the Deno\nstandard library.", - "\n\n*@category* - Runtime Environment", - ], - "range": { - "start": { - "line": 0, - "character": 17 - }, - "end": { - "line": 0, - "character": 21 - } - } - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_hover_asset() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "console.log(Date.now());\n" - } - }), - ); - let (_, maybe_error) = client - .write_request::<_, _, Value>( - "textDocument/definition", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 14 - } - }), - ) - .unwrap(); - assert!(maybe_error.is_none()); - let (_, maybe_error) = client - .write_request::<_, _, Value>( - "deno/virtualTextDocument", - json!({ - "textDocument": { - "uri": "deno:/asset/lib.deno.shared_globals.d.ts" - } - }), - ) - .unwrap(); - assert!(maybe_error.is_none()); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "deno:/asset/lib.es2015.symbol.wellknown.d.ts" - }, - "position": { - "line": 109, - "character": 13 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value": "interface Date", - }, - "Enables basic storage and retrieval of dates and times." - ], - "range": { - "start": { - "line": 109, - "character": 10, - }, - "end": { - "line": 109, - "character": 14, - } - } - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_hover_disabled() { - let mut client = init("initialize_params_disabled.json"); - client - .write_notification( - "textDocument/didOpen", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "console.log(Date.now());\n" - } - }), - ) - .unwrap(); - - handle_configuration_request(&mut client, json!([{ "enable": false }])); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 19 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!(null))); - shutdown(&mut client); -} - -#[test] -fn lsp_inlay_hints() { - let mut client = init("initialize_params_hints.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": r#"function a(b: string) { - return b; - } - - a("foo"); - - enum C { - A, - } - - parseInt("123", 8); - - const d = Date.now(); - - class E { - f = Date.now(); - } - - ["a"].map((v) => v + v); - "# - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/inlayHint", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "range": { - "start": { - "line": 0, - "character": 0 - }, - "end": { - "line": 19, - "character": 0, - } - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - json!(maybe_res), - json!([ - { - "position": { - "line": 0, - "character": 21 - }, - "label": ": string", - "kind": 1, - "paddingLeft": true - }, - { - "position": { - "line": 4, - "character": 10 - }, - "label": "b:", - "kind": 2, - "paddingRight": true - }, - { - "position": { - "line": 7, - "character": 11 - }, - "label": "= 0", - "paddingLeft": true - }, - { - "position": { - "line": 10, - "character": 17 - }, - "label": "string:", - "kind": 2, - "paddingRight": true - }, - { - "position": { - "line": 10, - "character": 24 - }, - "label": "radix:", - "kind": 2, - "paddingRight": true - }, - { - "position": { - "line": 12, - "character": 15 - }, - "label": ": number", - "kind": 1, - "paddingLeft": true - }, - { - "position": { - "line": 15, - "character": 11 - }, - "label": ": number", - "kind": 1, - "paddingLeft": true - }, - { - "position": { - "line": 18, - "character": 18 - }, - "label": "callbackfn:", - "kind": 2, - "paddingRight": true - }, - { - "position": { - "line": 18, - "character": 20 - }, - "label": ": string", - "kind": 1, - "paddingLeft": true - }, - { - "position": { - "line": 18, - "character": 21 - }, - "label": ": string", - "kind": 1, - "paddingLeft": true - } - ]) - ); -} - -#[test] -fn lsp_inlay_hints_not_enabled() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": r#"function a(b: string) { - return b; - } - - a("foo"); - - enum C { - A, - } - - parseInt("123", 8); - - const d = Date.now(); - - class E { - f = Date.now(); - } - - ["a"].map((v) => v + v); - "# - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/inlayHint", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "range": { - "start": { - "line": 0, - "character": 0 - }, - "end": { - "line": 19, - "character": 0, - } - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(json!(maybe_res), json!(null)); -} - -#[test] -fn lsp_workspace_enable_paths() { - let mut params: lsp::InitializeParams = serde_json::from_value(load_fixture( - "initialize_params_workspace_enable_paths.json", - )) - .unwrap(); - // we aren't actually writing anything to the tempdir in this test, but we - // just need a legitimate file path on the host system so that logic that - // tries to convert to and from the fs paths works on all env - let temp_dir = TempDir::new(); - - let root_specifier = - ensure_directory_specifier(Url::from_file_path(temp_dir.path()).unwrap()); - - params.root_uri = Some(root_specifier.clone()); - params.workspace_folders = Some(vec![lsp::WorkspaceFolder { - uri: root_specifier.clone(), - name: "project".to_string(), - }]); - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - - client.write_notification("initialized", json!({})).unwrap(); - - handle_configuration_request( - &mut client, - json!([{ - "enable": false, - "enablePaths": [ - "./worker" - ], - }]), - ); - - did_open( - &mut client, - json!({ - "textDocument": { - "uri": root_specifier.join("./file.ts").unwrap(), - "languageId": "typescript", - "version": 1, - "text": "console.log(Date.now());\n" - } - }), - ); - - did_open( - &mut client, - json!({ - "textDocument": { - "uri": root_specifier.join("./other/file.ts").unwrap(), - "languageId": "typescript", - "version": 1, - "text": "console.log(Date.now());\n" - } - }), - ); - - did_open( - &mut client, - json!({ - "textDocument": { - "uri": root_specifier.join("./worker/file.ts").unwrap(), - "languageId": "typescript", - "version": 1, - "text": "console.log(Date.now());\n" - } - }), - ); - - did_open( - &mut client, - json!({ - "textDocument": { - "uri": root_specifier.join("./worker/subdir/file.ts").unwrap(), - "languageId": "typescript", - "version": 1, - "text": "console.log(Date.now());\n" - } - }), - ); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": root_specifier.join("./file.ts").unwrap(), - }, - "position": { - "line": 0, - "character": 19 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!(null))); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": root_specifier.join("./other/file.ts").unwrap(), - }, - "position": { - "line": 0, - "character": 19 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!(null))); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": root_specifier.join("./worker/file.ts").unwrap(), - }, - "position": { - "line": 0, - "character": 19 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value": "(method) DateConstructor.now(): number", - }, - "" - ], - "range": { - "start": { - "line": 0, - "character": 17, - }, - "end": { - "line": 0, - "character": 20, - } - } - })) - ); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": root_specifier.join("./worker/subdir/file.ts").unwrap(), - }, - "position": { - "line": 0, - "character": 19 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value": "(method) DateConstructor.now(): number", - }, - "" - ], - "range": { - "start": { - "line": 0, - "character": 17, - }, - "end": { - "line": 0, - "character": 20, - } - } - })) - ); - - shutdown(&mut client); -} - -#[test] -fn lsp_hover_unstable_disabled() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "console.log(Deno.dlopen);\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 19 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value": "any" - } - ], - "range": { - "start": { - "line": 0, - "character": 17 - }, - "end": { - "line": 0, - "character": 23 - } - } - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_hover_unstable_enabled() { - let mut client = init("initialize_params_unstable.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "console.log(Deno.ppid);\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 19 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents":[ - { - "language":"typescript", - "value":"const Deno.ppid: number" - }, - "The process ID of parent process of this instance of the Deno CLI.\n\n```ts\nconsole.log(Deno.ppid);\n```", - "\n\n*@category* - Runtime Environment", - ], - "range":{ - "start":{ - "line":0, - "character":17 - }, - "end":{ - "line":0, - "character":21 - } - } - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_hover_change_mbc() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "const a = `编写软件很难`;\nconst b = `👍🦕😃`;\nconsole.log(a, b);\n" - } - }), - ); - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 1, - "character": 11 - }, - "end": { - "line": 1, - // the LSP uses utf16 encoded characters indexes, so - // after the deno emoiji is character index 15 - "character": 15 - } - }, - "text": "" - } - ] - }), - ) - .unwrap(); - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 2, - "character": 15 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value": "const b: \"😃\"", - }, - "", - ], - "range": { - "start": { - "line": 2, - "character": 15, - }, - "end": { - "line": 2, - "character": 16, - }, - } - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_hover_closed_document() { - let temp_dir_guard = TempDir::new(); - let temp_dir = temp_dir_guard.path(); - let a_path = temp_dir.join("a.ts"); - fs::write(a_path, r#"export const a = "a";"#).unwrap(); - let b_path = temp_dir.join("b.ts"); - fs::write(&b_path, r#"export * from "./a.ts";"#).unwrap(); - let b_specifier = Url::from_file_path(b_path).unwrap(); - let c_path = temp_dir.join("c.ts"); - fs::write(&c_path, "import { a } from \"./b.ts\";\nconsole.log(a);\n") - .unwrap(); - let c_specifier = Url::from_file_path(c_path).unwrap(); - - let mut client = init("initialize_params.json"); - client - .write_notification( - "textDocument/didOpen", - json!({ - "textDocument": { - "uri": b_specifier, - "languageId": "typescript", - "version": 1, - "text": r#"export * from "./a.ts";"# - } - }), - ) - .unwrap(); - let (id, method, _) = client.read_request::().unwrap(); - assert_eq!(method, "workspace/configuration"); - client - .write_response(id, json!([{ "enable": true }])) - .unwrap(); - - client - .write_notification( - "textDocument/didOpen", - json!({ - "textDocument": { - "uri": c_specifier, - "languageId": "typescript", - "version": 1, - "text": "import { a } from \"./b.ts\";\nconsole.log(a);\n", - } - }), - ) - .unwrap(); - let (id, method, _) = client.read_request::().unwrap(); - assert_eq!(method, "workspace/configuration"); - client - .write_response(id, json!([{ "enable": true }])) - .unwrap(); - - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": c_specifier, - }, - "position": { - "line": 0, - "character": 10 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value": "(alias) const a: \"a\"\nimport a" - }, - "" - ], - "range": { - "start": { - "line": 0, - "character": 9 - }, - "end": { - "line": 0, - "character": 10 - } - } - })) - ); - client - .write_notification( - "textDocument/didClose", - json!({ - "textDocument": { - "uri": b_specifier, - } - }), - ) - .unwrap(); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": c_specifier, - }, - "position": { - "line": 0, - "character": 10 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value": "(alias) const a: \"a\"\nimport a" - }, - "" - ], - "range": { - "start": { - "line": 0, - "character": 9 - }, - "end": { - "line": 0, - "character": 10 - } - } - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_hover_dependency() { - let _g = http_server(); - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file_01.ts", - "languageId": "typescript", - "version": 1, - "text": "export const a = \"a\";\n", - } - }), - ); - did_open( - &mut client, - load_fixture("did_open_params_import_hover.json"), - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "deno/cache", - json!({ - "referrer": { - "uri": "file:///a/file.ts", - }, - "uris": [], - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "position": { - "line": 0, - "character": 28 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": { - "kind": "markdown", - "value": "**Resolved Dependency**\n\n**Code**: http​://127.0.0.1:4545/xTypeScriptTypes.js\n\n**Types**: http​://127.0.0.1:4545/xTypeScriptTypes.d.ts\n" - }, - "range": { - "start": { - "line": 0, - "character": 19 - }, - "end":{ - "line": 0, - "character": 62 - } - } - })) - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "position": { - "line": 3, - "character": 28 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": { - "kind": "markdown", - "value": "**Resolved Dependency**\n\n**Code**: http​://127.0.0.1:4545/subdir/type_reference.js\n\n**Types**: http​://127.0.0.1:4545/subdir/type_reference.d.ts\n" - }, - "range": { - "start": { - "line": 3, - "character": 19 - }, - "end":{ - "line": 3, - "character": 67 - } - } - })) - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "position": { - "line": 4, - "character": 28 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": { - "kind": "markdown", - "value": "**Resolved Dependency**\n\n**Code**: http​://127.0.0.1:4545/subdir/mod1.ts\n" - }, - "range": { - "start": { - "line": 4, - "character": 19 - }, - "end":{ - "line": 4, - "character": 57 - } - } - })) - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "position": { - "line": 5, - "character": 28 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": { - "kind": "markdown", - "value": "**Resolved Dependency**\n\n**Code**: _(a data url)_\n" - }, - "range": { - "start": { - "line": 5, - "character": 19 - }, - "end":{ - "line": 5, - "character": 132 - } - } - })) - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "position": { - "line": 6, - "character": 28 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": { - "kind": "markdown", - "value": "**Resolved Dependency**\n\n**Code**: file​:///a/file_01.ts\n" - }, - "range": { - "start": { - "line": 6, - "character": 19 - }, - "end":{ - "line": 6, - "character": 33 - } - } - })) - ); -} - -// This tests for a regression covered by denoland/deno#12753 where the lsp was -// unable to resolve dependencies when there was an invalid syntax in the module -#[test] -fn lsp_hover_deps_preserved_when_invalid_parse() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file1.ts", - "languageId": "typescript", - "version": 1, - "text": "export type Foo = { bar(): string };\n" - } - }), - ); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file2.ts", - "languageId": "typescript", - "version": 1, - "text": "import { Foo } from './file1.ts'; declare const f: Foo; f\n" - } - }), - ); - let (maybe_res, maybe_error) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file2.ts" - }, - "position": { - "line": 0, - "character": 56 - } - }), - ) - .unwrap(); - assert!(maybe_error.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value": "const f: Foo", - }, - "" - ], - "range": { - "start": { - "line": 0, - "character": 56, - }, - "end": { - "line": 0, - "character": 57, - } - } - })) - ); - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file2.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 0, - "character": 57 - }, - "end": { - "line": 0, - "character": 58 - } - }, - "text": "." - } - ] - }), - ) - .unwrap(); - let (maybe_res, maybe_error) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file2.ts" - }, - "position": { - "line": 0, - "character": 56 - } - }), - ) - .unwrap(); - assert!(maybe_error.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value": "const f: Foo", - }, - "" - ], - "range": { - "start": { - "line": 0, - "character": 56, - }, - "end": { - "line": 0, - "character": 57, - } - } - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_hover_typescript_types() { - let _g = http_server(); - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "import * as a from \"http://127.0.0.1:4545/xTypeScriptTypes.js\";\n\nconsole.log(a.foo);\n", - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "deno/cache", - json!({ - "referrer": { - "uri": "file:///a/file.ts", - }, - "uris": [ - { - "uri": "http://127.0.0.1:4545/xTypeScriptTypes.js", - } - ], - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 24 - } - }), - ) - .unwrap(); - assert!(maybe_res.is_some()); - assert!(maybe_err.is_none()); - assert_eq!( - json!(maybe_res.unwrap()), - json!({ - "contents": { - "kind": "markdown", - "value": "**Resolved Dependency**\n\n**Code**: http​://127.0.0.1:4545/xTypeScriptTypes.js\n\n**Types**: http​://127.0.0.1:4545/xTypeScriptTypes.d.ts\n" - }, - "range": { - "start": { - "line": 0, - "character": 19 - }, - "end": { - "line": 0, - "character": 62 - } - } - }) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_hover_jsdoc_symbol_link() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/b.ts", - "languageId": "typescript", - "version": 1, - "text": "export function hello() {}\n" - } - }), - ); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "import { hello } from \"./b.ts\";\n\nhello();\n\nconst b = \"b\";\n\n/** JSDoc {@link hello} and {@linkcode b} */\nfunction a() {}\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 7, - "character": 10 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": [ - { - "language": "typescript", - "value": "function a(): void" - }, - "JSDoc [hello](file:///a/file.ts#L1,10) and [`b`](file:///a/file.ts#L5,7)" - ], - "range": { - "start": { - "line": 7, - "character": 9 - }, - "end": { - "line": 7, - "character": 10 - } - } - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_goto_type_definition() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "interface A {\n a: string;\n}\n\nexport class B implements A {\n a = \"a\";\n log() {\n console.log(this.a);\n }\n}\n\nconst b = new B();\nb;\n", - } - }), - ); - let (maybe_res, maybe_error) = client - .write_request::<_, _, Value>( - "textDocument/typeDefinition", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 12, - "character": 1 - } - }), - ) - .unwrap(); - assert!(maybe_error.is_none()); - assert_eq!( - maybe_res, - Some(json!([ - { - "targetUri": "file:///a/file.ts", - "targetRange": { - "start": { - "line": 4, - "character": 0 - }, - "end": { - "line": 9, - "character": 1 - } - }, - "targetSelectionRange": { - "start": { - "line": 4, - "character": 13 - }, - "end": { - "line": 4, - "character": 14 - } - } - } - ])) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_call_hierarchy() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "function foo() {\n return false;\n}\n\nclass Bar {\n baz() {\n return foo();\n }\n}\n\nfunction main() {\n const bar = new Bar();\n bar.baz();\n}\n\nmain();" - } - }), - ); - let (maybe_res, maybe_error) = client - .write_request( - "textDocument/prepareCallHierarchy", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 5, - "character": 3 - } - }), - ) - .unwrap(); - assert!(maybe_error.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("prepare_call_hierarchy_response.json")) - ); - let (maybe_res, maybe_error) = client - .write_request( - "callHierarchy/incomingCalls", - load_fixture("incoming_calls_params.json"), - ) - .unwrap(); - assert!(maybe_error.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("incoming_calls_response.json")) - ); - let (maybe_res, maybe_error) = client - .write_request( - "callHierarchy/outgoingCalls", - load_fixture("outgoing_calls_params.json"), - ) - .unwrap(); - assert!(maybe_error.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("outgoing_calls_response.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_large_doc_changes() { - let mut client = init("initialize_params.json"); - did_open(&mut client, load_fixture("did_open_params_large.json")); - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 444, - "character": 11 - }, - "end": { - "line": 444, - "character": 14 - } - }, - "text": "+++" - } - ] - }), - ) - .unwrap(); - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 445, - "character": 4 - }, - "end": { - "line": 445, - "character": 4 - } - }, - "text": "// " - } - ] - }), - ) - .unwrap(); - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 477, - "character": 4 - }, - "end": { - "line": 477, - "character": 9 - } - }, - "text": "error" - } - ] - }), - ) - .unwrap(); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 421, - "character": 30 - } - }), - ) - .unwrap(); - assert!(maybe_res.is_some()); - assert!(maybe_err.is_none()); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 444, - "character": 6 - } - }), - ) - .unwrap(); - assert!(maybe_res.is_some()); - assert!(maybe_err.is_none()); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 461, - "character": 34 - } - }), - ) - .unwrap(); - assert!(maybe_res.is_some()); - assert!(maybe_err.is_none()); - shutdown(&mut client); - - assert!(client.duration().as_millis() <= 15000); -} - -#[test] -fn lsp_document_symbol() { - let mut client = init("initialize_params.json"); - did_open(&mut client, load_fixture("did_open_params_doc_symbol.json")); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/documentSymbol", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("document_symbol_response.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_folding_range() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "// #region 1\n/*\n * Some comment\n */\nclass Foo {\n bar(a, b) {\n if (a === b) {\n return true;\n }\n return false;\n }\n}\n// #endregion" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/foldingRange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!([ - { - "startLine": 0, - "endLine": 12, - "kind": "region" - }, - { - "startLine": 1, - "endLine": 3, - "kind": "comment" - }, - { - "startLine": 4, - "endLine": 10 - }, - { - "startLine": 5, - "endLine": 9 - }, - { - "startLine": 6, - "endLine": 7 - } - ])) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_rename() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - // this should not rename in comments and strings - "text": "let variable = 'a'; // variable\nconsole.log(variable);\n\"variable\";\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/rename", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 4 - }, - "newName": "variable_modified" - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(load_fixture("rename_response.json"))); - shutdown(&mut client); -} - -#[test] -fn lsp_selection_range() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "class Foo {\n bar(a, b) {\n if (a === b) {\n return true;\n }\n return false;\n }\n}" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/selectionRange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "positions": [ - { - "line": 2, - "character": 8 - } - ] - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("selection_range_response.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_semantic_tokens() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - load_fixture("did_open_params_semantic_tokens.json"), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/semanticTokens/full", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "data": [ - 0, 5, 6, 1, 1, 0, 9, 6, 8, 9, 0, 8, 6, 8, 9, 2, 15, 3, 10, 5, 0, 4, 1, - 6, 1, 0, 12, 7, 2, 16, 1, 8, 1, 7, 41, 0, 4, 1, 6, 0, 0, 2, 5, 11, 16, - 1, 9, 1, 7, 40, 3, 10, 4, 2, 1, 1, 11, 1, 9, 9, 1, 2, 3, 11, 1, 3, 6, 3, - 0, 1, 0, 15, 4, 2, 0, 1, 30, 1, 6, 9, 1, 2, 3, 11,1, 1, 9, 9, 9, 3, 0, - 16, 3, 0, 0, 1, 17, 12, 11, 3, 0, 24, 3, 0, 0, 0, 4, 9, 9, 2 - ] - })) - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/semanticTokens/range", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "range": { - "start": { - "line": 0, - "character": 0 - }, - "end": { - "line": 6, - "character": 0 - } - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "data": [ - 0, 5, 6, 1, 1, 0, 9, 6, 8, 9, 0, 8, 6, 8, 9, 2, 15, 3, 10, 5, 0, 4, 1, - 6, 1, 0, 12, 7, 2, 16, 1, 8, 1, 7, 41, 0, 4, 1, 6, 0, 0, 2, 5, 11, 16, - 1, 9, 1, 7, 40 - ] - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_code_lens() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "class A {\n a = \"a\";\n\n b() {\n console.log(this.a);\n }\n\n c() {\n this.a = \"c\";\n }\n}\n\nconst a = new A();\na.b();\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeLens", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(load_fixture("code_lens_response.json"))); - let (maybe_res, maybe_err) = client - .write_request( - "codeLens/resolve", - json!({ - "range": { - "start": { - "line": 0, - "character": 6 - }, - "end": { - "line": 0, - "character": 7 - } - }, - "data": { - "specifier": "file:///a/file.ts", - "source": "references" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_lens_resolve_response.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_code_lens_impl() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "interface A {\n b(): void;\n}\n\nclass B implements A {\n b() {\n console.log(\"b\");\n }\n}\n\ninterface C {\n c: string;\n}\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeLens", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_lens_response_impl.json")) - ); - let (maybe_res, maybe_err) = client - .write_request( - "codeLens/resolve", - json!({ - "range": { - "start": { - "line": 0, - "character": 10 - }, - "end": { - "line": 0, - "character": 11 - } - }, - "data": { - "specifier": "file:///a/file.ts", - "source": "implementations" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_lens_resolve_response_impl.json")) - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "codeLens/resolve", - json!({ - "range": { - "start": { - "line": 10, - "character": 10 - }, - "end": { - "line": 10, - "character": 11 - } - }, - "data": { - "specifier": "file:///a/file.ts", - "source": "implementations" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "range": { - "start": { - "line": 10, - "character": 10 - }, - "end": { - "line": 10, - "character": 11 - } - }, - "command": { - "title": "0 implementations", - "command": "" - } - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_code_lens_test() { - let mut client = init("initialize_params_code_lens_test.json"); - did_open( - &mut client, - load_fixture("did_open_params_test_code_lens.json"), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeLens", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_lens_response_test.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_code_lens_test_disabled() { - let mut client = init("initialize_params_code_lens_test_disabled.json"); - client - .write_notification( - "textDocument/didOpen", - load_fixture("did_open_params_test_code_lens.json"), - ) - .unwrap(); - - let (id, method, _) = client.read_request::().unwrap(); - assert_eq!(method, "workspace/configuration"); - client - .write_response( - id, - json!([{ - "enable": true, - "codeLens": { - "test": false - } - }]), - ) - .unwrap(); - - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - let (method, _) = client.read_notification::().unwrap(); - assert_eq!(method, "textDocument/publishDiagnostics"); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeLens", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!([]))); - shutdown(&mut client); -} - -#[test] -fn lsp_code_lens_non_doc_nav_tree() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "console.log(Date.now());\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/references", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 3 - }, - "context": { - "includeDeclaration": true - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "deno/virtualTextDocument", - json!({ - "textDocument": { - "uri": "deno:/asset/lib.deno.shared_globals.d.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Vec>( - "textDocument/codeLens", - json!({ - "textDocument": { - "uri": "deno:/asset/lib.deno.shared_globals.d.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let res = maybe_res.unwrap(); - assert!(res.len() > 50); - let (maybe_res, maybe_err) = client - .write_request::<_, _, lsp::CodeLens>( - "codeLens/resolve", - json!({ - "range": { - "start": { - "line": 416, - "character": 12 - }, - "end": { - "line": 416, - "character": 19 - } - }, - "data": { - "specifier": "asset:///lib.deno.shared_globals.d.ts", - "source": "references" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - shutdown(&mut client); -} - -#[test] -fn lsp_nav_tree_updates() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "interface A {\n b(): void;\n}\n\nclass B implements A {\n b() {\n console.log(\"b\");\n }\n}\n\ninterface C {\n c: string;\n}\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeLens", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_lens_response_impl.json")) - ); - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 10, - "character": 0 - }, - "end": { - "line": 13, - "character": 0 - } - }, - "text": "" - } - ] - }), - ) - .unwrap(); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeLens", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_lens_response_changed.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_signature_help() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "/**\n * Adds two numbers.\n * @param a This is a first number.\n * @param b This is a second number.\n */\nfunction add(a: number, b: number) {\n return a + b;\n}\n\nadd(" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/signatureHelp", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "character": 4, - "line": 9 - }, - "context": { - "triggerKind": 2, - "triggerCharacter": "(", - "isRetrigger": false - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "signatures": [ - { - "label": "add(a: number, b: number): number", - "documentation": { - "kind": "markdown", - "value": "Adds two numbers." - }, - "parameters": [ - { - "label": "a: number", - "documentation": { - "kind": "markdown", - "value": "This is a first number." - } - }, - { - "label": "b: number", - "documentation": { - "kind": "markdown", - "value": "This is a second number." - } - } - ] - } - ], - "activeSignature": 0, - "activeParameter": 0 - })) - ); - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 9, - "character": 4 - }, - "end": { - "line": 9, - "character": 4 - } - }, - "text": "123, " - } - ] - }), - ) - .unwrap(); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/signatureHelp", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "character": 8, - "line": 9 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "signatures": [ - { - "label": "add(a: number, b: number): number", - "documentation": { - "kind": "markdown", - "value": "Adds two numbers." - }, - "parameters": [ - { - "label": "a: number", - "documentation": { - "kind": "markdown", - "value": "This is a first number." - } - }, - { - "label": "b: number", - "documentation": { - "kind": "markdown", - "value": "This is a second number." - } - } - ] - } - ], - "activeSignature": 0, - "activeParameter": 1 - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_code_actions() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "export function a(): void {\n await Promise.resolve(\"a\");\n}\n\nexport function b(): void {\n await Promise.resolve(\"b\");\n}\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeAction", - load_fixture("code_action_params.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(load_fixture("code_action_response.json"))); - let (maybe_res, maybe_err) = client - .write_request( - "codeAction/resolve", - load_fixture("code_action_resolve_params.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_action_resolve_response.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_code_actions_deno_cache() { - let mut session = TestSession::from_file("initialize_params.json"); - let diagnostics = session.did_open(json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "import * as a from \"https://deno.land/x/a/mod.ts\";\n\nconsole.log(a);\n" - } - })); - assert_eq!( - diagnostics.with_source("deno"), - load_fixture_as("diagnostics_deno_deps.json") - ); - - let (maybe_res, maybe_err) = session - .client - .write_request( - "textDocument/codeAction", - load_fixture("code_action_params_cache.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_action_response_cache.json")) - ); - session.shutdown_and_exit(); -} - -#[test] -fn lsp_code_actions_deno_cache_npm() { - let mut session = TestSession::from_file("initialize_params.json"); - let diagnostics = session.did_open(json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "import chalk from \"npm:chalk\";\n\nconsole.log(chalk.green);\n" - } - })); - assert_eq!( - diagnostics.with_source("deno"), - load_fixture_as("code_actions/cache_npm/diagnostics.json") - ); - - let (maybe_res, maybe_err) = session - .client - .write_request( - "textDocument/codeAction", - load_fixture("code_actions/cache_npm/cache_action.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_actions/cache_npm/cache_response.json")) - ); - session.shutdown_and_exit(); -} - -#[test] -fn lsp_code_actions_imports() { - let mut session = TestSession::from_file("initialize_params.json"); - session.did_open(json!({ - "textDocument": { - "uri": "file:///a/file00.ts", - "languageId": "typescript", - "version": 1, - "text": "export const abc = \"abc\";\nexport const def = \"def\";\n" - } - })); - session.did_open(json!({ - "textDocument": { - "uri": "file:///a/file01.ts", - "languageId": "typescript", - "version": 1, - "text": "\nconsole.log(abc);\nconsole.log(def)\n" - } - })); - - let (maybe_res, maybe_err) = session - .client - .write_request( - "textDocument/codeAction", - load_fixture("code_action_params_imports.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_action_response_imports.json")) - ); - let (maybe_res, maybe_err) = session - .client - .write_request( - "codeAction/resolve", - load_fixture("code_action_resolve_params_imports.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_action_resolve_response_imports.json")) - ); - - session.shutdown_and_exit(); -} - -#[test] -fn lsp_code_actions_refactor() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "var x: { a?: number; b?: string } = {};\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeAction", - load_fixture("code_action_params_refactor.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_action_response_refactor.json")) - ); - let (maybe_res, maybe_err) = client - .write_request( - "codeAction/resolve", - load_fixture("code_action_resolve_params_refactor.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_action_resolve_response_refactor.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_code_actions_refactor_no_disabled_support() { - let mut client = init("initialize_params_ca_no_disabled.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "interface A {\n a: string;\n}\n\ninterface B {\n b: string;\n}\n\nclass AB implements A, B {\n a = \"a\";\n b = \"b\";\n}\n\nnew AB().a;\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeAction", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "range": { - "start": { - "line": 0, - "character": 0 - }, - "end": { - "line": 14, - "character": 0 - } - }, - "context": { - "diagnostics": [], - "only": [ - "refactor" - ] - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_action_response_no_disabled.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_code_actions_deadlock() { - let mut client = init("initialize_params.json"); - client - .write_notification( - "textDocument/didOpen", - load_fixture("did_open_params_large.json"), - ) - .unwrap(); - let (id, method, _) = client.read_request::().unwrap(); - assert_eq!(method, "workspace/configuration"); - client - .write_response(id, json!([{ "enable": true }])) - .unwrap(); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/semanticTokens/full", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - read_diagnostics(&mut client); - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 444, - "character": 11 - }, - "end": { - "line": 444, - "character": 14 - } - }, - "text": "+++" - } - ] - }), - ) - .unwrap(); - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 445, - "character": 4 - }, - "end": { - "line": 445, - "character": 4 - } - }, - "text": "// " - } - ] - }), - ) - .unwrap(); - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 477, - "character": 4 - }, - "end": { - "line": 477, - "character": 9 - } - }, - "text": "error" - } - ] - }), - ) - .unwrap(); - // diagnostics only trigger after changes have elapsed in a separate thread, - // so we need to delay the next messages a little bit to attempt to create a - // potential for a deadlock with the codeAction - std::thread::sleep(std::time::Duration::from_millis(50)); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "position": { - "line": 609, - "character": 33, - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/codeAction", - load_fixture("code_action_params_deadlock.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - - read_diagnostics(&mut client); - - shutdown(&mut client); -} - -#[test] -fn lsp_completions() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "Deno." - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/completion", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 5 - }, - "context": { - "triggerKind": 2, - "triggerCharacter": "." - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - if let Some(lsp::CompletionResponse::List(list)) = maybe_res { - assert!(!list.is_incomplete); - assert!(list.items.len() > 90); - } else { - panic!("unexpected response"); - } - let (maybe_res, maybe_err) = client - .write_request( - "completionItem/resolve", - load_fixture("completion_resolve_params.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("completion_resolve_response.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_completions_optional() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "interface A {\n b?: string;\n}\n\nconst o: A = {};\n\nfunction c(s: string) {}\n\nc(o.)" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/completion", - load_fixture("completion_request_params_optional.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "isIncomplete": false, - "items": [ - { - "label": "b?", - "kind": 5, - "sortText": "11", - "filterText": "b", - "insertText": "b", - "commitCharacters": [".", ",", ";", "("], - "data": { - "tsc": { - "specifier": "file:///a/file.ts", - "position": 79, - "name": "b", - "useCodeSnippet": false - } - } - } - ] - })) - ); - let (maybe_res, maybe_err) = client - .write_request( - "completionItem/resolve", - load_fixture("completion_resolve_params_optional.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "label": "b?", - "kind": 5, - "detail": "(property) A.b?: string | undefined", - "documentation": { - "kind": "markdown", - "value": "" - }, - "sortText": "1", - "filterText": "b", - "insertText": "b" - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_completions_auto_import() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/b.ts", - "languageId": "typescript", - "version": 1, - "text": "export const foo = \"foo\";\n", - } - }), - ); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "export {};\n\n", - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/completion", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 2, - "character": 0, - }, - "context": { - "triggerKind": 1, - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - if let Some(lsp::CompletionResponse::List(list)) = maybe_res { - assert!(!list.is_incomplete); - if !list.items.iter().any(|item| item.label == "foo") { - panic!("completions items missing 'foo' symbol"); - } - } else { - panic!("unexpected completion response"); - } - let (maybe_res, maybe_err) = client - .write_request( - "completionItem/resolve", - json!({ - "label": "foo", - "kind": 6, - "sortText": "￿16", - "commitCharacters": [ - ".", - ",", - ";", - "(" - ], - "data": { - "tsc": { - "specifier": "file:///a/file.ts", - "position": 12, - "name": "foo", - "source": "./b", - "data": { - "exportName": "foo", - "moduleSpecifier": "./b", - "fileName": "file:///a/b.ts" - }, - "useCodeSnippet": false - } - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "label": "foo", - "kind": 6, - "detail": "const foo: \"foo\"", - "documentation": { - "kind": "markdown", - "value": "" - }, - "sortText": "￿16", - "additionalTextEdits": [ - { - "range": { - "start": { - "line": 0, - "character": 0 - }, - "end": { - "line": 0, - "character": 0 - } - }, - "newText": "import { foo } from \"./b.ts\";\n\n" - } - ], - "commitCharacters": [ - ".", - ",", - ";", - "(" - ] - })) - ); -} - -#[test] -fn lsp_completions_snippet() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/a.tsx", - "languageId": "typescriptreact", - "version": 1, - "text": "function A({ type }: { type: string }) {\n return type;\n}\n\nfunction B() {\n return ( - "deno/cache", - json!({ - "referrer": { - "uri": "file:///a/file.ts", - }, - "uris": [ - { - "uri": "npm:@denotest/cjs-default-export", - }, - { - "uri": "npm:chalk", - } - ] - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - - // check importing a cjs default import - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 2, - "character": 0 - }, - "end": { - "line": 2, - "character": 0 - } - }, - "text": "cjsDefault." - } - ] - }), - ) - .unwrap(); - read_diagnostics(&mut client); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/completion", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 2, - "character": 11 - }, - "context": { - "triggerKind": 2, - "triggerCharacter": "." - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - if let Some(lsp::CompletionResponse::List(list)) = maybe_res { - assert!(!list.is_incomplete); - assert_eq!(list.items.len(), 3); - assert!(list.items.iter().any(|i| i.label == "default")); - assert!(list.items.iter().any(|i| i.label == "MyClass")); - } else { - panic!("unexpected response"); - } - let (maybe_res, maybe_err) = client - .write_request( - "completionItem/resolve", - load_fixture("completions/npm/resolve_params.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("completions/npm/resolve_response.json")) - ); - - // now check chalk, which is esm - client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "version": 3 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 2, - "character": 0 - }, - "end": { - "line": 2, - "character": 11 - } - }, - "text": "chalk." - } - ] - }), - ) - .unwrap(); - read_diagnostics(&mut client); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/completion", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 2, - "character": 6 - }, - "context": { - "triggerKind": 2, - "triggerCharacter": "." - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - if let Some(lsp::CompletionResponse::List(list)) = maybe_res { - assert!(!list.is_incomplete); - assert!(list.items.iter().any(|i| i.label == "green")); - assert!(list.items.iter().any(|i| i.label == "red")); - } else { - panic!("unexpected response"); - } - - shutdown(&mut client); -} - -#[test] -fn lsp_completions_registry() { - let _g = http_server(); - let mut client = init("initialize_params_registry.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "import * as a from \"http://localhost:4545/x/a@\"" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/completion", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 46 - }, - "context": { - "triggerKind": 2, - "triggerCharacter": "@" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - if let Some(lsp::CompletionResponse::List(list)) = maybe_res { - assert!(!list.is_incomplete); - assert_eq!(list.items.len(), 3); - } else { - panic!("unexpected response"); - } - let (maybe_res, maybe_err) = client - .write_request( - "completionItem/resolve", - load_fixture("completion_resolve_params_registry.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("completion_resolve_response_registry.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_completions_registry_empty() { - let _g = http_server(); - let mut client = init("initialize_params_registry.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "import * as a from \"\"" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/completion", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 20 - }, - "context": { - "triggerKind": 2, - "triggerCharacter": "\"" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("completion_request_response_empty.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_auto_discover_registry() { - let _g = http_server(); - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "import * as a from \"http://localhost:4545/x/a@\"" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/completion", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 46 - }, - "context": { - "triggerKind": 2, - "triggerCharacter": "@" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let (method, maybe_res) = client.read_notification().unwrap(); - assert_eq!(method, "deno/registryState"); - assert_eq!( - maybe_res, - Some(json!({ - "origin": "http://localhost:4545", - "suggestions": true, - })) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_cache_location() { - let _g = http_server(); - let temp_dir = TempDir::new(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params_registry.json")) - .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("cache".to_string(), json!(".cache")); - params.initialization_options = Some(Value::Object(map)); - } - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - client.write_notification("initialized", json!({})).unwrap(); - let mut session = TestSession::from_client(client); - - session.did_open(json!({ - "textDocument": { - "uri": "file:///a/file_01.ts", - "languageId": "typescript", - "version": 1, - "text": "export const a = \"a\";\n", - } - })); - let diagnostics = - session.did_open(load_fixture("did_open_params_import_hover.json")); - assert_eq!(diagnostics.viewed().len(), 7); - let (maybe_res, maybe_err) = session - .client - .write_request::<_, _, Value>( - "deno/cache", - json!({ - "referrer": { - "uri": "file:///a/file.ts", - }, - "uris": [], - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let (maybe_res, maybe_err) = session - .client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "position": { - "line": 0, - "character": 28 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": { - "kind": "markdown", - "value": "**Resolved Dependency**\n\n**Code**: http​://127.0.0.1:4545/xTypeScriptTypes.js\n\n**Types**: http​://127.0.0.1:4545/xTypeScriptTypes.d.ts\n" - }, - "range": { - "start": { - "line": 0, - "character": 19 - }, - "end":{ - "line": 0, - "character": 62 - } - } - })) - ); - let (maybe_res, maybe_err) = session - .client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "position": { - "line": 7, - "character": 28 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": { - "kind": "markdown", - "value": "**Resolved Dependency**\n\n**Code**: http​://localhost:4545/x/a/mod.ts\n\n\n---\n\n**a**\n\nmod.ts" - }, - "range": { - "start": { - "line": 7, - "character": 19 - }, - "end": { - "line": 7, - "character": 53 - } - } - })) - ); - let cache_path = temp_dir.path().join(".cache"); - assert!(cache_path.is_dir()); - assert!(cache_path.join("gen").is_dir()); - session.shutdown_and_exit(); -} - -/// Sets the TLS root certificate on startup, which allows the LSP to connect to -/// the custom signed test server and be able to retrieve the registry config -/// and cache files. -#[test] -fn lsp_tls_cert() { - let _g = http_server(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params_tls_cert.json")) - .unwrap(); - - params.root_uri = Some(Url::from_file_path(testdata_path()).unwrap()); - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - client.write_notification("initialized", json!({})).unwrap(); - let mut session = TestSession::from_client(client); - - session.did_open(json!({ - "textDocument": { - "uri": "file:///a/file_01.ts", - "languageId": "typescript", - "version": 1, - "text": "export const a = \"a\";\n", - } - })); - let diagnostics = - session.did_open(load_fixture("did_open_params_tls_cert.json")); - let diagnostics = diagnostics.viewed(); - assert_eq!(diagnostics.len(), 7); - let (maybe_res, maybe_err) = session - .client - .write_request::<_, _, Value>( - "deno/cache", - json!({ - "referrer": { - "uri": "file:///a/file.ts", - }, - "uris": [], - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let (maybe_res, maybe_err) = session - .client - .write_request( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "position": { - "line": 0, - "character": 28 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": { - "kind": "markdown", - "value": "**Resolved Dependency**\n\n**Code**: https​://localhost:5545/xTypeScriptTypes.js\n" - }, - "range": { - "start": { - "line": 0, - "character": 19 - }, - "end":{ - "line": 0, - "character": 63 - } - } - })) - ); - let (maybe_res, maybe_err) = session - .client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - }, - "position": { - "line": 7, - "character": 28 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": { - "kind": "markdown", - "value": "**Resolved Dependency**\n\n**Code**: http​://localhost:4545/x/a/mod.ts\n\n\n---\n\n**a**\n\nmod.ts" - }, - "range": { - "start": { - "line": 7, - "character": 19 - }, - "end": { - "line": 7, - "character": 53 - } - } - })) - ); - session.shutdown_and_exit(); -} - -#[test] -fn lsp_diagnostics_warn_redirect() { - let _g = http_server(); - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "import * as a from \"http://127.0.0.1:4545/x_deno_warning.js\";\n\nconsole.log(a)\n", - }, - }), - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "deno/cache", - json!({ - "referrer": { - "uri": "file:///a/file.ts", - }, - "uris": [ - { - "uri": "http://127.0.0.1:4545/x_deno_warning.js", - } - ], - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let diagnostics = read_diagnostics(&mut client); - assert_eq!( - diagnostics.with_source("deno"), - lsp::PublishDiagnosticsParams { - uri: Url::parse("file:///a/file.ts").unwrap(), - diagnostics: vec![ - lsp::Diagnostic { - range: lsp::Range { - start: lsp::Position { - line: 0, - character: 19 - }, - end: lsp::Position { - line: 0, - character: 60 - } - }, - severity: Some(lsp::DiagnosticSeverity::WARNING), - code: Some(lsp::NumberOrString::String("deno-warn".to_string())), - source: Some("deno".to_string()), - message: "foobar".to_string(), - ..Default::default() - }, - lsp::Diagnostic { - range: lsp::Range { - start: lsp::Position { - line: 0, - character: 19 - }, - end: lsp::Position { - line: 0, - character: 60 - } - }, - severity: Some(lsp::DiagnosticSeverity::INFORMATION), - code: Some(lsp::NumberOrString::String("redirect".to_string())), - source: Some("deno".to_string()), - message: "The import of \"http://127.0.0.1:4545/x_deno_warning.js\" was redirected to \"http://127.0.0.1:4545/lsp/x_deno_warning_redirect.js\".".to_string(), - data: Some(json!({"specifier": "http://127.0.0.1:4545/x_deno_warning.js", "redirect": "http://127.0.0.1:4545/lsp/x_deno_warning_redirect.js"})), - ..Default::default() - } - ], - version: Some(1), - } - ); - shutdown(&mut client); -} - -#[test] -fn lsp_redirect_quick_fix() { - let _g = http_server(); - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "import * as a from \"http://127.0.0.1:4545/x_deno_warning.js\";\n\nconsole.log(a)\n", - }, - }), - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "deno/cache", - json!({ - "referrer": { - "uri": "file:///a/file.ts", - }, - "uris": [ - { - "uri": "http://127.0.0.1:4545/x_deno_warning.js", - } - ], - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let diagnostics = read_diagnostics(&mut client) - .with_source("deno") - .diagnostics; - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeAction", - json!(json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "range": { - "start": { - "line": 0, - "character": 19 - }, - "end": { - "line": 0, - "character": 60 - } - }, - "context": { - "diagnostics": diagnostics, - "only": [ - "quickfix" - ] - } - })), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_action_redirect_response.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_diagnostics_deprecated() { - let mut client = init("initialize_params.json"); - let diagnostics = did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "/** @deprecated */\nexport const a = \"a\";\n\na;\n", - }, - }), - ); - assert_eq!( - json!(diagnostics), - json!([ - { - "uri": "file:///a/file.ts", - "diagnostics": [], - "version": 1 - }, - { - "uri": "file:///a/file.ts", - "diagnostics": [], - "version": 1 - }, - { - "uri": "file:///a/file.ts", - "diagnostics": [ - { - "range": { - "start": { - "line": 3, - "character": 0 - }, - "end": { - "line": 3, - "character": 1 - } - }, - "severity": 4, - "code": 6385, - "source": "deno-ts", - "message": "'a' is deprecated.", - "relatedInformation": [], - "tags": [ - 2 - ] - } - ], - "version": 1 - } - ]) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_diagnostics_deno_types() { - let mut client = init("initialize_params.json"); - client - .write_notification( - "textDocument/didOpen", - load_fixture("did_open_params_deno_types.json"), - ) - .unwrap(); - let (id, method, _) = client.read_request::().unwrap(); - assert_eq!(method, "workspace/configuration"); - client - .write_response(id, json!([{ "enable": true }])) - .unwrap(); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/documentSymbol", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - } - }), - ) - .unwrap(); - assert!(maybe_res.is_some()); - assert!(maybe_err.is_none()); - let diagnostics = read_diagnostics(&mut client); - assert_eq!(diagnostics.viewed().len(), 5); - shutdown(&mut client); -} - -#[test] -fn lsp_diagnostics_refresh_dependents() { - let mut session = TestSession::from_file("initialize_params.json"); - session.did_open(json!({ - "textDocument": { - "uri": "file:///a/file_00.ts", - "languageId": "typescript", - "version": 1, - "text": "export const a = \"a\";\n", - }, - })); - session.did_open(json!({ - "textDocument": { - "uri": "file:///a/file_01.ts", - "languageId": "typescript", - "version": 1, - "text": "export * from \"./file_00.ts\";\n", - }, - })); - let diagnostics = session.did_open(json!({ - "textDocument": { - "uri": "file:///a/file_02.ts", - "languageId": "typescript", - "version": 1, - "text": "import { a, b } from \"./file_01.ts\";\n\nconsole.log(a, b);\n" - } - })); - assert_eq!( - json!(diagnostics.with_file_and_source("file:///a/file_02.ts", "deno-ts")), - json!({ - "uri": "file:///a/file_02.ts", - "diagnostics": [ - { - "range": { - "start": { - "line": 0, - "character": 12 - }, - "end": { - "line": 0, - "character": 13 - } - }, - "severity": 1, - "code": 2305, - "source": "deno-ts", - "message": "Module '\"./file_01.ts\"' has no exported member 'b'." - } - ], - "version": 1 - }) - ); - - // fix the code causing the diagnostic - session - .client - .write_notification( - "textDocument/didChange", - json!({ - "textDocument": { - "uri": "file:///a/file_00.ts", - "version": 2 - }, - "contentChanges": [ - { - "range": { - "start": { - "line": 1, - "character": 0 - }, - "end": { - "line": 1, - "character": 0 - } - }, - "text": "export const b = \"b\";\n" - } - ] - }), - ) - .unwrap(); - let diagnostics = session.read_diagnostics(); - assert_eq!(diagnostics.viewed().len(), 0); // no diagnostics now - - session.shutdown_and_exit(); - assert_eq!(session.client.queue_len(), 0); -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PerformanceAverage { - pub name: String, - pub count: u32, - pub average_duration: u32, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -struct PerformanceAverages { - averages: Vec, -} - -#[test] -fn lsp_performance() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "console.log(Deno.args);\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 19 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let (maybe_res, maybe_err) = client - .write_request::<_, _, PerformanceAverages>("deno/performance", json!(null)) - .unwrap(); - assert!(maybe_err.is_none()); - if let Some(res) = maybe_res { - assert_eq!(res.averages.len(), 13); - } else { - panic!("unexpected result"); - } - shutdown(&mut client); -} - -#[test] -fn lsp_format_no_changes() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "console;\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/formatting", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "options": { - "tabSize": 2, - "insertSpaces": true - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!(null))); - client.assert_no_notification("window/showMessage"); - shutdown(&mut client); -} - -#[test] -fn lsp_format_error() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "console test test\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/formatting", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "options": { - "tabSize": 2, - "insertSpaces": true - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!(null))); - shutdown(&mut client); -} - -#[test] -fn lsp_format_mbc() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "const bar = '👍🇺🇸😃'\nconsole.log('hello deno')\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/formatting", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "options": { - "tabSize": 2, - "insertSpaces": true - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!(load_fixture("formatting_mbc_response.json"))) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_format_exclude_with_config() { - let temp_dir = TempDir::new(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); - let deno_fmt_jsonc = - serde_json::to_vec_pretty(&load_fixture("deno.fmt.exclude.jsonc")).unwrap(); - fs::write(temp_dir.path().join("deno.fmt.jsonc"), deno_fmt_jsonc).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!("./deno.fmt.jsonc")); - params.initialization_options = Some(Value::Object(map)); - } - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - - let file_uri = - ModuleSpecifier::from_file_path(temp_dir.path().join("ignored.ts")) - .unwrap() - .to_string(); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": file_uri, - "languageId": "typescript", - "version": 1, - "text": "function myFunc(){}" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/formatting", - json!({ - "textDocument": { - "uri": file_uri - }, - "options": { - "tabSize": 2, - "insertSpaces": true - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!(null))); - shutdown(&mut client); -} - -#[test] -fn lsp_format_exclude_default_config() { - let temp_dir = TempDir::new(); - let workspace_root = temp_dir.path().canonicalize().unwrap(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); - let deno_jsonc = - serde_json::to_vec_pretty(&load_fixture("deno.fmt.exclude.jsonc")).unwrap(); - fs::write(workspace_root.join("deno.jsonc"), deno_jsonc).unwrap(); - - params.root_uri = Some(Url::from_file_path(workspace_root.clone()).unwrap()); - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - - let file_uri = - ModuleSpecifier::from_file_path(workspace_root.join("ignored.ts")) - .unwrap() - .to_string(); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": file_uri, - "languageId": "typescript", - "version": 1, - "text": "function myFunc(){}" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/formatting", - json!({ - "textDocument": { - "uri": file_uri - }, - "options": { - "tabSize": 2, - "insertSpaces": true - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!(null))); - shutdown(&mut client); -} - -#[test] -fn lsp_format_json() { - let mut client = init("initialize_params.json"); - client - .write_notification( - "textDocument/didOpen", - json!({ - "textDocument": { - "uri": "file:///a/file.json", - "languageId": "json", - "version": 1, - "text": "{\"key\":\"value\"}" - } - }), - ) - .unwrap(); - - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/formatting", - json!({ - "textDocument": { - "uri": "file:///a/file.json" - }, - "options": { - "tabSize": 2, - "insertSpaces": true - } - }), - ) - .unwrap(); - - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!([ - { - "range": { - "start": { - "line": 0, - "character": 1 - }, - "end": { - "line": 0, - "character": 1 - } - }, - "newText": " " - }, - { - "range": { - "start": { "line": 0, "character": 7 }, - "end": { "line": 0, "character": 7 } - }, - "newText": " " - }, - { - "range": { - "start": { "line": 0, "character": 14 }, - "end": { "line": 0, "character": 15 } - }, - "newText": " }\n" - } - ])) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_json_no_diagnostics() { - let mut client = init("initialize_params.json"); - client - .write_notification( - "textDocument/didOpen", - json!({ - "textDocument": { - "uri": "file:///a/file.json", - "languageId": "json", - "version": 1, - "text": "{\"key\":\"value\"}" - } - }), - ) - .unwrap(); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/semanticTokens/full", - json!({ - "textDocument": { - "uri": "file:///a/file.json" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!(null))); - - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.json" - }, - "position": { - "line": 0, - "character": 3 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!(null))); - - shutdown(&mut client); -} - -#[test] -fn lsp_format_markdown() { - let mut client = init("initialize_params.json"); - client - .write_notification( - "textDocument/didOpen", - json!({ - "textDocument": { - "uri": "file:///a/file.md", - "languageId": "markdown", - "version": 1, - "text": "# Hello World" - } - }), - ) - .unwrap(); - - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/formatting", - json!({ - "textDocument": { - "uri": "file:///a/file.md" - }, - "options": { - "tabSize": 2, - "insertSpaces": true - } - }), - ) - .unwrap(); - - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!([ - { - "range": { - "start": { "line": 0, "character": 1 }, - "end": { "line": 0, "character": 3 } - }, - "newText": "" - }, - { - "range": { - "start": { "line": 0, "character": 15 }, - "end": { "line": 0, "character": 15 } - }, - "newText": "\n" - } - ])) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_format_with_config() { - let temp_dir = TempDir::new(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); - let deno_fmt_jsonc = - serde_json::to_vec_pretty(&load_fixture("deno.fmt.jsonc")).unwrap(); - fs::write(temp_dir.path().join("deno.fmt.jsonc"), deno_fmt_jsonc).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!("./deno.fmt.jsonc")); - params.initialization_options = Some(Value::Object(map)); - } - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - - client - .write_notification( - "textDocument/didOpen", - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "export async function someVeryLongFunctionName() {\nconst response = fetch(\"http://localhost:4545/some/non/existent/path.json\");\nconsole.log(response.text());\nconsole.log(\"finished!\")\n}" - } - }), - ) - .unwrap(); - - // The options below should be ignored in favor of configuration from config file. - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/formatting", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "options": { - "tabSize": 2, - "insertSpaces": true - } - }), - ) - .unwrap(); - - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!([{ - "range": { - "start": { - "line": 1, - "character": 0 - }, - "end": { - "line": 1, - "character": 0 - } - }, - "newText": "\t" - }, - { - "range": { - "start": { - "line": 1, - "character": 23 - }, - "end": { - "line": 1, - "character": 24 - } - }, - "newText": "\n\t\t'" - }, - { - "range": { - "start": { - "line": 1, - "character": 73 - }, - "end": { - "line": 1, - "character": 74 - } - }, - "newText": "',\n\t" - }, - { - "range": { - "start": { - "line": 2, - "character": 0 - }, - "end": { - "line": 2, - "character": 0 - } - }, - "newText": "\t" - }, - { - "range": { - "start": { - "line": 3, - "character": 0 - }, - "end": { - "line": 3, - "character": 0 - } - }, - "newText": "\t" - }, - { - "range": { - "start": { - "line": 3, - "character": 12 - }, - "end": { - "line": 3, - "character": 13 - } - }, - "newText": "'" - }, - { - "range": { - "start": { - "line": 3, - "character": 22 - }, - "end": { - "line": 3, - "character": 24 - } - }, - "newText": "');" - }, - { - "range": { - "start": { - "line": 4, - "character": 1 - }, - "end": { - "line": 4, - "character": 1 - } - }, - "newText": "\n" - }] - )) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_markdown_no_diagnostics() { - let mut client = init("initialize_params.json"); - client - .write_notification( - "textDocument/didOpen", - json!({ - "textDocument": { - "uri": "file:///a/file.md", - "languageId": "markdown", - "version": 1, - "text": "# Hello World" - } - }), - ) - .unwrap(); - - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/semanticTokens/full", - json!({ - "textDocument": { - "uri": "file:///a/file.md" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!(null))); - - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.md" - }, - "position": { - "line": 0, - "character": 3 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!(maybe_res, Some(json!(null))); - - shutdown(&mut client); -} - -#[test] -fn lsp_configuration_did_change() { - let _g = http_server(); - let mut client = init("initialize_params_did_config_change.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "import * as a from \"http://localhost:4545/x/a@\"" - } - }), - ); - client - .write_notification( - "workspace/didChangeConfiguration", - json!({ - "settings": {} - }), - ) - .unwrap(); - let (id, method, _) = client.read_request::().unwrap(); - assert_eq!(method, "workspace/configuration"); - client - .write_response( - id, - json!([{ - "enable": true, - "codeLens": { - "implementations": true, - "references": true - }, - "importMap": null, - "lint": true, - "suggest": { - "autoImports": true, - "completeFunctionCalls": false, - "names": true, - "paths": true, - "imports": { - "hosts": { - "http://localhost:4545/": true - } - } - }, - "unstable": false - }]), - ) - .unwrap(); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/completion", - json!({ - "textDocument": { - "uri": "file:///a/file.ts" - }, - "position": { - "line": 0, - "character": 46 - }, - "context": { - "triggerKind": 2, - "triggerCharacter": "@" - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - if let Some(lsp::CompletionResponse::List(list)) = maybe_res { - assert!(!list.is_incomplete); - assert_eq!(list.items.len(), 3); - } else { - panic!("unexpected response"); - } - let (maybe_res, maybe_err) = client - .write_request( - "completionItem/resolve", - load_fixture("completion_resolve_params_registry.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("completion_resolve_response_registry.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_workspace_symbol() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "export class A {\n fieldA: string;\n fieldB: string;\n}\n", - } - }), - ); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file_01.ts", - "languageId": "typescript", - "version": 1, - "text": "export class B {\n fieldC: string;\n fieldD: string;\n}\n", - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "workspace/symbol", - json!({ - "query": "field" - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!([ - { - "name": "fieldA", - "kind": 8, - "location": { - "uri": "file:///a/file.ts", - "range": { - "start": { - "line": 1, - "character": 2 - }, - "end": { - "line": 1, - "character": 17 - } - } - }, - "containerName": "A" - }, - { - "name": "fieldB", - "kind": 8, - "location": { - "uri": "file:///a/file.ts", - "range": { - "start": { - "line": 2, - "character": 2 - }, - "end": { - "line": 2, - "character": 17 - } - } - }, - "containerName": "A" - }, - { - "name": "fieldC", - "kind": 8, - "location": { - "uri": "file:///a/file_01.ts", - "range": { - "start": { - "line": 1, - "character": 2 - }, - "end": { - "line": 1, - "character": 17 - } - } - }, - "containerName": "B" - }, - { - "name": "fieldD", - "kind": 8, - "location": { - "uri": "file:///a/file_01.ts", - "range": { - "start": { - "line": 2, - "character": 2 - }, - "end": { - "line": 2, - "character": 17 - } - } - }, - "containerName": "B" - } - ])) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_code_actions_ignore_lint() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": "let message = 'Hello, Deno!';\nconsole.log(message);\n" - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeAction", - load_fixture("code_action_ignore_lint_params.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_action_ignore_lint_response.json")) - ); - shutdown(&mut client); -} - -/// This test exercises updating an existing deno-lint-ignore-file comment. -#[test] -fn lsp_code_actions_update_ignore_lint() { - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.ts", - "languageId": "typescript", - "version": 1, - "text": -"#!/usr/bin/env -S deno run -// deno-lint-ignore-file camelcase -let snake_case = 'Hello, Deno!'; -console.log(snake_case); -", - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request( - "textDocument/codeAction", - load_fixture("code_action_update_ignore_lint_params.json"), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(load_fixture("code_action_update_ignore_lint_response.json")) - ); - shutdown(&mut client); -} - -#[test] -fn lsp_lint_with_config() { - let temp_dir = TempDir::new(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); - let deno_lint_jsonc = - serde_json::to_vec_pretty(&load_fixture("deno.lint.jsonc")).unwrap(); - fs::write(temp_dir.path().join("deno.lint.jsonc"), deno_lint_jsonc).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!("./deno.lint.jsonc")); - params.initialization_options = Some(Value::Object(map)); - } - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - let mut session = TestSession::from_client(client); - - let diagnostics = session.did_open(load_fixture("did_open_lint.json")); - let diagnostics = diagnostics.viewed(); - assert_eq!(diagnostics.len(), 1); - assert_eq!( - diagnostics[0].code, - Some(lsp::NumberOrString::String("ban-untagged-todo".to_string())) - ); - session.shutdown_and_exit(); -} - -#[test] -fn lsp_lint_exclude_with_config() { - let temp_dir = TempDir::new(); - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); - let deno_lint_jsonc = - serde_json::to_vec_pretty(&load_fixture("deno.lint.exclude.jsonc")) - .unwrap(); - fs::write(temp_dir.path().join("deno.lint.jsonc"), deno_lint_jsonc).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!("./deno.lint.jsonc")); - params.initialization_options = Some(Value::Object(map)); - } - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - - let diagnostics = did_open( - &mut client, - json!({ - "textDocument": { - "uri": ModuleSpecifier::from_file_path(temp_dir.path().join("ignored.ts")).unwrap().to_string(), - "languageId": "typescript", - "version": 1, - "text": "// TODO: fixme\nexport async function non_camel_case() {\nconsole.log(\"finished!\")\n}" - } - }), - ); - let diagnostics = diagnostics - .into_iter() - .flat_map(|x| x.diagnostics) - .collect::>(); - assert_eq!(diagnostics, Vec::new()); - shutdown(&mut client); -} - -#[test] -fn lsp_jsx_import_source_pragma() { - let _g = http_server(); - let mut client = init("initialize_params.json"); - did_open( - &mut client, - json!({ - "textDocument": { - "uri": "file:///a/file.tsx", - "languageId": "typescriptreact", - "version": 1, - "text": -"/** @jsxImportSource http://localhost:4545/jsx */ - -function A() { - return \"hello\"; -} - -export function B() { - return ; -} -", - } - }), - ); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "deno/cache", - json!({ - "referrer": { - "uri": "file:///a/file.tsx", - }, - "uris": [ - { - "uri": "http://127.0.0.1:4545/jsx/jsx-runtime", - } - ], - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let (maybe_res, maybe_err) = client - .write_request::<_, _, Value>( - "textDocument/hover", - json!({ - "textDocument": { - "uri": "file:///a/file.tsx" - }, - "position": { - "line": 0, - "character": 25 - } - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert_eq!( - maybe_res, - Some(json!({ - "contents": { - "kind": "markdown", - "value": "**Resolved Dependency**\n\n**Code**: http​://localhost:4545/jsx/jsx-runtime\n", - }, - "range": { - "start": { - "line": 0, - "character": 21 - }, - "end": { - "line": 0, - "character": 46 - } - } - })) - ); - shutdown(&mut client); -} - -#[derive(Debug, Clone, Deserialize, PartialEq)] -#[serde(rename_all = "camelCase")] -struct TestData { - id: String, - label: String, - steps: Option>, - range: Option, -} - -#[derive(Debug, Deserialize, PartialEq)] -#[serde(rename_all = "camelCase")] -enum TestModuleNotificationKind { - Insert, - Replace, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -struct TestModuleNotificationParams { - text_document: lsp::TextDocumentIdentifier, - kind: TestModuleNotificationKind, - label: String, - tests: Vec, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -struct EnqueuedTestModule { - text_document: lsp::TextDocumentIdentifier, - ids: Vec, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -struct TestRunResponseParams { - enqueued: Vec, -} - -#[test] -fn lsp_testing_api() { - let mut params: lsp::InitializeParams = - serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); - let temp_dir = TempDir::new(); - - let root_specifier = - ensure_directory_specifier(Url::from_file_path(temp_dir.path()).unwrap()); - - let module_path = temp_dir.path().join("./test.ts"); - let specifier = ModuleSpecifier::from_file_path(&module_path).unwrap(); - let contents = r#" -Deno.test({ - name: "test a", - fn() { - console.log("test a"); - } -}); -"#; - fs::write(&module_path, contents).unwrap(); - fs::write(temp_dir.path().join("./deno.jsonc"), r#"{}"#).unwrap(); - - params.root_uri = Some(root_specifier); - - let deno_exe = deno_exe_path(); - let mut client = LspClient::new(&deno_exe, false).unwrap(); - client - .write_request::<_, _, Value>("initialize", params) - .unwrap(); - - client.write_notification("initialized", json!({})).unwrap(); - - client - .write_notification( - "textDocument/didOpen", - json!({ - "textDocument": { - "uri": specifier, - "languageId": "typescript", - "version": 1, - "text": contents, - } - }), - ) - .unwrap(); - - handle_configuration_request( - &mut client, - json!([{ - "enable": true, - "codeLens": { - "test": true - } - }]), - ); - - for _ in 0..4 { - let result = client.read_notification::(); - assert!(result.is_ok()); - let (method, notification) = result.unwrap(); - if method.as_str() == "deno/testModule" { - let params: TestModuleNotificationParams = - serde_json::from_value(notification.unwrap()).unwrap(); - assert_eq!(params.text_document.uri, specifier); - assert_eq!(params.kind, TestModuleNotificationKind::Replace); - assert_eq!(params.label, "test.ts"); - assert_eq!(params.tests.len(), 1); - let test = ¶ms.tests[0]; - assert_eq!(test.label, "test a"); - assert!(test.steps.is_none()); - assert_eq!( - test.range, - Some(lsp::Range { - start: lsp::Position { - line: 1, - character: 5, - }, - end: lsp::Position { - line: 1, - character: 9, - } - }) - ); - } - } - - let (maybe_res, maybe_err) = client - .write_request::<_, _, TestRunResponseParams>( - "deno/testRun", - json!({ - "id": 1, - "kind": "run", - }), - ) - .unwrap(); - assert!(maybe_err.is_none()); - assert!(maybe_res.is_some()); - let res = maybe_res.unwrap(); - assert_eq!(res.enqueued.len(), 1); - assert_eq!(res.enqueued[0].text_document.uri, specifier); - assert_eq!(res.enqueued[0].ids.len(), 1); - let id = res.enqueued[0].ids[0].clone(); - - let res = client.read_notification::(); - assert!(res.is_ok()); - let (method, notification) = res.unwrap(); - assert_eq!(method, "deno/testRunProgress"); - assert_eq!( - notification, - Some(json!({ - "id": 1, - "message": { - "type": "started", - "test": { - "textDocument": { - "uri": specifier, - }, - "id": id, - }, - } - })) - ); - - let res = client.read_notification::(); - assert!(res.is_ok()); - let (method, notification) = res.unwrap(); - assert_eq!(method, "deno/testRunProgress"); - let notification_value = notification - .as_ref() - .unwrap() - .as_object() - .unwrap() - .get("message") - .unwrap() - .as_object() - .unwrap() - .get("value") - .unwrap() - .as_str() - .unwrap(); - // deno test's output capturing flushes with a zero-width space in order to - // synchronize the output pipes. Occassionally this zero width space - // might end up in the output so strip it from the output comparison here. - assert_eq!(notification_value.replace('\u{200B}', ""), "test a\r\n"); - assert_eq!( - notification, - Some(json!({ - "id": 1, - "message": { - "type": "output", - "value": notification_value, - "test": { - "textDocument": { - "uri": specifier, - }, - "id": id, - }, - } - })) - ); - - let res = client.read_notification::(); - assert!(res.is_ok()); - let (method, notification) = res.unwrap(); - assert_eq!(method, "deno/testRunProgress"); - let notification = notification.unwrap(); - let obj = notification.as_object().unwrap(); - assert_eq!(obj.get("id"), Some(&json!(1))); - let message = obj.get("message").unwrap().as_object().unwrap(); - match message.get("type").and_then(|v| v.as_str()) { - Some("passed") => { - assert_eq!( - message.get("test"), - Some(&json!({ - "textDocument": { - "uri": specifier - }, - "id": id, - })) - ); - assert!(message.contains_key("duration")); - - let res = client.read_notification::(); - assert!(res.is_ok()); - let (method, notification) = res.unwrap(); - assert_eq!(method, "deno/testRunProgress"); - assert_eq!( - notification, - Some(json!({ - "id": 1, - "message": { - "type": "end", - } - })) - ); - } - // sometimes on windows, the messages come out of order, but it actually is - // working, so if we do get the end before the passed, we will simply let - // the test pass - Some("end") => (), - _ => panic!("unexpected message {}", json!(notification)), - } - - shutdown(&mut client); -} diff --git a/cli/tests/integration/mod.rs b/cli/tests/integration/mod.rs index 373d04e706..00031a6363 100644 --- a/cli/tests/integration/mod.rs +++ b/cli/tests/integration/mod.rs @@ -1,7 +1,5 @@ // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. -use test_util as util; - #[macro_export] macro_rules! itest( ($name:ident {$( $key:ident: $value:expr,)*}) => { @@ -31,96 +29,3 @@ macro_rules! itest_flaky( } } ); - -// These files have `_tests.rs` suffix to make it easier to tell which file is -// the test (ex. `lint_tests.rs`) and which is the implementation (ex. `lint.rs`) -// when both are open, especially for two tabs in VS Code - -#[path = "bench_tests.rs"] -mod bench; -#[path = "bundle_tests.rs"] -mod bundle; -#[path = "cache_tests.rs"] -mod cache; -#[path = "cert_tests.rs"] -mod cert; -#[path = "check_tests.rs"] -mod check; -#[path = "compile_tests.rs"] -mod compile; -#[path = "coverage_tests.rs"] -mod coverage; -#[path = "doc_tests.rs"] -mod doc; -#[path = "eval_tests.rs"] -mod eval; -#[path = "flags_tests.rs"] -mod flags; -#[path = "fmt_tests.rs"] -mod fmt; -#[path = "info_tests.rs"] -mod info; -#[path = "init_tests.rs"] -mod init; -#[path = "inspector_tests.rs"] -mod inspector; -#[path = "install_tests.rs"] -mod install; -#[path = "lint_tests.rs"] -mod lint; -#[path = "lsp_tests.rs"] -mod lsp; -#[path = "npm_tests.rs"] -mod npm; -#[path = "repl_tests.rs"] -mod repl; -#[path = "run_tests.rs"] -mod run; -#[path = "task_tests.rs"] -mod task; -#[path = "test_tests.rs"] -mod test; -#[path = "upgrade_tests.rs"] -mod upgrade; -#[path = "vendor_tests.rs"] -mod vendor; -#[path = "watcher_tests.rs"] -mod watcher; -#[path = "worker_tests.rs"] -mod worker; - -#[test] -fn js_unit_tests_lint() { - let status = util::deno_cmd() - .arg("lint") - .arg("--unstable") - .arg(util::tests_path().join("unit")) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); -} - -#[test] -fn js_unit_tests() { - let _g = util::http_server(); - - // Note that the unit tests are not safe for concurrency and must be run with a concurrency limit - // of one because there are some chdir tests in there. - // TODO(caspervonb) split these tests into two groups: parallel and serial. - let mut deno = util::deno_cmd() - .current_dir(util::root_path()) - .arg("test") - .arg("--unstable") - .arg("--location=http://js-unit-tests/foo/bar") - .arg("--no-prompt") - .arg("-A") - .arg(util::tests_path().join("unit")) - .spawn() - .expect("failed to spawn script"); - - let status = deno.wait().expect("failed to wait for the child process"); - assert_eq!(Some(0), status.code()); - assert!(status.success()); -} diff --git a/cli/tests/integration/npm_tests.rs b/cli/tests/integration/npm_tests.rs deleted file mode 100644 index 288500ce44..0000000000 --- a/cli/tests/integration/npm_tests.rs +++ /dev/null @@ -1,1521 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use pretty_assertions::assert_eq; -use std::process::Stdio; -use test_util as util; -use util::assert_contains; -use util::http_server; - -// NOTE: See how to make test npm packages at ../testdata/npm/README.md - -itest!(esm_module { - args: "run --allow-read --allow-env npm/esm/main.js", - output: "npm/esm/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(esm_module_eval { - args_vec: vec![ - "eval", - "import chalk from 'npm:chalk@5'; console.log(chalk.green('chalk esm loads'));", - ], - output: "npm/esm/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(esm_module_deno_test { - args: "test --allow-read --allow-env --unstable npm/esm/test.js", - output: "npm/esm/test.out", - envs: env_vars(), - http_server: true, -}); - -itest!(esm_import_cjs_default { - args: "run --allow-read --allow-env --unstable --quiet --check=all npm/esm_import_cjs_default/main.ts", - output: "npm/esm_import_cjs_default/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(cjs_with_deps { - args: "run --allow-read --allow-env npm/cjs_with_deps/main.js", - output: "npm/cjs_with_deps/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(cjs_sub_path { - args: "run --allow-read npm/cjs_sub_path/main.js", - output: "npm/cjs_sub_path/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(cjs_local_global_decls { - args: "run --allow-read npm/cjs_local_global_decls/main.ts", - output: "npm/cjs_local_global_decls/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(cjs_reexport_collision { - args: "run -A --quiet npm/cjs_reexport_collision/main.ts", - output: "npm/cjs_reexport_collision/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(cjs_this_in_exports { - args: "run --allow-read --quiet npm/cjs_this_in_exports/main.js", - output: "npm/cjs_this_in_exports/main.out", - envs: env_vars(), - http_server: true, - exit_code: 1, -}); - -itest!(translate_cjs_to_esm { - args: "run -A --quiet npm/translate_cjs_to_esm/main.js", - output: "npm/translate_cjs_to_esm/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(compare_globals { - args: "run --allow-read --unstable --check=all npm/compare_globals/main.ts", - output: "npm/compare_globals/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(conditional_exports { - args: "run --allow-read npm/conditional_exports/main.js", - output: "npm/conditional_exports/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(dual_cjs_esm { - args: "run -A --quiet npm/dual_cjs_esm/main.ts", - output: "npm/dual_cjs_esm/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(child_process_fork_test { - args: "run -A --quiet npm/child_process_fork_test/main.ts", - output: "npm/child_process_fork_test/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(cjs_module_export_assignment { - args: "run -A --unstable --quiet --check=all npm/cjs_module_export_assignment/main.ts", - output: "npm/cjs_module_export_assignment/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(cjs_module_export_assignment_number { - args: "run -A --unstable --quiet --check=all npm/cjs_module_export_assignment_number/main.ts", - output: "npm/cjs_module_export_assignment_number/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(mixed_case_package_name_global_dir { - args: "run npm/mixed_case_package_name/global.ts", - output: "npm/mixed_case_package_name/global.out", - exit_code: 0, - envs: env_vars(), - http_server: true, -}); - -itest!(mixed_case_package_name_local_dir { - args: - "run --node-modules-dir -A $TESTDATA/npm/mixed_case_package_name/local.ts", - output: "npm/mixed_case_package_name/local.out", - exit_code: 0, - envs: env_vars(), - http_server: true, - temp_cwd: true, -}); - -// FIXME(bartlomieju): npm: specifiers are not handled in dynamic imports -// at the moment -// itest!(dynamic_import { -// args: "run --allow-read --allow-env npm/dynamic_import/main.ts", -// output: "npm/dynamic_import/main.out", -// envs: env_vars(), -// http_server: true, -// }); - -itest!(env_var_re_export_dev { - args: "run --allow-read --allow-env --quiet npm/env_var_re_export/main.js", - output_str: Some("dev\n"), - envs: env_vars(), - http_server: true, -}); - -itest!(env_var_re_export_prod { - args: "run --allow-read --allow-env --quiet npm/env_var_re_export/main.js", - output_str: Some("prod\n"), - envs: { - let mut vars = env_vars(); - vars.push(("NODE_ENV".to_string(), "production".to_string())); - vars - }, - http_server: true, -}); - -itest!(cached_only { - args: "run --cached-only npm/cached_only/main.ts", - output: "npm/cached_only/main.out", - envs: env_vars(), - exit_code: 1, -}); - -itest!(import_map { - args: "run --allow-read --allow-env --import-map npm/import_map/import_map.json npm/import_map/main.js", - output: "npm/import_map/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(lock_file { - args: "run --allow-read --allow-env --lock npm/lock_file/lock.json npm/lock_file/main.js", - output: "npm/lock_file/main.out", - envs: env_vars(), - http_server: true, - exit_code: 10, -}); - -itest!(sub_paths { - args: "run -A --quiet npm/sub_paths/main.jsx", - output: "npm/sub_paths/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(remote_npm_specifier { - args: "run --quiet npm/remote_npm_specifier/main.ts", - output: "npm/remote_npm_specifier/main.out", - envs: env_vars(), - http_server: true, - exit_code: 1, -}); - -itest!(tarball_with_global_header { - args: "run -A --quiet npm/tarball_with_global_header/main.js", - output: "npm/tarball_with_global_header/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(nonexistent_file { - args: "run -A --quiet npm/nonexistent_file/main.js", - output: "npm/nonexistent_file/main.out", - envs: env_vars(), - http_server: true, - exit_code: 1, -}); - -itest!(invalid_package_name { - args: "run -A --quiet npm/invalid_package_name/main.js", - output: "npm/invalid_package_name/main.out", - envs: env_vars(), - exit_code: 1, -}); - -itest!(require_json { - args: "run -A --quiet npm/require_json/main.js", - output: "npm/require_json/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(error_version_after_subpath { - args: "run -A --quiet npm/error_version_after_subpath/main.js", - output: "npm/error_version_after_subpath/main.out", - envs: env_vars(), - http_server: true, - exit_code: 1, -}); - -itest!(deno_cache { - args: "cache --reload npm:chalk npm:mkdirp", - output: "npm/deno_cache.out", - envs: env_vars(), - http_server: true, -}); - -itest!(check_all { - args: "check --remote npm/check_errors/main.ts", - output: "npm/check_errors/main_all.out", - envs: env_vars(), - http_server: true, - exit_code: 1, -}); - -itest!(check_local { - args: "check npm/check_errors/main.ts", - output: "npm/check_errors/main_local.out", - envs: env_vars(), - http_server: true, - exit_code: 1, -}); - -itest!(types { - args: "check --quiet npm/types/main.ts", - output: "npm/types/main.out", - envs: env_vars(), - http_server: true, - exit_code: 1, -}); - -itest!(types_ambient_module { - args: "check --quiet npm/types_ambient_module/main.ts", - output: "npm/types_ambient_module/main.out", - envs: env_vars(), - http_server: true, - exit_code: 1, -}); - -itest!(types_ambient_module_import_map { - args: "check --quiet --import-map=npm/types_ambient_module/import_map.json npm/types_ambient_module/main_import_map.ts", - output: "npm/types_ambient_module/main_import_map.out", - envs: env_vars(), - http_server: true, - exit_code: 1, -}); - -itest!(no_types_in_conditional_exports { - args: "run --check --unstable npm/no_types_in_conditional_exports/main.ts", - output: "npm/no_types_in_conditional_exports/main.out", - exit_code: 0, - envs: env_vars(), - http_server: true, -}); - -itest!(types_entry_value_not_exists { - args: "run --check=all npm/types_entry_value_not_exists/main.ts", - output: "npm/types_entry_value_not_exists/main.out", - envs: env_vars(), - http_server: true, - exit_code: 0, -}); - -itest!(types_no_types_entry { - args: "run --check=all npm/types_no_types_entry/main.ts", - output: "npm/types_no_types_entry/main.out", - envs: env_vars(), - http_server: true, - exit_code: 0, -}); - -itest!(typescript_file_in_package { - args: "run npm/typescript_file_in_package/main.ts", - output: "npm/typescript_file_in_package/main.out", - envs: env_vars(), - http_server: true, - exit_code: 1, -}); - -#[test] -fn parallel_downloading() { - let (out, _err) = util::run_and_collect_output_with_args( - true, - vec![ - "run", - "--allow-read", - "--allow-env", - "npm/cjs_with_deps/main.js", - ], - None, - // don't use the sync env var - Some(env_vars_no_sync_download()), - true, - ); - assert!(out.contains("chalk cjs loads")); -} - -#[test] -fn cached_only_after_first_run() { - let _server = http_server(); - - let deno_dir = util::new_deno_dir(); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("npm/cached_only_after_first_run/main1.ts") - .env("NO_COLOR", "1") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - assert_contains!(stderr, "Download"); - assert_contains!(stdout, "createChalk: chalk"); - assert!(output.status.success()); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("--cached-only") - .arg("npm/cached_only_after_first_run/main2.ts") - .env("NO_COLOR", "1") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - assert_contains!( - stderr, - "An npm specifier not found in cache: \"ansi-styles\", --cached-only is specified." - ); - assert!(stdout.is_empty()); - assert!(!output.status.success()); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("--cached-only") - .arg("npm/cached_only_after_first_run/main1.ts") - .env("NO_COLOR", "1") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - - let output = deno.wait_with_output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - assert!(output.status.success()); - assert!(stderr.is_empty()); - assert_contains!(stdout, "createChalk: chalk"); -} - -#[test] -fn reload_flag() { - let _server = http_server(); - - let deno_dir = util::new_deno_dir(); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("npm/reload/main.ts") - .env("NO_COLOR", "1") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - assert_contains!(stderr, "Download"); - assert_contains!(stdout, "createChalk: chalk"); - assert!(output.status.success()); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("--reload") - .arg("npm/reload/main.ts") - .env("NO_COLOR", "1") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - assert_contains!(stderr, "Download"); - assert_contains!(stdout, "createChalk: chalk"); - assert!(output.status.success()); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("--reload=npm:") - .arg("npm/reload/main.ts") - .env("NO_COLOR", "1") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - assert_contains!(stderr, "Download"); - assert_contains!(stdout, "createChalk: chalk"); - assert!(output.status.success()); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("--reload=npm:chalk") - .arg("npm/reload/main.ts") - .env("NO_COLOR", "1") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - assert_contains!(stderr, "Download"); - assert_contains!(stdout, "createChalk: chalk"); - assert!(output.status.success()); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("--reload=npm:foobar") - .arg("npm/reload/main.ts") - .env("NO_COLOR", "1") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - assert!(stderr.is_empty()); - assert_contains!(stdout, "createChalk: chalk"); - assert!(output.status.success()); -} - -#[test] -fn no_npm_after_first_run() { - let _server = http_server(); - - let deno_dir = util::new_deno_dir(); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("--no-npm") - .arg("npm/no_npm_after_first_run/main1.ts") - .env("NO_COLOR", "1") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - assert_contains!( - stderr, - "Following npm specifiers were requested: \"chalk@5\"; but --no-npm is specified." - ); - assert!(stdout.is_empty()); - assert!(!output.status.success()); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("npm/no_npm_after_first_run/main1.ts") - .env("NO_COLOR", "1") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - assert_contains!(stderr, "Download"); - assert_contains!(stdout, "createChalk: chalk"); - assert!(output.status.success()); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("--no-npm") - .arg("npm/no_npm_after_first_run/main1.ts") - .env("NO_COLOR", "1") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - assert_contains!( - stderr, - "Following npm specifiers were requested: \"chalk@5\"; but --no-npm is specified." - ); - assert!(stdout.is_empty()); - assert!(!output.status.success()); -} - -#[test] -fn deno_run_cjs_module() { - let _server = http_server(); - - let deno_dir = util::new_deno_dir(); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(deno_dir.path()) - .arg("run") - .arg("--allow-read") - .arg("--allow-env") - .arg("--allow-write") - .arg("npm:mkdirp@1.0.4") - .arg("test_dir") - .env("NO_COLOR", "1") - .envs(env_vars()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert!(output.status.success()); - - assert!(deno_dir.path().join("test_dir").exists()); -} - -itest!(deno_run_cowsay { - args: "run -A --quiet npm:cowsay@1.5.0 Hello", - output: "npm/deno_run_cowsay.out", - envs: env_vars_no_sync_download(), - http_server: true, -}); - -itest!(deno_run_cowsay_explicit { - args: "run -A --quiet npm:cowsay@1.5.0/cowsay Hello", - output: "npm/deno_run_cowsay.out", - envs: env_vars_no_sync_download(), - http_server: true, -}); - -itest!(deno_run_cowthink { - args: "run -A --quiet npm:cowsay@1.5.0/cowthink Hello", - output: "npm/deno_run_cowthink.out", - envs: env_vars_no_sync_download(), - http_server: true, -}); - -itest!(deno_run_bin_esm { - args: "run -A --quiet npm:@denotest/bin/cli-esm this is a test", - output: "npm/deno_run_esm.out", - envs: env_vars(), - http_server: true, -}); - -itest!(deno_run_bin_no_ext { - args: "run -A --quiet npm:@denotest/bin/cli-no-ext this is a test", - output: "npm/deno_run_no_ext.out", - envs: env_vars(), - http_server: true, -}); - -itest!(deno_run_bin_cjs { - args: "run -A --quiet npm:@denotest/bin/cli-cjs this is a test", - output: "npm/deno_run_cjs.out", - envs: env_vars(), - http_server: true, -}); - -itest!(deno_run_non_existent { - args: "run npm:mkdirp@0.5.125", - output: "npm/deno_run_non_existent.out", - envs: env_vars(), - http_server: true, - exit_code: 1, -}); - -itest!(builtin_module_module { - args: "run --allow-read --quiet npm/builtin_module_module/main.js", - output: "npm/builtin_module_module/main.out", - envs: env_vars(), - http_server: true, -}); - -itest!(node_modules_dir_require_added_node_modules_folder { - args: - "run --node-modules-dir -A --quiet $TESTDATA/npm/require_added_nm_folder/main.js", - output: "npm/require_added_nm_folder/main.out", - envs: env_vars(), - http_server: true, - exit_code: 0, - temp_cwd: true, -}); - -itest!(node_modules_dir_with_deps { - args: "run --allow-read --allow-env --node-modules-dir $TESTDATA/npm/cjs_with_deps/main.js", - output: "npm/cjs_with_deps/main.out", - envs: env_vars(), - http_server: true, - temp_cwd: true, -}); - -itest!(node_modules_dir_yargs { - args: "run --allow-read --allow-env --node-modules-dir $TESTDATA/npm/cjs_yargs/main.js", - output: "npm/cjs_yargs/main.out", - envs: env_vars(), - http_server: true, - temp_cwd: true, -}); - -#[test] -fn node_modules_dir_cache() { - let _server = http_server(); - - let deno_dir = util::new_deno_dir(); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(deno_dir.path()) - .arg("cache") - .arg("--node-modules-dir") - .arg("--quiet") - .arg(util::testdata_path().join("npm/dual_cjs_esm/main.ts")) - .envs(env_vars()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert!(output.status.success()); - - let node_modules = deno_dir.path().join("node_modules"); - assert!(node_modules - .join( - ".deno/@denotest+dual-cjs-esm@1.0.0/node_modules/@denotest/dual-cjs-esm" - ) - .exists()); - assert!(node_modules.join("@denotest/dual-cjs-esm").exists()); - - // now try deleting the folder with the package source in the npm cache dir - let package_global_cache_dir = deno_dir - .path() - .join("npm") - .join("localhost_4545") - .join("npm") - .join("registry") - .join("@denotest") - .join("dual-cjs-esm") - .join("1.0.0"); - assert!(package_global_cache_dir.exists()); - std::fs::remove_dir_all(&package_global_cache_dir).unwrap(); - - // run the output, and it shouldn't bother recreating the directory - // because it already has everything cached locally in the node_modules folder - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(deno_dir.path()) - .arg("run") - .arg("--node-modules-dir") - .arg("--quiet") - .arg("-A") - .arg(util::testdata_path().join("npm/dual_cjs_esm/main.ts")) - .envs(env_vars()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert!(output.status.success()); - - // this won't exist, but actually the parent directory - // will because it still re-downloads the registry information - assert!(!package_global_cache_dir.exists()); -} - -#[test] -fn ensure_registry_files_local() { - // ensures the registry files all point at local tarballs - let registry_dir_path = util::testdata_path().join("npm").join("registry"); - for entry in std::fs::read_dir(®istry_dir_path).unwrap() { - let entry = entry.unwrap(); - if entry.metadata().unwrap().is_dir() { - let registry_json_path = registry_dir_path - .join(entry.file_name()) - .join("registry.json"); - if registry_json_path.exists() { - let file_text = std::fs::read_to_string(®istry_json_path).unwrap(); - if file_text.contains("https://registry.npmjs.org/") { - panic!( - "file {} contained a reference to the npm registry", - registry_json_path.display(), - ); - } - } - } - } -} - -itest!(compile_errors { - args: "compile -A --quiet npm/cached_only/main.ts", - output_str: Some("error: npm specifiers have not yet been implemented for this sub command (https://github.com/denoland/deno/issues/15960). Found: npm:chalk@5\n"), - exit_code: 1, - envs: env_vars(), - http_server: true, -}); - -itest!(bundle_errors { - args: "bundle --quiet npm/esm/main.js", - output_str: Some("error: npm specifiers have not yet been implemented for this sub command (https://github.com/denoland/deno/issues/15960). Found: npm:chalk@5\n"), - exit_code: 1, - envs: env_vars(), - http_server: true, -}); - -itest!(info_chalk_display { - args: "info --quiet npm/cjs_with_deps/main.js", - output: "npm/cjs_with_deps/main_info.out", - exit_code: 0, - envs: env_vars(), - http_server: true, -}); - -itest!(info_chalk_display_node_modules_dir { - args: "info --quiet --node-modules-dir $TESTDATA/npm/cjs_with_deps/main.js", - output: "npm/cjs_with_deps/main_info.out", - exit_code: 0, - envs: env_vars(), - http_server: true, - temp_cwd: true, -}); - -itest!(info_chalk_json { - args: "info --quiet --json npm/cjs_with_deps/main.js", - output: "npm/cjs_with_deps/main_info_json.out", - exit_code: 0, - envs: env_vars(), - http_server: true, -}); - -itest!(info_chalk_json_node_modules_dir { - args: - "info --quiet --node-modules-dir --json $TESTDATA/npm/cjs_with_deps/main.js", - output: "npm/cjs_with_deps/main_info_json.out", - exit_code: 0, - envs: env_vars(), - http_server: true, - temp_cwd: true, -}); - -itest!(info_cli_chalk_display { - args: "info --quiet npm:chalk@4", - output: "npm/info/chalk.out", - exit_code: 0, - envs: env_vars(), - http_server: true, -}); - -itest!(info_cli_chalk_json { - args: "info --quiet --json npm:chalk@4", - output: "npm/info/chalk_json.out", - exit_code: 0, - envs: env_vars(), - http_server: true, -}); - -#[test] -fn lock_file_missing_top_level_package() { - let _server = http_server(); - - let deno_dir = util::new_deno_dir(); - let temp_dir = util::TempDir::new(); - - // write empty config file - temp_dir.write("deno.json", "{}"); - - // Lock file that is automatically picked up has been intentionally broken, - // by removing "cowsay" package from it. This test ensures that npm resolver - // snapshot can be successfully hydrated in such situation - let lock_file_content = r#"{ - "version": "2", - "remote": {}, - "npm": { - "specifiers": { "cowsay": "cowsay@1.5.0" }, - "packages": { - "ansi-regex@3.0.1": { - "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", - "dependencies": {} - }, - "ansi-regex@5.0.1": { - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dependencies": {} - }, - "ansi-styles@4.3.0": { - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dependencies": { "color-convert": "color-convert@2.0.1" } - }, - "camelcase@5.3.1": { - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dependencies": {} - }, - "cliui@6.0.0": { - "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", - "dependencies": { - "string-width": "string-width@4.2.3", - "strip-ansi": "strip-ansi@6.0.1", - "wrap-ansi": "wrap-ansi@6.2.0" - } - }, - "color-convert@2.0.1": { - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dependencies": { "color-name": "color-name@1.1.4" } - }, - "color-name@1.1.4": { - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dependencies": {} - }, - "decamelize@1.2.0": { - "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", - "dependencies": {} - }, - "emoji-regex@8.0.0": { - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dependencies": {} - }, - "find-up@4.1.0": { - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dependencies": { - "locate-path": "locate-path@5.0.0", - "path-exists": "path-exists@4.0.0" - } - }, - "get-caller-file@2.0.5": { - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dependencies": {} - }, - "get-stdin@8.0.0": { - "integrity": "sha512-sY22aA6xchAzprjyqmSEQv4UbAAzRN0L2dQB0NlN5acTTK9Don6nhoc3eAbUnpZiCANAMfd/+40kVdKfFygohg==", - "dependencies": {} - }, - "is-fullwidth-code-point@2.0.0": { - "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", - "dependencies": {} - }, - "is-fullwidth-code-point@3.0.0": { - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dependencies": {} - }, - "locate-path@5.0.0": { - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dependencies": { "p-locate": "p-locate@4.1.0" } - }, - "p-limit@2.3.0": { - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dependencies": { "p-try": "p-try@2.2.0" } - }, - "p-locate@4.1.0": { - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dependencies": { "p-limit": "p-limit@2.3.0" } - }, - "p-try@2.2.0": { - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dependencies": {} - }, - "path-exists@4.0.0": { - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dependencies": {} - }, - "require-directory@2.1.1": { - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dependencies": {} - }, - "require-main-filename@2.0.0": { - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", - "dependencies": {} - }, - "set-blocking@2.0.0": { - "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", - "dependencies": {} - }, - "string-width@2.1.1": { - "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", - "dependencies": { - "is-fullwidth-code-point": "is-fullwidth-code-point@2.0.0", - "strip-ansi": "strip-ansi@4.0.0" - } - }, - "string-width@4.2.3": { - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dependencies": { - "emoji-regex": "emoji-regex@8.0.0", - "is-fullwidth-code-point": "is-fullwidth-code-point@3.0.0", - "strip-ansi": "strip-ansi@6.0.1" - } - }, - "strip-ansi@4.0.0": { - "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==", - "dependencies": { "ansi-regex": "ansi-regex@3.0.1" } - }, - "strip-ansi@6.0.1": { - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dependencies": { "ansi-regex": "ansi-regex@5.0.1" } - }, - "strip-final-newline@2.0.0": { - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dependencies": {} - }, - "which-module@2.0.0": { - "integrity": "sha512-B+enWhmw6cjfVC7kS8Pj9pCrKSc5txArRyaYGe088shv/FGWH+0Rjx/xPgtsWfsUtS27FkP697E4DDhgrgoc0Q==", - "dependencies": {} - }, - "wrap-ansi@6.2.0": { - "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", - "dependencies": { - "ansi-styles": "ansi-styles@4.3.0", - "string-width": "string-width@4.2.3", - "strip-ansi": "strip-ansi@6.0.1" - } - }, - "y18n@4.0.3": { - "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", - "dependencies": {} - }, - "yargs-parser@18.1.3": { - "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", - "dependencies": { - "camelcase": "camelcase@5.3.1", - "decamelize": "decamelize@1.2.0" - } - }, - "yargs@15.4.1": { - "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", - "dependencies": { - "cliui": "cliui@6.0.0", - "decamelize": "decamelize@1.2.0", - "find-up": "find-up@4.1.0", - "get-caller-file": "get-caller-file@2.0.5", - "require-directory": "require-directory@2.1.1", - "require-main-filename": "require-main-filename@2.0.0", - "set-blocking": "set-blocking@2.0.0", - "string-width": "string-width@4.2.3", - "which-module": "which-module@2.0.0", - "y18n": "y18n@4.0.3", - "yargs-parser": "yargs-parser@18.1.3" - } - } - } - } - } - "#; - temp_dir.write("deno.lock", lock_file_content); - let main_contents = r#" - import cowsay from "npm:cowsay"; - console.log(cowsay); - "#; - temp_dir.write("main.ts", main_contents); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(temp_dir.path()) - .arg("run") - .arg("--quiet") - .arg("--lock") - .arg("deno.lock") - .arg("-A") - .arg("main.ts") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert!(!output.status.success()); - - let stderr = String::from_utf8(output.stderr).unwrap(); - assert_eq!( - stderr, - "error: failed reading lockfile 'deno.lock'\n\nCaused by:\n the lockfile is corrupt. You can recreate it with --lock-write\n" - ); -} - -#[test] -fn lock_file_lock_write() { - // https://github.com/denoland/deno/issues/16666 - // Ensure that --lock-write still adds npm packages to the lockfile - let _server = http_server(); - - let deno_dir = util::new_deno_dir(); - let temp_dir = util::TempDir::new(); - - // write empty config file - temp_dir.write("deno.json", "{}"); - - // write a lock file with borked integrity - let lock_file_content = r#"{ - "version": "2", - "remote": {}, - "npm": { - "specifiers": { "cowsay@1.5.0": "cowsay@1.5.0" }, - "packages": { - "ansi-regex@3.0.1": { - "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", - "dependencies": {} - }, - "ansi-regex@5.0.1": { - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dependencies": {} - }, - "ansi-styles@4.3.0": { - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dependencies": { "color-convert": "color-convert@2.0.1" } - }, - "camelcase@5.3.1": { - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dependencies": {} - }, - "cliui@6.0.0": { - "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", - "dependencies": { - "string-width": "string-width@4.2.3", - "strip-ansi": "strip-ansi@6.0.1", - "wrap-ansi": "wrap-ansi@6.2.0" - } - }, - "color-convert@2.0.1": { - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dependencies": { "color-name": "color-name@1.1.4" } - }, - "color-name@1.1.4": { - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dependencies": {} - }, - "cowsay@1.5.0": { - "integrity": "sha512-8Ipzr54Z8zROr/62C8f0PdhQcDusS05gKTS87xxdji8VbWefWly0k8BwGK7+VqamOrkv3eGsCkPtvlHzrhWsCA==", - "dependencies": { - "get-stdin": "get-stdin@8.0.0", - "string-width": "string-width@2.1.1", - "strip-final-newline": "strip-final-newline@2.0.0", - "yargs": "yargs@15.4.1" - } - }, - "decamelize@1.2.0": { - "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", - "dependencies": {} - }, - "emoji-regex@8.0.0": { - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dependencies": {} - }, - "find-up@4.1.0": { - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dependencies": { - "locate-path": "locate-path@5.0.0", - "path-exists": "path-exists@4.0.0" - } - }, - "get-caller-file@2.0.5": { - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dependencies": {} - }, - "get-stdin@8.0.0": { - "integrity": "sha512-sY22aA6xchAzprjyqmSEQv4UbAAzRN0L2dQB0NlN5acTTK9Don6nhoc3eAbUnpZiCANAMfd/+40kVdKfFygohg==", - "dependencies": {} - }, - "is-fullwidth-code-point@2.0.0": { - "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", - "dependencies": {} - }, - "is-fullwidth-code-point@3.0.0": { - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dependencies": {} - }, - "locate-path@5.0.0": { - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dependencies": { "p-locate": "p-locate@4.1.0" } - }, - "p-limit@2.3.0": { - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dependencies": { "p-try": "p-try@2.2.0" } - }, - "p-locate@4.1.0": { - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dependencies": { "p-limit": "p-limit@2.3.0" } - }, - "p-try@2.2.0": { - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dependencies": {} - }, - "path-exists@4.0.0": { - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dependencies": {} - }, - "require-directory@2.1.1": { - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dependencies": {} - }, - "require-main-filename@2.0.0": { - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", - "dependencies": {} - }, - "set-blocking@2.0.0": { - "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", - "dependencies": {} - }, - "string-width@2.1.1": { - "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", - "dependencies": { - "is-fullwidth-code-point": "is-fullwidth-code-point@2.0.0", - "strip-ansi": "strip-ansi@4.0.0" - } - }, - "string-width@4.2.3": { - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dependencies": { - "emoji-regex": "emoji-regex@8.0.0", - "is-fullwidth-code-point": "is-fullwidth-code-point@3.0.0", - "strip-ansi": "strip-ansi@6.0.1" - } - }, - "strip-ansi@4.0.0": { - "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==", - "dependencies": { "ansi-regex": "ansi-regex@3.0.1" } - }, - "strip-ansi@6.0.1": { - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dependencies": { "ansi-regex": "ansi-regex@5.0.1" } - }, - "strip-final-newline@2.0.0": { - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dependencies": {} - }, - "which-module@2.0.0": { - "integrity": "sha512-B+enWhmw6cjfVC7kS8Pj9pCrKSc5txArRyaYGe088shv/FGWH+0Rjx/xPgtsWfsUtS27FkP697E4DDhgrgoc0Q==", - "dependencies": {} - }, - "wrap-ansi@6.2.0": { - "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", - "dependencies": { - "ansi-styles": "ansi-styles@4.3.0", - "string-width": "string-width@4.2.3", - "strip-ansi": "strip-ansi@6.0.1" - } - }, - "y18n@4.0.3": { - "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", - "dependencies": {} - }, - "yargs-parser@18.1.3": { - "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", - "dependencies": { - "camelcase": "camelcase@5.3.1", - "decamelize": "decamelize@1.2.0" - } - }, - "yargs@15.4.1": { - "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", - "dependencies": { - "cliui": "cliui@6.0.0", - "decamelize": "decamelize@1.2.0", - "find-up": "find-up@4.1.0", - "get-caller-file": "get-caller-file@2.0.5", - "require-directory": "require-directory@2.1.1", - "require-main-filename": "require-main-filename@2.0.0", - "set-blocking": "set-blocking@2.0.0", - "string-width": "string-width@4.2.3", - "which-module": "which-module@2.0.0", - "y18n": "y18n@4.0.3", - "yargs-parser": "yargs-parser@18.1.3" - } - } - } - } -} -"#; - temp_dir.write("deno.lock", lock_file_content); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(temp_dir.path()) - .arg("cache") - .arg("--lock-write") - .arg("--quiet") - .arg("npm:cowsay@1.5.0") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert!(output.status.success()); - assert_eq!(output.status.code(), Some(0)); - - let stdout = String::from_utf8(output.stdout).unwrap(); - assert!(stdout.is_empty()); - let stderr = String::from_utf8(output.stderr).unwrap(); - assert!(stderr.is_empty()); - assert_eq!( - lock_file_content, - std::fs::read_to_string(temp_dir.path().join("deno.lock")).unwrap() - ); -} - -#[test] -fn auto_discover_lock_file() { - let _server = http_server(); - - let deno_dir = util::new_deno_dir(); - let temp_dir = util::TempDir::new(); - - // write empty config file - temp_dir.write("deno.json", "{}"); - - // write a lock file with borked integrity - let lock_file_content = r#"{ - "version": "2", - "remote": {}, - "npm": { - "specifiers": { "@denotest/bin": "@denotest/bin@1.0.0" }, - "packages": { - "@denotest/bin@1.0.0": { - "integrity": "sha512-foobar", - "dependencies": {} - } - } - } - }"#; - temp_dir.write("deno.lock", lock_file_content); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(temp_dir.path()) - .arg("run") - .arg("--unstable") - .arg("-A") - .arg("npm:@denotest/bin/cli-esm") - .arg("test") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert!(!output.status.success()); - assert_eq!(output.status.code(), Some(10)); - - let stderr = String::from_utf8(output.stderr).unwrap(); - assert!(stderr.contains( - "Integrity check failed for npm package: \"@denotest/bin@1.0.0\"" - )); -} - -#[test] -fn peer_deps_with_copied_folders_and_lockfile() { - let _server = http_server(); - - let deno_dir = util::new_deno_dir(); - let temp_dir = util::TempDir::new(); - - // write empty config file - temp_dir.write("deno.json", "{}"); - let test_folder_path = test_util::testdata_path() - .join("npm") - .join("peer_deps_with_copied_folders"); - let main_contents = - std::fs::read_to_string(test_folder_path.join("main.ts")).unwrap(); - temp_dir.write("./main.ts", main_contents); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(temp_dir.path()) - .arg("run") - .arg("-A") - .arg("main.ts") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert!(output.status.success()); - - let expected_output = - std::fs::read_to_string(test_folder_path.join("main.out")).unwrap(); - - assert_eq!(String::from_utf8(output.stderr).unwrap(), expected_output); - - assert!(temp_dir.path().join("deno.lock").exists()); - let grandchild_path = deno_dir - .path() - .join("npm") - .join("localhost_4545") - .join("npm") - .join("registry") - .join("@denotest") - .join("peer-dep-test-grandchild"); - assert!(grandchild_path.join("1.0.0").exists()); - assert!(grandchild_path.join("1.0.0_1").exists()); // copy folder, which is hardlinked - - // run again - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(temp_dir.path()) - .arg("run") - .arg("-A") - .arg("main.ts") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!(String::from_utf8(output.stderr).unwrap(), "1\n2\n"); - assert!(output.status.success()); - - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(temp_dir.path()) - .arg("run") - .arg("--reload") - .arg("-A") - .arg("main.ts") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!(String::from_utf8(output.stderr).unwrap(), expected_output); - assert!(output.status.success()); - - // now run with local node modules - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(temp_dir.path()) - .arg("run") - .arg("--node-modules-dir") - .arg("-A") - .arg("main.ts") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!(String::from_utf8(output.stderr).unwrap(), "1\n2\n"); - assert!(output.status.success()); - - let deno_folder = temp_dir.path().join("node_modules").join(".deno"); - assert!(deno_folder - .join("@denotest+peer-dep-test-grandchild@1.0.0") - .exists()); - assert!(deno_folder - .join("@denotest+peer-dep-test-grandchild@1.0.0_1") - .exists()); // copy folder - - // now again run with local node modules - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(temp_dir.path()) - .arg("run") - .arg("--node-modules-dir") - .arg("-A") - .arg("main.ts") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert!(output.status.success()); - assert_eq!(String::from_utf8(output.stderr).unwrap(), "1\n2\n"); - - // now ensure it works with reloading - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(temp_dir.path()) - .arg("run") - .arg("--node-modules-dir") - .arg("--reload") - .arg("-A") - .arg("main.ts") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert!(output.status.success()); - assert_eq!(String::from_utf8(output.stderr).unwrap(), expected_output); - - // now ensure it works with reloading and no lockfile - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(temp_dir.path()) - .arg("run") - .arg("--node-modules-dir") - .arg("--no-lock") - .arg("--reload") - .arg("-A") - .arg("main.ts") - .envs(env_vars()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!(String::from_utf8(output.stderr).unwrap(), expected_output,); - assert!(output.status.success()); -} - -itest!(info_peer_deps { - args: "info --quiet npm/peer_deps_with_copied_folders/main.ts", - output: "npm/peer_deps_with_copied_folders/main_info.out", - exit_code: 0, - envs: env_vars(), - http_server: true, -}); - -itest!(info_peer_deps_json { - args: "info --quiet --json npm/peer_deps_with_copied_folders/main.ts", - output: "npm/peer_deps_with_copied_folders/main_info_json.out", - exit_code: 0, - envs: env_vars(), - http_server: true, -}); - -itest!(create_require { - args: "run --reload npm/create_require/main.ts", - output: "npm/create_require/main.out", - exit_code: 0, - envs: env_vars(), - http_server: true, -}); - -fn env_vars_no_sync_download() -> Vec<(String, String)> { - vec![ - ("DENO_NODE_COMPAT_URL".to_string(), util::std_file_url()), - ("DENO_NPM_REGISTRY".to_string(), util::npm_registry_url()), - ("NO_COLOR".to_string(), "1".to_string()), - ] -} - -fn env_vars() -> Vec<(String, String)> { - let mut env_vars = env_vars_no_sync_download(); - env_vars.push(( - // make downloads determinstic - "DENO_UNSTABLE_NPM_SYNC_DOWNLOAD".to_string(), - "1".to_string(), - )); - env_vars -} diff --git a/cli/tests/integration/repl_tests.rs b/cli/tests/integration/repl_tests.rs deleted file mode 100644 index 44c7ec08ff..0000000000 --- a/cli/tests/integration/repl_tests.rs +++ /dev/null @@ -1,877 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use test_util as util; -use test_util::assert_contains; -use test_util::assert_ends_with; -use test_util::assert_not_contains; - -#[test] -fn pty_multiline() { - util::with_pty(&["repl"], |mut console| { - console.write_line("(\n1 + 2\n)"); - console.write_line("{\nfoo: \"foo\"\n}"); - console.write_line("`\nfoo\n`"); - console.write_line("`\n\\`\n`"); - console.write_line("'{'"); - console.write_line("'('"); - console.write_line("'['"); - console.write_line("/{/"); - console.write_line("/\\(/"); - console.write_line("/\\[/"); - console.write_line("console.log(\"{test1} abc {test2} def {{test3}}\".match(/{([^{].+?)}/));"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_contains!(output, '3'); - assert_contains!(output, "{ foo: \"foo\" }"); - assert_contains!(output, "\"\\nfoo\\n\""); - assert_contains!(output, "\"\\n`\\n\""); - assert_contains!(output, "\"{\""); - assert_contains!(output, "\"(\""); - assert_contains!(output, "\"[\""); - assert_contains!(output, "/{/"); - assert_contains!(output, "/\\(/"); - assert_contains!(output, "/\\[/"); - assert_contains!(output, "[ \"{test1}\", \"test1\" ]"); - }); -} - -#[test] -fn pty_null() { - util::with_pty(&["repl"], |mut console| { - console.write_line("null"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_contains!(output, "null"); - }); -} - -#[test] -fn pty_unpaired_braces() { - util::with_pty(&["repl"], |mut console| { - console.write_line(")"); - console.write_line("]"); - console.write_line("}"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_contains!(output, "Unexpected token `)`"); - assert_contains!(output, "Unexpected token `]`"); - assert_contains!(output, "Unexpected token `}`"); - }); -} - -#[test] -fn pty_bad_input() { - util::with_pty(&["repl"], |mut console| { - console.write_line("'\\u{1f3b5}'[0]"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_contains!(output, "Unterminated string literal"); - }); -} - -#[test] -fn pty_syntax_error_input() { - util::with_pty(&["repl"], |mut console| { - console.write_line("('\\u')"); - console.write_line("'"); - console.write_line("[{'a'}];"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_contains!( - output, - "Bad character escape sequence, expected 4 hex characters" - ); - assert_contains!(output, "Unterminated string constant"); - assert_contains!(output, "Expected a semicolon"); - }); -} - -#[test] -fn pty_complete_symbol() { - util::with_pty(&["repl"], |mut console| { - console.write_line("Symbol.it\t"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_contains!(output, "Symbol(Symbol.iterator)"); - }); -} - -#[test] -fn pty_complete_declarations() { - util::with_pty(&["repl"], |mut console| { - console.write_line("class MyClass {}"); - console.write_line("My\t"); - console.write_line("let myVar;"); - console.write_line("myV\t"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_contains!(output, "> MyClass"); - assert_contains!(output, "> myVar"); - }); -} - -#[test] -fn pty_complete_primitives() { - util::with_pty(&["repl"], |mut console| { - console.write_line("let func = function test(){}"); - console.write_line("func.appl\t"); - console.write_line("let str = ''"); - console.write_line("str.leng\t"); - console.write_line("false.valueO\t"); - console.write_line("5n.valueO\t"); - console.write_line("let num = 5"); - console.write_line("num.toStrin\t"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_contains!(output, "> func.apply"); - assert_contains!(output, "> str.length"); - assert_contains!(output, "> 5n.valueOf"); - assert_contains!(output, "> false.valueOf"); - assert_contains!(output, "> num.toString"); - }); -} - -#[test] -fn pty_complete_expression() { - util::with_pty(&["repl"], |mut console| { - console.write_text("Deno.\t\t"); - console.write_text("y"); - console.write_line(""); - console.write_line("close();"); - let output = console.read_all_output(); - assert_contains!(output, "Display all"); - assert_contains!(output, "core"); - assert_contains!(output, "args"); - assert_contains!(output, "exit"); - assert_contains!(output, "symlink"); - assert_contains!(output, "permissions"); - }); -} - -#[test] -fn pty_complete_imports() { - util::with_pty(&["repl"], |mut console| { - // single quotes - console.write_line("import './run/001_hel\t'"); - // double quotes - console.write_line("import { output } from \"./run/045_out\t\""); - console.write_line("output('testing output');"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_contains!(output, "Hello World"); - assert_contains!( - output, - // on windows, could contain either (it's flaky) - "\ntesting output", - "testing output\u{1b}", - ); - }); - - // ensure when the directory changes that the suggestions come from the cwd - util::with_pty(&["repl"], |mut console| { - console.write_line("Deno.chdir('./subdir');"); - console.write_line("import '../run/001_hel\t'"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_contains!(output, "Hello World"); - }); -} - -#[test] -fn pty_complete_imports_no_panic_empty_specifier() { - // does not panic when tabbing when empty - util::with_pty(&["repl"], |mut console| { - console.write_line("import '\t';"); - console.write_line("close();"); - }); -} - -#[test] -fn pty_ignore_symbols() { - util::with_pty(&["repl"], |mut console| { - console.write_line("Array.Symbol\t"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_contains!(output, "undefined"); - assert_not_contains!( - output, - "Uncaught TypeError: Array.Symbol is not a function" - ); - }); -} - -#[test] -fn pty_assign_global_this() { - util::with_pty(&["repl"], |mut console| { - console.write_line("globalThis = 42;"); - console.write_line("close();"); - - let output = console.read_all_output(); - assert_not_contains!(output, "panicked"); - }); -} - -#[test] -fn pty_emoji() { - // windows was having issues displaying this - util::with_pty(&["repl"], |mut console| { - console.write_line(r#"console.log('\u{1F995}');"#); - console.write_line("close();"); - - let output = console.read_all_output(); - // only one for the output (since input is escaped) - let emoji_count = output.chars().filter(|c| *c == '🦕').count(); - assert_eq!(emoji_count, 1); - }); -} - -#[test] -fn console_log() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["console.log('hello')", "'world'"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "hello\nundefined\n\"world\"\n"); - assert!(err.is_empty()); -} - -#[test] -fn object_literal() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["{}", "{ foo: 'bar' }"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "{}\n{ foo: \"bar\" }\n"); - assert!(err.is_empty()); -} - -#[test] -fn block_expression() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["{};", "{\"\"}"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "undefined\n\"\"\n"); - assert!(err.is_empty()); -} - -#[test] -fn await_resolve() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["await Promise.resolve('done')"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "\"done\"\n"); - assert!(err.is_empty()); -} - -#[test] -fn await_timeout() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["await new Promise((r) => setTimeout(r, 0, 'done'))"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "\"done\"\n"); - assert!(err.is_empty()); -} - -#[test] -fn let_redeclaration() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["let foo = 0;", "foo", "let foo = 1;", "foo"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "undefined\n0\nundefined\n1\n"); - assert!(err.is_empty()); -} - -#[test] -fn repl_cwd() { - let (_out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["Deno.cwd()"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert!(err.is_empty()); -} - -#[test] -fn typescript() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec![ - "function add(a: number, b: number) { return a + b }", - "const result: number = add(1, 2) as number;", - "result", - ]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "undefined\nundefined\n3\n"); - assert!(err.is_empty()); -} - -#[test] -fn typescript_declarations() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec![ - "namespace Test { export enum Values { A, B, C } }", - "Test.Values.A", - "Test.Values.C", - "interface MyInterface { prop: string; }", - "type MyTypeAlias = string;", - ]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - let expected_end_text = "undefined\n0\n2\nundefined\nundefined\n"; - assert_ends_with!(out, expected_end_text); - assert!(err.is_empty()); -} - -#[test] -fn typescript_decorators() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec![ - "function dec(target) { target.prototype.test = () => 2; }", - "@dec class Test {}", - "new Test().test()", - ]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "undefined\n[Function: Test]\n2\n"); - assert!(err.is_empty()); -} - -#[test] -fn eof() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["1 + 2"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "3\n"); - assert!(err.is_empty()); -} - -#[test] -fn strict() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec![ - "let a = {};", - "Object.preventExtensions(a);", - "a.c = 1;", - ]), - None, - false, - ); - assert_contains!( - out, - "Uncaught TypeError: Cannot add property c, object is not extensible" - ); - assert!(err.is_empty()); -} - -#[test] -fn close_command() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["close()", "'ignored'"]), - None, - false, - ); - - assert_not_contains!(out, "ignored"); - assert!(err.is_empty()); -} - -#[test] -fn function() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["Deno.writeFileSync"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "[Function: writeFileSync]\n"); - assert!(err.is_empty()); -} - -#[test] -#[ignore] -fn multiline() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["(\n1 + 2\n)"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "3\n"); - assert!(err.is_empty()); -} - -#[test] -fn import() { - let (out, _) = util::run_and_collect_output( - true, - "repl", - Some(vec!["import('./subdir/auto_print_hello.ts')"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_contains!(out, "hello!\n"); -} - -#[test] -fn import_declarations() { - let (out, _) = util::run_and_collect_output( - true, - "repl", - Some(vec!["import './subdir/auto_print_hello.ts';"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_contains!(out, "hello!\n"); -} - -#[test] -fn exports_stripped() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["export default 5;", "export class Test {}"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_contains!(out, "5\n"); - assert!(err.is_empty()); -} - -#[test] -fn call_eval_unterminated() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["eval('{')"]), - None, - false, - ); - assert_contains!(out, "Unexpected end of input"); - assert!(err.is_empty()); -} - -#[test] -fn unpaired_braces() { - for right_brace in &[")", "]", "}"] { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec![right_brace]), - None, - false, - ); - assert_contains!(out, "Unexpected token"); - assert!(err.is_empty()); - } -} - -#[test] -fn reference_error() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["not_a_variable"]), - None, - false, - ); - assert_contains!(out, "not_a_variable is not defined"); - assert!(err.is_empty()); -} - -#[test] -fn syntax_error() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec![ - "syntax error", - "2", // ensure it keeps accepting input after - ]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "parse error: Expected ';', '}' or at 1:8\n2\n"); - assert!(err.is_empty()); -} - -#[test] -fn syntax_error_jsx() { - // JSX is not supported in the REPL - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["const element =

;"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_contains!(out, "Unexpected token `>`"); - assert!(err.is_empty()); -} - -#[test] -fn type_error() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["console()"]), - None, - false, - ); - assert_contains!(out, "console is not a function"); - assert!(err.is_empty()); -} - -#[test] -fn variable() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["var a = 123;", "a"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "undefined\n123\n"); - assert!(err.is_empty()); -} - -#[test] -fn lexical_scoped_variable() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["let a = 123;", "a"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "undefined\n123\n"); - assert!(err.is_empty()); -} - -#[test] -fn missing_deno_dir() { - use std::fs::{read_dir, remove_dir_all}; - const DENO_DIR: &str = "nonexistent"; - let test_deno_dir = test_util::testdata_path().join(DENO_DIR); - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["1"]), - Some(vec![ - ("DENO_DIR".to_owned(), DENO_DIR.to_owned()), - ("NO_COLOR".to_owned(), "1".to_owned()), - ]), - false, - ); - assert!(read_dir(&test_deno_dir).is_ok()); - remove_dir_all(&test_deno_dir).unwrap(); - assert_ends_with!(out, "1\n"); - assert!(err.is_empty()); -} - -#[test] -fn save_last_eval() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["1", "_"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "1\n1\n"); - assert!(err.is_empty()); -} - -#[test] -fn save_last_thrown() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["throw 1", "_error"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!(out, "Uncaught 1\n1\n"); - assert!(err.is_empty()); -} - -#[test] -fn assign_underscore() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["_ = 1", "2", "_"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - assert_ends_with!( - out, - "Last evaluation result is no longer saved to _.\n1\n2\n1\n" - ); - assert!(err.is_empty()); -} - -#[test] -fn assign_underscore_error() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["_error = 1", "throw 2", "_error"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - println!("{}", out); - assert_ends_with!( - out, - "Last thrown error is no longer saved to _error.\n1\nUncaught 2\n1\n" - ); - assert!(err.is_empty()); -} - -#[test] -fn custom_inspect() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec![ - r#"const o = { - [Symbol.for("Deno.customInspect")]() { - throw new Error('Oops custom inspect error'); - }, - };"#, - "o", - ]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - - assert_contains!(out, "Oops custom inspect error"); - assert!(err.is_empty()); -} - -#[test] -fn eval_flag_valid_input() { - let (out, err) = util::run_and_collect_output_with_args( - true, - vec!["repl", "--eval", "const t = 10;"], - Some(vec!["t * 500;"]), - None, - false, - ); - assert_contains!(out, "5000"); - assert!(err.is_empty()); -} - -#[test] -fn eval_flag_parse_error() { - let (out, err) = util::run_and_collect_output_with_args( - true, - vec!["repl", "--eval", "const %"], - Some(vec!["250 * 10"]), - None, - false, - ); - assert_contains!( - test_util::strip_ansi_codes(&out), - "error in --eval flag. parse error: Unexpected token `%`." - ); - assert_contains!(out, "2500"); // should not prevent input - assert!(err.is_empty()); -} - -#[test] -fn eval_flag_runtime_error() { - let (out, err) = util::run_and_collect_output_with_args( - true, - vec!["repl", "--eval", "throw new Error('Testing')"], - Some(vec!["250 * 10"]), - None, - false, - ); - assert_contains!(out, "error in --eval flag. Uncaught Error: Testing"); - assert_contains!(out, "2500"); // should not prevent input - assert!(err.is_empty()); -} - -#[test] -fn eval_file_flag_valid_input() { - let (out, err) = util::run_and_collect_output_with_args( - true, - vec!["repl", "--eval-file=./run/001_hello.js"], - None, - None, - false, - ); - assert_contains!(out, "Hello World"); - assert!(err.is_empty()); -} - -#[test] -fn eval_file_flag_call_defined_function() { - let (out, err) = util::run_and_collect_output_with_args( - true, - vec!["repl", "--eval-file=./tsc/d.ts"], - Some(vec!["v4()"]), - None, - false, - ); - assert_contains!(out, "hello"); - assert!(err.is_empty()); -} - -#[test] -fn eval_file_flag_http_input() { - let (out, err) = util::run_and_collect_output_with_args( - true, - vec!["repl", "--eval-file=http://127.0.0.1:4545/tsc/d.ts"], - Some(vec!["v4()"]), - None, - true, - ); - assert_contains!(out, "hello"); - assert!(err.contains("Download")); -} - -#[test] -fn eval_file_flag_multiple_files() { - let (out, err) = util::run_and_collect_output_with_args( - true, - vec!["repl", "--eval-file=http://127.0.0.1:4545/repl/import_type.ts,./tsc/d.ts,http://127.0.0.1:4545/type_definitions/foo.js"], - Some(vec!["b.method1=v4", "b.method1()+foo.toUpperCase()"]), - None, - true, - ); - assert_contains!(out, "helloFOO"); - assert_contains!(err, "Download"); -} - -#[test] -fn pty_clear_function() { - util::with_pty(&["repl"], |mut console| { - console.write_line("console.log('hello');"); - console.write_line("clear();"); - console.write_line("const clear = 1234 + 2000;"); - console.write_line("clear;"); - console.write_line("close();"); - - let output = console.read_all_output(); - if cfg!(windows) { - // Windows will overwrite what's in the console buffer before - // we read from it. It contains this string repeated many times - // to clear the screen. - assert_contains!(output, "\r\n\u{1b}[K\r\n\u{1b}[K\r\n\u{1b}[K"); - } else { - assert_contains!(output, "hello"); - assert_contains!(output, "[1;1H"); - } - assert_contains!(output, "undefined"); - assert_contains!(output, "const clear = 1234 + 2000;"); - assert_contains!(output, "3234"); - }); -} - -#[test] -fn pty_tab_handler() { - // If the last character is **not** whitespace, we show the completions - util::with_pty(&["repl"], |mut console| { - console.write_line("a\t\t"); - console.write_line("close();"); - let output = console.read_all_output(); - assert_contains!(output, "addEventListener"); - assert_contains!(output, "alert"); - assert_contains!(output, "atob"); - }); - // If the last character is whitespace, we just insert a tab - util::with_pty(&["repl"], |mut console| { - console.write_line("a; \t\t"); // last character is whitespace - console.write_line("close();"); - let output = console.read_all_output(); - assert_not_contains!(output, "addEventListener"); - assert_not_contains!(output, "alert"); - assert_not_contains!(output, "atob"); - }); -} - -#[test] -fn repl_report_error() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec![ - r#"console.log(1); reportError(new Error("foo")); console.log(2);"#, - ]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - - // TODO(nayeemrmn): The REPL should report event errors and rejections. - assert_contains!(out, "1\n2\nundefined\n"); - assert!(err.is_empty()); -} - -#[test] -fn pty_aggregate_error() { - let (out, err) = util::run_and_collect_output( - true, - "repl", - Some(vec!["await Promise.any([])"]), - Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), - false, - ); - - assert_contains!(out, "AggregateError"); - assert!(err.is_empty()); -} diff --git a/cli/tests/integration/run_tests.rs b/cli/tests/integration/run_tests.rs deleted file mode 100644 index 866fd2793c..0000000000 --- a/cli/tests/integration/run_tests.rs +++ /dev/null @@ -1,3660 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use deno_core::url; -use deno_runtime::deno_fetch::reqwest; -use std::io::Read; -use std::io::Write; -use std::process::Command; -use std::process::Stdio; -use test_util as util; -use test_util::TempDir; -use tokio::task::LocalSet; -use trust_dns_client::serialize::txt::Lexer; -use trust_dns_client::serialize::txt::Parser; -use util::assert_contains; - -itest!(stdout_write_all { - args: "run --quiet run/stdout_write_all.ts", - output: "run/stdout_write_all.out", -}); - -itest!(stdin_read_all { - args: "run --quiet run/stdin_read_all.ts", - output: "run/stdin_read_all.out", - input: Some("01234567890123456789012345678901234567890123456789"), -}); - -itest!(stdout_write_sync_async { - args: "run --quiet run/stdout_write_sync_async.ts", - output: "run/stdout_write_sync_async.out", -}); - -itest!(_001_hello { - args: "run --reload run/001_hello.js", - output: "run/001_hello.js.out", -}); - -itest!(_002_hello { - args: "run --quiet --reload run/002_hello.ts", - output: "run/002_hello.ts.out", -}); - -itest!(_003_relative_import { - args: "run --quiet --reload run/003_relative_import.ts", - output: "run/003_relative_import.ts.out", -}); - -itest!(_004_set_timeout { - args: "run --quiet --reload run/004_set_timeout.ts", - output: "run/004_set_timeout.ts.out", -}); - -itest!(_005_more_imports { - args: "run --quiet --reload run/005_more_imports.ts", - output: "run/005_more_imports.ts.out", -}); - -itest!(_006_url_imports { - args: "run --quiet --reload run/006_url_imports.ts", - output: "run/006_url_imports.ts.out", - http_server: true, -}); - -itest!(_012_async { - args: "run --quiet --reload run/012_async.ts", - output: "run/012_async.ts.out", -}); - -itest!(_013_dynamic_import { - args: "run --quiet --reload --allow-read run/013_dynamic_import.ts", - output: "run/013_dynamic_import.ts.out", -}); - -itest!(_014_duplicate_import { - args: "run --quiet --reload --allow-read run/014_duplicate_import.ts ", - output: "run/014_duplicate_import.ts.out", -}); - -itest!(_015_duplicate_parallel_import { - args: - "run --quiet --reload --allow-read run/015_duplicate_parallel_import.js", - output: "run/015_duplicate_parallel_import.js.out", -}); - -itest!(_016_double_await { - args: "run --quiet --allow-read --reload run/016_double_await.ts", - output: "run/016_double_await.ts.out", -}); - -itest!(_017_import_redirect { - args: "run --quiet --reload run/017_import_redirect.ts", - output: "run/017_import_redirect.ts.out", -}); - -itest!(_017_import_redirect_nocheck { - args: "run --quiet --reload --no-check run/017_import_redirect.ts", - output: "run/017_import_redirect.ts.out", -}); - -itest!(_017_import_redirect_info { - args: "info --quiet --reload run/017_import_redirect.ts", - output: "run/017_import_redirect_info.out", -}); - -itest!(_018_async_catch { - args: "run --quiet --reload run/018_async_catch.ts", - output: "run/018_async_catch.ts.out", -}); - -itest!(_019_media_types { - args: "run --reload run/019_media_types.ts", - output: "run/019_media_types.ts.out", - http_server: true, -}); - -itest!(_020_json_modules { - args: "run --reload run/020_json_modules.ts", - output: "run/020_json_modules.ts.out", - exit_code: 1, -}); - -itest!(_021_mjs_modules { - args: "run --quiet --reload run/021_mjs_modules.ts", - output: "run/021_mjs_modules.ts.out", -}); - -itest!(_023_no_ext { - args: "run --reload --check run/023_no_ext", - output: "run/023_no_ext.out", -}); - -// TODO(lucacasonato): remove --unstable when permissions goes stable -itest!(_025_hrtime { - args: "run --quiet --allow-hrtime --unstable --reload run/025_hrtime.ts", - output: "run/025_hrtime.ts.out", -}); - -itest!(_025_reload_js_type_error { - args: "run --quiet --reload run/025_reload_js_type_error.js", - output: "run/025_reload_js_type_error.js.out", -}); - -itest!(_026_redirect_javascript { - args: "run --quiet --reload run/026_redirect_javascript.js", - output: "run/026_redirect_javascript.js.out", - http_server: true, -}); - -itest!(_027_redirect_typescript { - args: "run --quiet --reload run/027_redirect_typescript.ts", - output: "run/027_redirect_typescript.ts.out", - http_server: true, -}); - -itest!(_028_args { - args: - "run --quiet --reload run/028_args.ts --arg1 val1 --arg2=val2 -- arg3 arg4", - output: "run/028_args.ts.out", -}); - -itest!(_033_import_map { - args: - "run --quiet --reload --import-map=import_maps/import_map.json import_maps/test.ts", - output: "run/033_import_map.out", -}); - -itest!(_033_import_map_remote { - args: - "run --quiet --reload --import-map=http://127.0.0.1:4545/import_maps/import_map_remote.json --unstable import_maps/test_remote.ts", - output: "run/033_import_map_remote.out", - http_server: true, -}); - -itest!(onload { - args: "run --quiet --reload run/onload/main.ts", - output: "run/onload/main.out", -}); - -itest!(_035_cached_only_flag { - args: "run --reload --check --cached-only http://127.0.0.1:4545/run/019_media_types.ts", - output: "run/035_cached_only_flag.out", - exit_code: 1, - http_server: true, -}); - -itest!(_038_checkjs { - // checking if JS file is run through TS compiler - args: - "run --reload --config run/checkjs.tsconfig.json --check run/038_checkjs.js", - exit_code: 1, - output: "run/038_checkjs.js.out", -}); - -itest!(_042_dyn_import_evalcontext { - args: "run --quiet --allow-read --reload run/042_dyn_import_evalcontext.ts", - output: "run/042_dyn_import_evalcontext.ts.out", -}); - -itest!(_044_bad_resource { - args: "run --quiet --reload --allow-read run/044_bad_resource.ts", - output: "run/044_bad_resource.ts.out", - exit_code: 1, -}); - -// TODO(bartlomieju): remove --unstable once Deno.spawn is stabilized -itest!(_045_proxy { - args: "run -L debug --unstable --allow-net --allow-env --allow-run --allow-read --reload --quiet run/045_proxy_test.ts", - output: "run/045_proxy_test.ts.out", - http_server: true, -}); - -itest!(_046_tsx { - args: "run --quiet --reload run/046_jsx_test.tsx", - output: "run/046_jsx_test.tsx.out", -}); - -itest!(_047_jsx { - args: "run --quiet --reload run/047_jsx_test.jsx", - output: "run/047_jsx_test.jsx.out", -}); - -itest!(_048_media_types_jsx { - args: "run --reload run/048_media_types_jsx.ts", - output: "run/048_media_types_jsx.ts.out", - http_server: true, -}); - -itest!(_052_no_remote_flag { - args: - "run --reload --check --no-remote http://127.0.0.1:4545/run/019_media_types.ts", - output: "run/052_no_remote_flag.out", - exit_code: 1, - http_server: true, -}); - -itest!(_056_make_temp_file_write_perm { - args: - "run --quiet --allow-read --allow-write=./subdir/ run/056_make_temp_file_write_perm.ts", - output: "run/056_make_temp_file_write_perm.out", -}); - -itest!(_058_tasks_microtasks_close { - args: "run --quiet run/058_tasks_microtasks_close.ts", - output: "run/058_tasks_microtasks_close.ts.out", -}); - -itest!(_059_fs_relative_path_perm { - args: "run run/059_fs_relative_path_perm.ts", - output: "run/059_fs_relative_path_perm.ts.out", - exit_code: 1, -}); - -itest!(_070_location { - args: "run --location https://foo/bar?baz#bat run/070_location.ts", - output: "run/070_location.ts.out", -}); - -itest!(_071_location_unset { - args: "run run/071_location_unset.ts", - output: "run/071_location_unset.ts.out", -}); - -itest!(_072_location_relative_fetch { - args: "run --location http://127.0.0.1:4545/ --allow-net run/072_location_relative_fetch.ts", - output: "run/072_location_relative_fetch.ts.out", - http_server: true, -}); - -// tests the beforeunload event -itest!(beforeunload_event { - args: "run run/before_unload.js", - output: "run/before_unload.js.out", -}); - -// tests the serialization of webstorage (both localStorage and sessionStorage) -itest!(webstorage_serialization { - args: "run run/webstorage/serialization.ts", - output: "run/webstorage/serialization.ts.out", -}); - -// tests to ensure that when `--location` is set, all code shares the same -// localStorage cache based on the origin of the location URL. -#[test] -fn webstorage_location_shares_origin() { - let deno_dir = util::new_deno_dir(); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--location") - .arg("https://example.com/a.ts") - .arg("run/webstorage/fixture.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Storage { length: 0 }\n"); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--location") - .arg("https://example.com/b.ts") - .arg("run/webstorage/logger.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Storage { length: 1, hello: \"deno\" }\n"); -} - -// test to ensure that when a --config file is set, but no --location, that -// storage persists against unique configuration files. -#[test] -fn webstorage_config_file() { - let deno_dir = util::new_deno_dir(); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--config") - .arg("run/webstorage/config_a.jsonc") - .arg("run/webstorage/fixture.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Storage { length: 0 }\n"); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--config") - .arg("run/webstorage/config_b.jsonc") - .arg("run/webstorage/logger.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Storage { length: 0 }\n"); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--config") - .arg("run/webstorage/config_a.jsonc") - .arg("run/webstorage/logger.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Storage { length: 1, hello: \"deno\" }\n"); -} - -// tests to ensure `--config` does not effect persisted storage when a -// `--location` is provided. -#[test] -fn webstorage_location_precedes_config() { - let deno_dir = util::new_deno_dir(); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--location") - .arg("https://example.com/a.ts") - .arg("--config") - .arg("run/webstorage/config_a.jsonc") - .arg("run/webstorage/fixture.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Storage { length: 0 }\n"); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--location") - .arg("https://example.com/b.ts") - .arg("--config") - .arg("run/webstorage/config_b.jsonc") - .arg("run/webstorage/logger.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Storage { length: 1, hello: \"deno\" }\n"); -} - -// test to ensure that when there isn't a configuration or location, that the -// main module is used to determine how to persist storage data. -#[test] -fn webstorage_main_module() { - let deno_dir = util::new_deno_dir(); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("run/webstorage/fixture.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Storage { length: 0 }\n"); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("run/webstorage/logger.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Storage { length: 0 }\n"); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("run/webstorage/fixture.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(output.stdout, b"Storage { length: 1, hello: \"deno\" }\n"); -} - -itest!(_075_import_local_query_hash { - args: "run run/075_import_local_query_hash.ts", - output: "run/075_import_local_query_hash.ts.out", -}); - -itest!(_077_fetch_empty { - args: "run -A run/077_fetch_empty.ts", - output: "run/077_fetch_empty.ts.out", - exit_code: 1, -}); - -itest!(_078_unload_on_exit { - args: "run run/078_unload_on_exit.ts", - output: "run/078_unload_on_exit.ts.out", - exit_code: 1, -}); - -itest!(_079_location_authentication { - args: - "run --location https://foo:bar@baz/qux run/079_location_authentication.ts", - output: "run/079_location_authentication.ts.out", -}); - -itest!(_081_location_relative_fetch_redirect { - args: "run --location http://127.0.0.1:4546/ --allow-net run/081_location_relative_fetch_redirect.ts", - output: "run/081_location_relative_fetch_redirect.ts.out", - http_server: true, - }); - -itest!(_082_prepare_stack_trace_throw { - args: "run run/082_prepare_stack_trace_throw.js", - output: "run/082_prepare_stack_trace_throw.js.out", - exit_code: 1, -}); - -#[test] -fn _083_legacy_external_source_map() { - let _g = util::http_server(); - let deno_dir = TempDir::new(); - let module_url = url::Url::parse( - "http://localhost:4545/run/083_legacy_external_source_map.ts", - ) - .unwrap(); - // Write a faulty old external source map. - let faulty_map_path = deno_dir.path().join("gen/http/localhost_PORT4545/9576bd5febd0587c5c4d88d57cb3ac8ebf2600c529142abe3baa9a751d20c334.js.map"); - std::fs::create_dir_all(faulty_map_path.parent().unwrap()).unwrap(); - std::fs::write(faulty_map_path, "{\"version\":3,\"file\":\"\",\"sourceRoot\":\"\",\"sources\":[\"http://localhost:4545/083_legacy_external_source_map.ts\"],\"names\":[],\"mappings\":\";AAAA,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC\"}").unwrap(); - let output = Command::new(util::deno_exe_path()) - .env("DENO_DIR", deno_dir.path()) - .current_dir(util::testdata_path()) - .arg("run") - .arg(module_url.to_string()) - .output() - .unwrap(); - // Before https://github.com/denoland/deno/issues/6965 was fixed, the faulty - // old external source map would cause a panic while formatting the error - // and the exit code would be 101. The external source map should be ignored - // in favor of the inline one. - assert_eq!(output.status.code(), Some(1)); - let out = std::str::from_utf8(&output.stdout).unwrap(); - assert_eq!(out, ""); -} - -itest!(dynamic_import_async_error { - args: "run --allow-read run/dynamic_import_async_error/main.ts", - output: "run/dynamic_import_async_error/main.out", -}); - -itest!(dynamic_import_already_rejected { - args: "run --allow-read run/dynamic_import_already_rejected/main.ts", - output: "run/dynamic_import_already_rejected/main.out", -}); - -itest!(no_check_imports_not_used_as_values { - args: "run --config run/no_check_imports_not_used_as_values/preserve_imports.tsconfig.json --no-check run/no_check_imports_not_used_as_values/main.ts", - output: "run/no_check_imports_not_used_as_values/main.out", - }); - -itest!(_088_dynamic_import_already_evaluating { - args: "run --allow-read run/088_dynamic_import_already_evaluating.ts", - output: "run/088_dynamic_import_already_evaluating.ts.out", -}); - -// TODO(bartlomieju): remove --unstable once Deno.spawn is stabilized -itest!(_089_run_allow_list { - args: "run --unstable --allow-run=curl run/089_run_allow_list.ts", - output: "run/089_run_allow_list.ts.out", -}); - -#[test] -fn _090_run_permissions_request() { - let args = "run --quiet run/090_run_permissions_request.ts"; - use util::PtyData::*; - util::test_pty2(args, vec![ - Output("⚠️ ️Deno requests run access to \"ls\". Run again with --allow-run to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)]"), - Input("y\n"), - Output("⚠️ ️Deno requests run access to \"cat\". Run again with --allow-run to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)]"), - Input("n\n"), - Output("granted\r\n"), - Output("prompt\r\n"), - Output("denied\r\n"), - ]); -} - -itest!(_091_use_define_for_class_fields { - args: "run --check run/091_use_define_for_class_fields.ts", - output: "run/091_use_define_for_class_fields.ts.out", - exit_code: 1, -}); - -itest!(_092_import_map_unmapped_bare_specifier { - args: "run --import-map import_maps/import_map.json run/092_import_map_unmapped_bare_specifier.ts", - output: "run/092_import_map_unmapped_bare_specifier.ts.out", - exit_code: 1, -}); - -itest!(js_import_detect { - args: "run --quiet --reload run/js_import_detect.ts", - output: "run/js_import_detect.ts.out", - exit_code: 0, -}); - -itest!(blob_gc_finalization { - args: "run run/blob_gc_finalization.js", - output: "run/blob_gc_finalization.js.out", - exit_code: 0, -}); - -itest!(fetch_response_finalization { - args: - "run --v8-flags=--expose-gc --allow-net run/fetch_response_finalization.js", - output: "run/fetch_response_finalization.js.out", - http_server: true, - exit_code: 0, -}); - -itest!(import_type { - args: "run --reload run/import_type.ts", - output: "run/import_type.ts.out", -}); - -itest!(import_type_no_check { - args: "run --reload --no-check run/import_type.ts", - output: "run/import_type.ts.out", -}); - -itest!(private_field_presence { - args: "run --reload run/private_field_presence.ts", - output: "run/private_field_presence.ts.out", -}); - -itest!(private_field_presence_no_check { - args: "run --reload --no-check run/private_field_presence.ts", - output: "run/private_field_presence.ts.out", -}); - -// TODO(bartlomieju): remove --unstable once Deno.spawn is stabilized -itest!(lock_write_fetch { - args: - "run --quiet --allow-read --allow-write --allow-env --allow-run --unstable run/lock_write_fetch/main.ts", - output: "run/lock_write_fetch/main.out", - http_server: true, - exit_code: 0, -}); - -itest!(lock_check_ok { - args: - "run --lock=run/lock_check_ok.json http://127.0.0.1:4545/run/003_relative_import.ts", - output: "run/003_relative_import.ts.out", - http_server: true, -}); - -itest!(lock_check_ok2 { - args: "run --lock=run/lock_check_ok2.json run/019_media_types.ts", - output: "run/019_media_types.ts.out", - http_server: true, -}); - -itest!(lock_dynamic_imports { - args: "run --lock=run/lock_dynamic_imports.json --allow-read --allow-net http://127.0.0.1:4545/run/013_dynamic_import.ts", - output: "run/lock_dynamic_imports.out", - exit_code: 10, - http_server: true, -}); - -itest!(lock_check_err { - args: "run --lock=run/lock_check_err.json http://127.0.0.1:4545/run/003_relative_import.ts", - output: "run/lock_check_err.out", - exit_code: 10, - http_server: true, -}); - -itest!(lock_check_err2 { - args: "run --lock=run/lock_check_err2.json run/019_media_types.ts", - output: "run/lock_check_err2.out", - exit_code: 10, - http_server: true, -}); - -itest!(lock_v2_check_ok { - args: - "run --lock=run/lock_v2_check_ok.json http://127.0.0.1:4545/run/003_relative_import.ts", - output: "run/003_relative_import.ts.out", - http_server: true, -}); - -itest!(lock_v2_check_ok2 { - args: "run --lock=run/lock_v2_check_ok2.json run/019_media_types.ts", - output: "run/019_media_types.ts.out", - http_server: true, -}); - -itest!(lock_v2_dynamic_imports { - args: "run --lock=run/lock_v2_dynamic_imports.json --allow-read --allow-net http://127.0.0.1:4545/run/013_dynamic_import.ts", - output: "run/lock_v2_dynamic_imports.out", - exit_code: 10, - http_server: true, -}); - -itest!(lock_v2_check_err { - args: "run --lock=run/lock_v2_check_err.json http://127.0.0.1:4545/run/003_relative_import.ts", - output: "run/lock_v2_check_err.out", - exit_code: 10, - http_server: true, -}); - -itest!(lock_v2_check_err2 { - args: "run --lock=run/lock_v2_check_err2.json run/019_media_types.ts", - output: "run/lock_v2_check_err2.out", - exit_code: 10, - http_server: true, -}); - -itest!(lock_only_http_and_https { - args: "run --lock=run/lock_only_http_and_https/deno.lock run/lock_only_http_and_https/main.ts", - output: "run/lock_only_http_and_https/main.out", - http_server: true, -}); - -itest!(mts_dmts_mjs { - args: "run subdir/import.mts", - output: "run/mts_dmts_mjs.out", -}); - -itest!(mts_dmts_mjs_no_check { - args: "run --no-check subdir/import.mts", - output: "run/mts_dmts_mjs.out", -}); - -itest!(async_error { - exit_code: 1, - args: "run --reload run/async_error.ts", - output: "run/async_error.ts.out", -}); - -itest!(config { - args: - "run --reload --config run/config/tsconfig.json --check run/config/main.ts", - output: "run/config/main.out", -}); - -itest!(config_types { - args: - "run --reload --quiet --config run/config_types/tsconfig.json run/config_types/main.ts", - output: "run/config_types/main.out", -}); - -itest!(config_types_remote { - http_server: true, - args: "run --reload --quiet --config run/config_types/remote.tsconfig.json run/config_types/main.ts", - output: "run/config_types/main.out", - }); - -itest!(empty_typescript { - args: "run --reload --check run/empty.ts", - output_str: Some("Check file:[WILDCARD]/run/empty.ts\n"), -}); - -itest!(error_001 { - args: "run --reload run/error_001.ts", - exit_code: 1, - output: "run/error_001.ts.out", -}); - -itest!(error_002 { - args: "run --reload run/error_002.ts", - exit_code: 1, - output: "run/error_002.ts.out", -}); - -itest!(error_003_typescript { - args: "run --reload --check run/error_003_typescript.ts", - exit_code: 1, - output: "run/error_003_typescript.ts.out", -}); - -// Supposing that we've already attempted to run error_003_typescript.ts -// we want to make sure that JS wasn't emitted. Running again without reload flag -// should result in the same output. -// https://github.com/denoland/deno/issues/2436 -itest!(error_003_typescript2 { - args: "run --check run/error_003_typescript.ts", - exit_code: 1, - output: "run/error_003_typescript.ts.out", -}); - -itest!(error_004_missing_module { - args: "run --reload run/error_004_missing_module.ts", - exit_code: 1, - output: "run/error_004_missing_module.ts.out", -}); - -itest!(error_005_missing_dynamic_import { - args: - "run --reload --allow-read --quiet run/error_005_missing_dynamic_import.ts", - exit_code: 1, - output: "run/error_005_missing_dynamic_import.ts.out", -}); - -itest!(error_006_import_ext_failure { - args: "run --reload run/error_006_import_ext_failure.ts", - exit_code: 1, - output: "run/error_006_import_ext_failure.ts.out", -}); - -itest!(error_007_any { - args: "run --reload run/error_007_any.ts", - exit_code: 1, - output: "run/error_007_any.ts.out", -}); - -itest!(error_008_checkjs { - args: "run --reload run/error_008_checkjs.js", - exit_code: 1, - output: "run/error_008_checkjs.js.out", -}); - -itest!(error_009_extensions_error { - args: "run run/error_009_extensions_error.js", - output: "run/error_009_extensions_error.js.out", - exit_code: 1, -}); - -itest!(error_011_bad_module_specifier { - args: "run --reload run/error_011_bad_module_specifier.ts", - exit_code: 1, - output: "run/error_011_bad_module_specifier.ts.out", -}); - -itest!(error_012_bad_dynamic_import_specifier { - args: "run --reload --check run/error_012_bad_dynamic_import_specifier.ts", - exit_code: 1, - output: "run/error_012_bad_dynamic_import_specifier.ts.out", -}); - -itest!(error_013_missing_script { - args: "run --reload missing_file_name", - exit_code: 1, - output: "run/error_013_missing_script.out", -}); - -itest!(error_014_catch_dynamic_import_error { - args: - "run --reload --allow-read run/error_014_catch_dynamic_import_error.js", - output: "run/error_014_catch_dynamic_import_error.js.out", -}); - -itest!(error_015_dynamic_import_permissions { - args: "run --reload --quiet run/error_015_dynamic_import_permissions.js", - output: "run/error_015_dynamic_import_permissions.out", - exit_code: 1, - http_server: true, -}); - -// We have an allow-net flag but not allow-read, it should still result in error. -itest!(error_016_dynamic_import_permissions2 { - args: "run --reload --allow-net run/error_016_dynamic_import_permissions2.js", - output: "run/error_016_dynamic_import_permissions2.out", - exit_code: 1, - http_server: true, -}); - -itest!(error_017_hide_long_source_ts { - args: "run --reload --check run/error_017_hide_long_source_ts.ts", - output: "run/error_017_hide_long_source_ts.ts.out", - exit_code: 1, -}); - -itest!(error_018_hide_long_source_js { - args: "run run/error_018_hide_long_source_js.js", - output: "run/error_018_hide_long_source_js.js.out", - exit_code: 1, -}); - -itest!(error_019_stack_function { - args: "run run/error_019_stack_function.ts", - output: "run/error_019_stack_function.ts.out", - exit_code: 1, -}); - -itest!(error_020_stack_constructor { - args: "run run/error_020_stack_constructor.ts", - output: "run/error_020_stack_constructor.ts.out", - exit_code: 1, -}); - -itest!(error_021_stack_method { - args: "run run/error_021_stack_method.ts", - output: "run/error_021_stack_method.ts.out", - exit_code: 1, -}); - -itest!(error_022_stack_custom_error { - args: "run run/error_022_stack_custom_error.ts", - output: "run/error_022_stack_custom_error.ts.out", - exit_code: 1, -}); - -itest!(error_023_stack_async { - args: "run run/error_023_stack_async.ts", - output: "run/error_023_stack_async.ts.out", - exit_code: 1, -}); - -itest!(error_024_stack_promise_all { - args: "run run/error_024_stack_promise_all.ts", - output: "run/error_024_stack_promise_all.ts.out", - exit_code: 1, -}); - -itest!(error_025_tab_indent { - args: "run run/error_025_tab_indent", - output: "run/error_025_tab_indent.out", - exit_code: 1, -}); - -itest!(error_026_remote_import_error { - args: "run run/error_026_remote_import_error.ts", - output: "run/error_026_remote_import_error.ts.out", - exit_code: 1, - http_server: true, -}); - -itest!(error_for_await { - args: "run --reload --check run/error_for_await.ts", - output: "run/error_for_await.ts.out", - exit_code: 1, -}); - -itest!(error_missing_module_named_import { - args: "run --reload run/error_missing_module_named_import.ts", - output: "run/error_missing_module_named_import.ts.out", - exit_code: 1, -}); - -itest!(error_no_check { - args: "run --reload --no-check run/error_no_check.ts", - output: "run/error_no_check.ts.out", - exit_code: 1, -}); - -itest!(error_syntax { - args: "run --reload run/error_syntax.js", - exit_code: 1, - output: "run/error_syntax.js.out", -}); - -itest!(error_syntax_empty_trailing_line { - args: "run --reload run/error_syntax_empty_trailing_line.mjs", - exit_code: 1, - output: "run/error_syntax_empty_trailing_line.mjs.out", -}); - -itest!(error_type_definitions { - args: "run --reload --check run/error_type_definitions.ts", - exit_code: 1, - output: "run/error_type_definitions.ts.out", -}); - -itest!(error_local_static_import_from_remote_ts { - args: "run --reload http://localhost:4545/run/error_local_static_import_from_remote.ts", - exit_code: 1, - http_server: true, - output: "run/error_local_static_import_from_remote.ts.out", - }); - -itest!(error_local_static_import_from_remote_js { - args: "run --reload http://localhost:4545/run/error_local_static_import_from_remote.js", - exit_code: 1, - http_server: true, - output: "run/error_local_static_import_from_remote.js.out", - }); - -itest!(exit_error42 { - exit_code: 42, - args: "run --quiet --reload run/exit_error42.ts", - output: "run/exit_error42.ts.out", -}); - -itest!(set_exit_code_0 { - args: "run --no-check --unstable run/set_exit_code_0.ts", - output_str: Some(""), - exit_code: 0, -}); - -itest!(set_exit_code_1 { - args: "run --no-check --unstable run/set_exit_code_1.ts", - output_str: Some(""), - exit_code: 42, -}); - -itest!(set_exit_code_2 { - args: "run --no-check --unstable run/set_exit_code_2.ts", - output_str: Some(""), - exit_code: 42, -}); - -itest!(op_exit_op_set_exit_code_in_worker { - args: "run --no-check --unstable --allow-read run/op_exit_op_set_exit_code_in_worker.ts", - exit_code: 21, - output_str: Some(""), -}); - -itest!(deno_exit_tampering { - args: "run --no-check --unstable run/deno_exit_tampering.ts", - output_str: Some(""), - exit_code: 42, -}); - -itest!(heapstats { - args: "run --quiet --unstable --v8-flags=--expose-gc run/heapstats.js", - output: "run/heapstats.js.out", -}); - -itest!(finalization_registry { - args: - "run --quiet --unstable --v8-flags=--expose-gc run/finalization_registry.js", - output: "run/finalization_registry.js.out", -}); - -itest!(https_import { - args: "run --quiet --reload --cert tls/RootCA.pem run/https_import.ts", - output: "run/https_import.ts.out", - http_server: true, -}); - -itest!(if_main { - args: "run --quiet --reload run/if_main.ts", - output: "run/if_main.ts.out", -}); - -itest!(import_meta { - args: "run --quiet --reload --import-map=run/import_meta/importmap.json run/import_meta/main.ts", - output: "run/import_meta/main.out", -}); - -itest!(main_module { - args: "run --quiet --allow-read --reload run/main_module/main.ts", - output: "run/main_module/main.out", -}); - -itest!(no_check { - args: "run --quiet --reload --no-check run/006_url_imports.ts", - output: "run/006_url_imports.ts.out", - http_server: true, -}); - -itest!(no_check_decorators { - args: "run --quiet --reload --no-check run/no_check_decorators.ts", - output: "run/no_check_decorators.ts.out", -}); - -itest!(check_remote { - args: "run --quiet --reload --check=all run/no_check_remote.ts", - output: "run/no_check_remote.ts.disabled.out", - exit_code: 1, - http_server: true, -}); - -itest!(no_check_remote { - args: "run --quiet --reload --no-check=remote run/no_check_remote.ts", - output: "run/no_check_remote.ts.enabled.out", - http_server: true, -}); - -itest!(runtime_decorators { - args: "run --quiet --reload --no-check run/runtime_decorators.ts", - output: "run/runtime_decorators.ts.out", -}); - -itest!(seed_random { - args: "run --seed=100 run/seed_random.js", - output: "run/seed_random.js.out", -}); - -itest!(type_definitions { - args: "run --reload run/type_definitions.ts", - output: "run/type_definitions.ts.out", -}); - -itest!(type_definitions_for_export { - args: "run --reload --check run/type_definitions_for_export.ts", - output: "run/type_definitions_for_export.ts.out", - exit_code: 1, -}); - -itest!(type_directives_01 { - args: "run --reload --check=all -L debug run/type_directives_01.ts", - output: "run/type_directives_01.ts.out", - http_server: true, -}); - -itest!(type_directives_02 { - args: "run --reload --check=all -L debug run/type_directives_02.ts", - output: "run/type_directives_02.ts.out", -}); - -itest!(type_directives_js_main { - args: "run --reload -L debug run/type_directives_js_main.js", - output: "run/type_directives_js_main.js.out", - exit_code: 0, -}); - -itest!(type_directives_redirect { - args: "run --reload --check run/type_directives_redirect.ts", - output: "run/type_directives_redirect.ts.out", - http_server: true, -}); - -itest!(type_headers_deno_types { - args: "run --reload --check run/type_headers_deno_types.ts", - output: "run/type_headers_deno_types.ts.out", - http_server: true, -}); - -itest!(ts_type_imports { - args: "run --reload --check run/ts_type_imports.ts", - output: "run/ts_type_imports.ts.out", - exit_code: 1, -}); - -itest!(ts_decorators { - args: "run --reload --check run/ts_decorators.ts", - output: "run/ts_decorators.ts.out", -}); - -itest!(ts_type_only_import { - args: "run --reload --check run/ts_type_only_import.ts", - output: "run/ts_type_only_import.ts.out", -}); - -itest!(swc_syntax_error { - args: "run --reload --check run/swc_syntax_error.ts", - output: "run/swc_syntax_error.ts.out", - exit_code: 1, -}); - -itest!(unbuffered_stderr { - args: "run --reload run/unbuffered_stderr.ts", - output: "run/unbuffered_stderr.ts.out", -}); - -itest!(unbuffered_stdout { - args: "run --quiet --reload run/unbuffered_stdout.ts", - output: "run/unbuffered_stdout.ts.out", -}); - -itest!(v8_flags_run { - args: "run --v8-flags=--expose-gc run/v8_flags.js", - output: "run/v8_flags.js.out", -}); - -itest!(v8_flags_unrecognized { - args: "repl --v8-flags=--foo,bar,--trace-gc,-baz", - output: "run/v8_flags_unrecognized.out", - exit_code: 1, -}); - -itest!(v8_help { - args: "repl --v8-flags=--help", - output: "run/v8_help.out", -}); - -itest!(unsupported_dynamic_import_scheme { - args: "eval import('xxx:')", - output: "run/unsupported_dynamic_import_scheme.out", - exit_code: 1, -}); - -itest!(wasm { - args: "run --quiet run/wasm.ts", - output: "run/wasm.ts.out", -}); - -itest!(wasm_shared { - args: "run --quiet run/wasm_shared.ts", - output: "run/wasm_shared.out", -}); - -itest!(wasm_async { - args: "run run/wasm_async.js", - output: "run/wasm_async.out", -}); - -itest!(wasm_unreachable { - args: "run --allow-read run/wasm_unreachable.js", - output: "run/wasm_unreachable.out", - exit_code: 1, -}); - -itest!(wasm_url { - args: "run --quiet --allow-net=localhost:4545 run/wasm_url.js", - output: "run/wasm_url.out", - exit_code: 1, - http_server: true, -}); - -itest!(weakref { - args: "run --quiet --reload run/weakref.ts", - output: "run/weakref.ts.out", -}); - -itest!(top_level_await_order { - args: "run --allow-read run/top_level_await/order.js", - output: "run/top_level_await/order.out", -}); - -itest!(top_level_await_loop { - args: "run --allow-read run/top_level_await/loop.js", - output: "run/top_level_await/loop.out", -}); - -itest!(top_level_await_circular { - args: "run --allow-read run/top_level_await/circular.js", - output: "run/top_level_await/circular.out", - exit_code: 1, -}); - -// Regression test for https://github.com/denoland/deno/issues/11238. -itest!(top_level_await_nested { - args: "run --allow-read run/top_level_await/nested/main.js", - output: "run/top_level_await/nested.out", -}); - -itest!(top_level_await_unresolved { - args: "run run/top_level_await/unresolved.js", - output: "run/top_level_await/unresolved.out", - exit_code: 1, -}); - -itest!(top_level_await { - args: "run --allow-read run/top_level_await/top_level_await.js", - output: "run/top_level_await/top_level_await.out", -}); - -itest!(top_level_await_ts { - args: "run --quiet --allow-read run/top_level_await/top_level_await.ts", - output: "run/top_level_await/top_level_await.out", -}); - -itest!(top_level_for_await { - args: "run --quiet run/top_level_await/top_level_for_await.js", - output: "run/top_level_await/top_level_for_await.out", -}); - -itest!(top_level_for_await_ts { - args: "run --quiet run/top_level_await/top_level_for_await.ts", - output: "run/top_level_await/top_level_for_await.out", -}); - -itest!(unstable_disabled { - args: "run --reload --check run/unstable.ts", - exit_code: 1, - output: "run/unstable_disabled.out", -}); - -itest!(unstable_enabled { - args: "run --quiet --reload --unstable run/unstable.ts", - output: "run/unstable_enabled.out", -}); - -itest!(unstable_disabled_js { - args: "run --reload run/unstable.js", - output: "run/unstable_disabled_js.out", -}); - -itest!(unstable_enabled_js { - args: "run --quiet --reload --unstable run/unstable.ts", - output: "run/unstable_enabled_js.out", -}); - -itest!(unstable_worker { - args: "run --reload --unstable --quiet --allow-read run/unstable_worker.ts", - output: "run/unstable_worker.ts.out", -}); - -itest!(import_compression { - args: "run --quiet --reload --allow-net run/import_compression/main.ts", - output: "run/import_compression/main.out", - http_server: true, -}); - -itest!(disallow_http_from_https_js { - args: "run --quiet --reload --cert tls/RootCA.pem https://localhost:5545/run/disallow_http_from_https.js", - output: "run/disallow_http_from_https_js.out", - http_server: true, - exit_code: 1, -}); - -itest!(disallow_http_from_https_ts { - args: "run --quiet --reload --cert tls/RootCA.pem https://localhost:5545/run/disallow_http_from_https.ts", - output: "run/disallow_http_from_https_ts.out", - http_server: true, - exit_code: 1, -}); - -itest!(dynamic_import_conditional { - args: "run --quiet --reload run/dynamic_import_conditional.js", - output: "run/dynamic_import_conditional.js.out", -}); - -itest!(tsx_imports { - args: "run --reload --check run/tsx_imports/tsx_imports.ts", - output: "run/tsx_imports/tsx_imports.ts.out", -}); - -itest!(fix_dynamic_import_errors { - args: "run --reload run/fix_dynamic_import_errors.js", - output: "run/fix_dynamic_import_errors.js.out", -}); - -itest!(fix_emittable_skipped { - args: "run --reload run/fix_emittable_skipped.js", - output: "run/fix_emittable_skipped.ts.out", -}); - -itest!(fix_js_import_js { - args: "run --quiet --reload run/fix_js_import_js.ts", - output: "run/fix_js_import_js.ts.out", -}); - -itest!(fix_js_imports { - args: "run --quiet --reload run/fix_js_imports.ts", - output: "run/fix_js_imports.ts.out", -}); - -itest!(fix_tsc_file_exists { - args: "run --quiet --reload tsc/test.js", - output: "run/fix_tsc_file_exists.out", -}); - -itest!(fix_worker_dispatchevent { - args: "run --quiet --reload run/fix_worker_dispatchevent.ts", - output: "run/fix_worker_dispatchevent.ts.out", -}); - -itest!(es_private_fields { - args: "run --quiet --reload run/es_private_fields.js", - output: "run/es_private_fields.js.out", -}); - -itest!(cjs_imports { - args: "run --quiet --reload run/cjs_imports/main.ts", - output: "run/cjs_imports/main.out", -}); - -itest!(ts_import_from_js { - args: "run --quiet --reload run/ts_import_from_js/main.js", - output: "run/ts_import_from_js/main.out", - http_server: true, -}); - -itest!(jsx_import_from_ts { - args: "run --quiet --reload run/jsx_import_from_ts.ts", - output: "run/jsx_import_from_ts.ts.out", -}); - -itest!(jsx_import_source_pragma { - args: "run --reload run/jsx_import_source_pragma.tsx", - output: "run/jsx_import_source.out", - http_server: true, -}); - -itest!(jsx_import_source_pragma_with_config { - args: - "run --reload --config jsx/deno-jsx.jsonc --no-lock run/jsx_import_source_pragma.tsx", - output: "run/jsx_import_source.out", - http_server: true, -}); - -itest!(jsx_import_source_pragma_with_dev_config { - args: - "run --reload --config jsx/deno-jsxdev.jsonc --no-lock run/jsx_import_source_pragma.tsx", - output: "run/jsx_import_source_dev.out", - http_server: true, -}); - -itest!(jsx_import_source_no_pragma { - args: - "run --reload --config jsx/deno-jsx.jsonc --no-lock run/jsx_import_source_no_pragma.tsx", - output: "run/jsx_import_source.out", - http_server: true, -}); - -itest!(jsx_import_source_no_pragma_dev { - args: "run --reload --config jsx/deno-jsxdev.jsonc --no-lock run/jsx_import_source_no_pragma.tsx", - output: "run/jsx_import_source_dev.out", - http_server: true, -}); - -itest!(jsx_import_source_pragma_import_map { - args: "run --reload --import-map jsx/import-map.json run/jsx_import_source_pragma_import_map.tsx", - output: "run/jsx_import_source_import_map.out", - http_server: true, -}); - -itest!(jsx_import_source_pragma_import_map_dev { - args: "run --reload --import-map jsx/import-map.json --config jsx/deno-jsxdev-import-map.jsonc run/jsx_import_source_pragma_import_map.tsx", - output: "run/jsx_import_source_import_map_dev.out", - http_server: true, -}); - -itest!(jsx_import_source_import_map { - args: "run --reload --import-map jsx/import-map.json --no-lock --config jsx/deno-jsx-import-map.jsonc run/jsx_import_source_no_pragma.tsx", - output: "run/jsx_import_source_import_map.out", - http_server: true, -}); - -itest!(jsx_import_source_import_map_dev { - args: "run --reload --import-map jsx/import-map.json --no-lock --config jsx/deno-jsxdev-import-map.jsonc run/jsx_import_source_no_pragma.tsx", - output: "run/jsx_import_source_import_map_dev.out", - http_server: true, -}); - -itest!(jsx_import_source_import_map_scoped { - args: "run --reload --import-map jsx/import-map-scoped.json --no-lock --config jsx/deno-jsx-import-map.jsonc subdir/jsx_import_source_no_pragma.tsx", - output: "run/jsx_import_source_import_map.out", - http_server: true, -}); - -itest!(jsx_import_source_import_map_scoped_dev { - args: "run --reload --import-map jsx/import-map-scoped.json --no-lock --config jsx/deno-jsxdev-import-map.jsonc subdir/jsx_import_source_no_pragma.tsx", - output: "run/jsx_import_source_import_map_dev.out", - http_server: true, -}); - -itest!(jsx_import_source_pragma_no_check { - args: "run --reload --no-check run/jsx_import_source_pragma.tsx", - output: "run/jsx_import_source.out", - http_server: true, -}); - -itest!(jsx_import_source_pragma_with_config_no_check { - args: "run --reload --config jsx/deno-jsx.jsonc --no-lock --no-check run/jsx_import_source_pragma.tsx", - output: "run/jsx_import_source.out", - http_server: true, -}); - -itest!(jsx_import_source_no_pragma_no_check { - args: - "run --reload --config jsx/deno-jsx.jsonc --no-lock --no-check run/jsx_import_source_no_pragma.tsx", - output: "run/jsx_import_source.out", - http_server: true, -}); - -itest!(jsx_import_source_pragma_import_map_no_check { - args: "run --reload --import-map jsx/import-map.json --no-check run/jsx_import_source_pragma_import_map.tsx", - output: "run/jsx_import_source_import_map.out", - http_server: true, -}); - -itest!(jsx_import_source_import_map_no_check { - args: "run --reload --import-map jsx/import-map.json --no-lock --config jsx/deno-jsx-import-map.jsonc --no-check run/jsx_import_source_no_pragma.tsx", - output: "run/jsx_import_source_import_map.out", - http_server: true, -}); - -itest!(jsx_import_source_error { - args: "run --config jsx/deno-jsx-error.jsonc --check run/jsx_import_source_no_pragma.tsx", - output: "run/jsx_import_source_error.out", - exit_code: 1, -}); - -// TODO(#11128): Flaky. Re-enable later. -// itest!(single_compile_with_reload { -// args: "run --relcert/oad --allow-read run/single_compile_with_reload.ts", -// output: "run/single_compile_with_reload.ts.out", -// }); - -itest!(proto_exploit { - args: "run run/proto_exploit.js", - output: "run/proto_exploit.js.out", -}); - -itest!(reference_types { - args: "run --reload --quiet run/reference_types.ts", - output: "run/reference_types.ts.out", -}); - -itest!(references_types_remote { - http_server: true, - args: "run --reload --quiet run/reference_types_remote.ts", - output: "run/reference_types_remote.ts.out", -}); - -itest!(reference_types_error { - args: - "run --config run/checkjs.tsconfig.json --check run/reference_types_error.js", - output: "run/reference_types_error.js.out", - exit_code: 1, -}); - -itest!(reference_types_error_no_check { - args: "run --no-check run/reference_types_error.js", - output_str: Some(""), -}); - -itest!(import_data_url_error_stack { - args: "run --quiet --reload run/import_data_url_error_stack.ts", - output: "run/import_data_url_error_stack.ts.out", - exit_code: 1, -}); - -itest!(import_data_url_import_relative { - args: "run --quiet --reload run/import_data_url_import_relative.ts", - output: "run/import_data_url_import_relative.ts.out", - exit_code: 1, -}); - -itest!(import_data_url_import_map { - args: "run --quiet --reload --import-map import_maps/import_map.json run/import_data_url.ts", - output: "run/import_data_url.ts.out", - }); - -itest!(import_data_url_imports { - args: "run --quiet --reload run/import_data_url_imports.ts", - output: "run/import_data_url_imports.ts.out", - http_server: true, -}); - -itest!(import_data_url_jsx { - args: "run --quiet --reload run/import_data_url_jsx.ts", - output: "run/import_data_url_jsx.ts.out", -}); - -itest!(import_data_url { - args: "run --quiet --reload run/import_data_url.ts", - output: "run/import_data_url.ts.out", -}); - -itest!(import_dynamic_data_url { - args: "run --quiet --reload run/import_dynamic_data_url.ts", - output: "run/import_dynamic_data_url.ts.out", -}); - -itest!(import_blob_url_error_stack { - args: "run --quiet --reload run/import_blob_url_error_stack.ts", - output: "run/import_blob_url_error_stack.ts.out", - exit_code: 1, -}); - -itest!(import_blob_url_import_relative { - args: "run --quiet --reload run/import_blob_url_import_relative.ts", - output: "run/import_blob_url_import_relative.ts.out", - exit_code: 1, -}); - -itest!(import_blob_url_imports { - args: - "run --quiet --reload --allow-net=localhost:4545 run/import_blob_url_imports.ts", - output: "run/import_blob_url_imports.ts.out", - http_server: true, -}); - -itest!(import_blob_url_jsx { - args: "run --quiet --reload run/import_blob_url_jsx.ts", - output: "run/import_blob_url_jsx.ts.out", -}); - -itest!(import_blob_url { - args: "run --quiet --reload run/import_blob_url.ts", - output: "run/import_blob_url.ts.out", -}); - -itest!(import_file_with_colon { - args: "run --quiet --reload run/import_file_with_colon.ts", - output: "run/import_file_with_colon.ts.out", - http_server: true, -}); - -itest!(import_extensionless { - args: "run --quiet --reload run/import_extensionless.ts", - output: "run/import_extensionless.ts.out", - http_server: true, -}); - -itest!(classic_workers_event_loop { - args: - "run --enable-testing-features-do-not-use run/classic_workers_event_loop.js", - output: "run/classic_workers_event_loop.js.out", -}); - -// FIXME(bartlomieju): disabled, because this test is very flaky on CI -// itest!(local_sources_not_cached_in_memory { -// args: "run --allow-read --allow-write run/no_mem_cache.js", -// output: "run/no_mem_cache.js.out", -// }); - -// This test checks that inline source map data is used. It uses a hand crafted -// source map that maps to a file that exists, but is not loaded into the module -// graph (inline_js_source_map_2.ts) (because there are no direct dependencies). -// Source line is not remapped because no inline source contents are included in -// the sourcemap and the file is not present in the dependency graph. -itest!(inline_js_source_map_2 { - args: "run --quiet run/inline_js_source_map_2.js", - output: "run/inline_js_source_map_2.js.out", - exit_code: 1, -}); - -// This test checks that inline source map data is used. It uses a hand crafted -// source map that maps to a file that exists, but is not loaded into the module -// graph (inline_js_source_map_2.ts) (because there are no direct dependencies). -// Source line remapped using th inline source contents that are included in the -// inline source map. -itest!(inline_js_source_map_2_with_inline_contents { - args: "run --quiet run/inline_js_source_map_2_with_inline_contents.js", - output: "run/inline_js_source_map_2_with_inline_contents.js.out", - exit_code: 1, -}); - -// This test checks that inline source map data is used. It uses a hand crafted -// source map that maps to a file that exists, and is loaded into the module -// graph because of a direct import statement (inline_js_source_map.ts). The -// source map was generated from an earlier version of this file, where the throw -// was not commented out. The source line is remapped using source contents that -// from the module graph. -itest!(inline_js_source_map_with_contents_from_graph { - args: "run --quiet run/inline_js_source_map_with_contents_from_graph.js", - output: "run/inline_js_source_map_with_contents_from_graph.js.out", - exit_code: 1, - http_server: true, -}); - -// This test ensures that a descriptive error is shown when we're unable to load -// the import map. Even though this tests only the `run` subcommand, we can be sure -// that the error message is similar for other subcommands as they all use -// `program_state.maybe_import_map` to access the import map underneath. -itest!(error_import_map_unable_to_load { - args: "run --import-map=import_maps/does_not_exist.json import_maps/test.ts", - output: "run/error_import_map_unable_to_load.out", - exit_code: 1, -}); - -// Test that setting `self` in the main thread to some other value doesn't break -// the world. -itest!(replace_self { - args: "run run/replace_self.js", - output: "run/replace_self.js.out", -}); - -itest!(worker_event_handler_test { - args: "run --quiet --reload --allow-read run/worker_event_handler_test.js", - output: "run/worker_event_handler_test.js.out", -}); - -itest!(worker_close_race { - args: "run --quiet --reload --allow-read run/worker_close_race.js", - output: "run/worker_close_race.js.out", -}); - -itest!(worker_drop_handle_race { - args: "run --quiet --reload --allow-read run/worker_drop_handle_race.js", - output: "run/worker_drop_handle_race.js.out", - exit_code: 1, -}); - -itest!(worker_drop_handle_race_terminate { - args: "run --unstable run/worker_drop_handle_race_terminate.js", - output: "run/worker_drop_handle_race_terminate.js.out", -}); - -itest!(worker_close_nested { - args: "run --quiet --reload --allow-read run/worker_close_nested.js", - output: "run/worker_close_nested.js.out", -}); - -itest!(worker_message_before_close { - args: "run --quiet --reload --allow-read run/worker_message_before_close.js", - output: "run/worker_message_before_close.js.out", -}); - -itest!(worker_close_in_wasm_reactions { - args: - "run --quiet --reload --allow-read run/worker_close_in_wasm_reactions.js", - output: "run/worker_close_in_wasm_reactions.js.out", -}); - -itest!(shebang_tsc { - args: "run --quiet --check run/shebang.ts", - output: "run/shebang.ts.out", -}); - -itest!(shebang_swc { - args: "run --quiet run/shebang.ts", - output: "run/shebang.ts.out", -}); - -itest!(shebang_with_json_imports_tsc { - args: "run --quiet import_assertions/json_with_shebang.ts", - output: "import_assertions/json_with_shebang.ts.out", - exit_code: 1, -}); - -itest!(shebang_with_json_imports_swc { - args: "run --quiet --no-check import_assertions/json_with_shebang.ts", - output: "import_assertions/json_with_shebang.ts.out", - exit_code: 1, -}); - -#[test] -fn no_validate_asm() { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("run/no_validate_asm.js") - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert!(output.stderr.is_empty()); - assert!(output.stdout.is_empty()); -} - -#[test] -fn exec_path() { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--allow-read") - .arg("run/exec_path.ts") - .stdout(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); - let actual = std::fs::canonicalize(std::path::Path::new(stdout_str)).unwrap(); - let expected = std::fs::canonicalize(util::deno_exe_path()).unwrap(); - assert_eq!(expected, actual); -} - -#[cfg(windows)] -// Clippy suggests to remove the `NoStd` prefix from all variants. I disagree. -#[allow(clippy::enum_variant_names)] -enum WinProcConstraints { - NoStdIn, - NoStdOut, - NoStdErr, -} - -#[cfg(windows)] -fn run_deno_script_constrained( - script_path: std::path::PathBuf, - constraints: WinProcConstraints, -) -> Result<(), i64> { - let file_path = "assets/DenoWinRunner.ps1"; - let constraints = match constraints { - WinProcConstraints::NoStdIn => "1", - WinProcConstraints::NoStdOut => "2", - WinProcConstraints::NoStdErr => "4", - }; - let deno_exe_path = util::deno_exe_path() - .into_os_string() - .into_string() - .unwrap(); - - let deno_script_path = script_path.into_os_string().into_string().unwrap(); - - let args = vec![&deno_exe_path[..], &deno_script_path[..], constraints]; - util::run_powershell_script_file(file_path, args) -} - -#[cfg(windows)] -#[test] -fn should_not_panic_on_no_stdin() { - let output = run_deno_script_constrained( - util::testdata_path().join("echo.ts"), - WinProcConstraints::NoStdIn, - ); - output.unwrap(); -} - -#[cfg(windows)] -#[test] -fn should_not_panic_on_no_stdout() { - let output = run_deno_script_constrained( - util::testdata_path().join("echo.ts"), - WinProcConstraints::NoStdOut, - ); - output.unwrap(); -} - -#[cfg(windows)] -#[test] -fn should_not_panic_on_no_stderr() { - let output = run_deno_script_constrained( - util::testdata_path().join("echo.ts"), - WinProcConstraints::NoStdErr, - ); - output.unwrap(); -} - -#[cfg(not(windows))] -#[test] -fn should_not_panic_on_undefined_home_environment_variable() { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("echo.ts") - .env_remove("HOME") - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); -} - -#[test] -fn should_not_panic_on_undefined_deno_dir_environment_variable() { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("echo.ts") - .env_remove("DENO_DIR") - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); -} - -#[cfg(not(windows))] -#[test] -fn should_not_panic_on_undefined_deno_dir_and_home_environment_variables() { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("echo.ts") - .env_remove("DENO_DIR") - .env_remove("HOME") - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); -} - -#[test] -fn rust_log() { - // Without RUST_LOG the stderr is empty. - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("run/001_hello.js") - .stderr(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert!(output.stderr.is_empty()); - - // With RUST_LOG the stderr is not empty. - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("run/001_hello.js") - .env("RUST_LOG", "debug") - .stderr(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - assert!(!output.stderr.is_empty()); -} - -#[test] -fn dont_cache_on_check_fail() { - let deno_dir = util::new_deno_dir(); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--check=all") - .arg("--reload") - .arg("run/error_003_typescript.ts") - .stderr(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - assert!(!output.stderr.is_empty()); - - let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); - let output = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--check=all") - .arg("run/error_003_typescript.ts") - .stderr(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - assert!(!output.stderr.is_empty()); -} - -mod permissions { - use test_util as util; - - // TODO(bartlomieju): remove --unstable once Deno.spawn is stabilized - #[test] - fn with_allow() { - for permission in &util::PERMISSION_VARIANTS { - let status = util::deno_cmd() - .current_dir(&util::testdata_path()) - .arg("run") - .arg("--unstable") - .arg(format!("--allow-{0}", permission)) - .arg("run/permission_test.ts") - .arg(format!("{0}Required", permission)) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - } - } - - // TODO(bartlomieju): remove --unstable once Deno.spawn is stabilized - #[test] - fn without_allow() { - for permission in &util::PERMISSION_VARIANTS { - let (_, err) = util::run_and_collect_output( - false, - &format!( - "run --unstable run/permission_test.ts {0}Required", - permission - ), - None, - None, - false, - ); - assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); - } - } - - #[test] - fn rw_inside_project_dir() { - const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; - for permission in &PERMISSION_VARIANTS { - let status = util::deno_cmd() - .current_dir(&util::testdata_path()) - .arg("run") - .arg(format!( - "--allow-{0}={1}", - permission, - util::testdata_path() - .into_os_string() - .into_string() - .unwrap() - )) - .arg("run/complex_permissions_test.ts") - .arg(permission) - .arg("run/complex_permissions_test.ts") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - } - } - - #[test] - fn rw_outside_test_dir() { - const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; - for permission in &PERMISSION_VARIANTS { - let (_, err) = util::run_and_collect_output( - false, - &format!( - "run --allow-{0}={1} run/complex_permissions_test.ts {0} {2}", - permission, - util::testdata_path() - .into_os_string() - .into_string() - .unwrap(), - util::root_path() - .join("Cargo.toml") - .into_os_string() - .into_string() - .unwrap(), - ), - None, - None, - false, - ); - assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); - } - } - - #[test] - fn rw_inside_test_dir() { - const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; - for permission in &PERMISSION_VARIANTS { - let status = util::deno_cmd() - .current_dir(&util::testdata_path()) - .arg("run") - .arg(format!( - "--allow-{0}={1}", - permission, - util::testdata_path() - .into_os_string() - .into_string() - .unwrap() - )) - .arg("run/complex_permissions_test.ts") - .arg(permission) - .arg("run/complex_permissions_test.ts") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - } - } - - #[test] - fn rw_outside_test_and_js_dir() { - const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; - let test_dir = util::testdata_path() - .into_os_string() - .into_string() - .unwrap(); - let js_dir = util::root_path() - .join("js") - .into_os_string() - .into_string() - .unwrap(); - for permission in &PERMISSION_VARIANTS { - let (_, err) = util::run_and_collect_output( - false, - &format!( - "run --allow-{0}={1},{2} run/complex_permissions_test.ts {0} {3}", - permission, - test_dir, - js_dir, - util::root_path() - .join("Cargo.toml") - .into_os_string() - .into_string() - .unwrap(), - ), - None, - None, - false, - ); - assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); - } - } - - #[test] - fn rw_inside_test_and_js_dir() { - const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; - let test_dir = util::testdata_path() - .into_os_string() - .into_string() - .unwrap(); - let js_dir = util::root_path() - .join("js") - .into_os_string() - .into_string() - .unwrap(); - for permission in &PERMISSION_VARIANTS { - let status = util::deno_cmd() - .current_dir(&util::testdata_path()) - .arg("run") - .arg(format!("--allow-{0}={1},{2}", permission, test_dir, js_dir)) - .arg("run/complex_permissions_test.ts") - .arg(permission) - .arg("run/complex_permissions_test.ts") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - } - } - - #[test] - fn rw_relative() { - const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; - for permission in &PERMISSION_VARIANTS { - let status = util::deno_cmd() - .current_dir(&util::testdata_path()) - .arg("run") - .arg(format!("--allow-{0}=.", permission)) - .arg("run/complex_permissions_test.ts") - .arg(permission) - .arg("run/complex_permissions_test.ts") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - } - } - - #[test] - fn rw_no_prefix() { - const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; - for permission in &PERMISSION_VARIANTS { - let status = util::deno_cmd() - .current_dir(&util::testdata_path()) - .arg("run") - .arg(format!("--allow-{0}=tls/../", permission)) - .arg("run/complex_permissions_test.ts") - .arg(permission) - .arg("run/complex_permissions_test.ts") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - } - } - - #[test] - fn net_fetch_allow_localhost_4545() { - let (_, err) = util::run_and_collect_output( - true, - "run --allow-net=localhost:4545 run/complex_permissions_test.ts netFetch http://localhost:4545/", - None, - None, - true, - ); - assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn net_fetch_allow_deno_land() { - let (_, err) = util::run_and_collect_output( - false, - "run --allow-net=deno.land run/complex_permissions_test.ts netFetch http://localhost:4545/", - None, - None, - true, - ); - assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn net_fetch_localhost_4545_fail() { - let (_, err) = util::run_and_collect_output( - false, - "run --allow-net=localhost:4545 run/complex_permissions_test.ts netFetch http://localhost:4546/", - None, - None, - true, - ); - assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn net_fetch_localhost() { - let (_, err) = util::run_and_collect_output( - true, - "run --allow-net=localhost run/complex_permissions_test.ts netFetch http://localhost:4545/ http://localhost:4546/ http://localhost:4547/", - None, - None, - true, - ); - assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn net_connect_allow_localhost_ip_4555() { - let (_, err) = util::run_and_collect_output( - true, - "run --allow-net=127.0.0.1:4545 run/complex_permissions_test.ts netConnect 127.0.0.1:4545", - None, - None, - true, - ); - assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn net_connect_allow_deno_land() { - let (_, err) = util::run_and_collect_output( - false, - "run --allow-net=deno.land run/complex_permissions_test.ts netConnect 127.0.0.1:4546", - None, - None, - true, - ); - assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn net_connect_allow_localhost_ip_4545_fail() { - let (_, err) = util::run_and_collect_output( - false, - "run --allow-net=127.0.0.1:4545 run/complex_permissions_test.ts netConnect 127.0.0.1:4546", - None, - None, - true, - ); - assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn net_connect_allow_localhost_ip() { - let (_, err) = util::run_and_collect_output( - true, - "run --allow-net=127.0.0.1 run/complex_permissions_test.ts netConnect 127.0.0.1:4545 127.0.0.1:4546 127.0.0.1:4547", - None, - None, - true, - ); - assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn net_listen_allow_localhost_4555() { - let (_, err) = util::run_and_collect_output( - true, - "run --allow-net=localhost:4558 run/complex_permissions_test.ts netListen localhost:4558", - None, - None, - false, - ); - assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn net_listen_allow_deno_land() { - let (_, err) = util::run_and_collect_output( - false, - "run --allow-net=deno.land run/complex_permissions_test.ts netListen localhost:4545", - None, - None, - false, - ); - assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn net_listen_allow_localhost_4555_fail() { - let (_, err) = util::run_and_collect_output( - false, - "run --allow-net=localhost:4555 run/complex_permissions_test.ts netListen localhost:4556", - None, - None, - false, - ); - assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn net_listen_allow_localhost() { - // Port 4600 is chosen to not colide with those used by - // target/debug/test_server - let (_, err) = util::run_and_collect_output( - true, - "run --allow-net=localhost run/complex_permissions_test.ts netListen localhost:4600", - None, - None, - false, - ); - assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); - } - - #[test] - fn _061_permissions_request() { - let args = "run --quiet run/061_permissions_request.ts"; - use util::PtyData::*; - util::test_pty2(args, vec![ - Output("⚠️ ️Deno requests read access to \"foo\". Run again with --allow-read to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)] "), - Input("y\n"), - Output("⚠️ ️Deno requests read access to \"bar\". Run again with --allow-read to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)]"), - Input("n\n"), - Output("granted\r\n"), - Output("prompt\r\n"), - Output("denied\r\n"), - ]); - } - - #[test] - fn _062_permissions_request_global() { - let args = "run --quiet run/062_permissions_request_global.ts"; - use util::PtyData::*; - util::test_pty2(args, vec![ - Output("⚠️ ️Deno requests read access. Run again with --allow-read to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)] "), - Input("y\n"), - Output("PermissionStatus { state: \"granted\", onchange: null }\r\n"), - Output("PermissionStatus { state: \"granted\", onchange: null }\r\n"), - Output("PermissionStatus { state: \"granted\", onchange: null }\r\n"), - ]); - } - - itest!(_063_permissions_revoke { - args: "run --allow-read=foo,bar run/063_permissions_revoke.ts", - output: "run/063_permissions_revoke.ts.out", - }); - - itest!(_064_permissions_revoke_global { - args: "run --allow-read=foo,bar run/064_permissions_revoke_global.ts", - output: "run/064_permissions_revoke_global.ts.out", - }); - - #[test] - fn _066_prompt() { - let args = "run --quiet --unstable run/066_prompt.ts"; - use util::PtyData::*; - util::test_pty2( - args, - vec![ - Output("What is your name? [Jane Doe] "), - Input("John Doe\n"), - Output("Your name is John Doe.\r\n"), - Output("What is your name? [Jane Doe] "), - Input("\n"), - Output("Your name is Jane Doe.\r\n"), - Output("Prompt "), - Input("foo\n"), - Output("Your input is foo.\r\n"), - Output("Question 0 [y/N] "), - Input("Y\n"), - Output("Your answer is true\r\n"), - Output("Question 1 [y/N] "), - Input("N\n"), - Output("Your answer is false\r\n"), - Output("Question 2 [y/N] "), - Input("yes\n"), - Output("Your answer is false\r\n"), - Output("Confirm [y/N] "), - Input("\n"), - Output("Your answer is false\r\n"), - Output("What is Windows EOL? "), - Input("windows\n"), - Output("Your answer is \"windows\"\r\n"), - Output("Hi [Enter] "), - Input("\n"), - Output("Alert [Enter] "), - Input("\n"), - Output("The end of test\r\n"), - Output("What is EOF? "), - Input("\n"), - Output("Your answer is null\r\n"), - ], - ); - } - - itest!(dynamic_import_permissions_remote_remote { - args: "run --quiet --reload --allow-net=localhost:4545 dynamic_import/permissions_remote_remote.ts", - output: "dynamic_import/permissions_remote_remote.ts.out", - http_server: true, - exit_code: 1, - }); - - itest!(dynamic_import_permissions_data_remote { - args: "run --quiet --reload --allow-net=localhost:4545 dynamic_import/permissions_data_remote.ts", - output: "dynamic_import/permissions_data_remote.ts.out", - http_server: true, - exit_code: 1, - }); - - itest!(dynamic_import_permissions_blob_remote { - args: "run --quiet --reload --allow-net=localhost:4545 dynamic_import/permissions_blob_remote.ts", - output: "dynamic_import/permissions_blob_remote.ts.out", - http_server: true, - exit_code: 1, - }); - - itest!(dynamic_import_permissions_data_local { - args: "run --quiet --reload --allow-net=localhost:4545 dynamic_import/permissions_data_local.ts", - output: "dynamic_import/permissions_data_local.ts.out", - http_server: true, - exit_code: 1, - }); - - itest!(dynamic_import_permissions_blob_local { - args: "run --quiet --reload --allow-net=localhost:4545 dynamic_import/permissions_blob_local.ts", - output: "dynamic_import/permissions_blob_local.ts.out", - http_server: true, - exit_code: 1, - }); -} - -itest!(tls_starttls { - args: "run --quiet --reload --allow-net --allow-read --unstable --cert tls/RootCA.pem run/tls_starttls.js", - output: "run/tls.out", -}); - -itest!(tls_connecttls { - args: "run --quiet --reload --allow-net --allow-read --cert tls/RootCA.pem run/tls_connecttls.js", - output: "run/tls.out", -}); - -itest!(byte_order_mark { - args: "run --no-check run/byte_order_mark.ts", - output: "run/byte_order_mark.out", -}); - -#[test] -fn issue9750() { - use util::PtyData::*; - util::test_pty2( - "run --prompt run/issue9750.js", - vec![ - Output("Enter 'yy':\r\n"), - Input("yy\n"), - Output("⚠️ ️Deno requests env access. Run again with --allow-env to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)]"), - Input("n\n"), - Output("⚠️ ️Deno requests env access to \"SECRET\". Run again with --allow-env to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)]"), - Input("n\n"), - Output("error: Uncaught (in promise) PermissionDenied: Requires env access to \"SECRET\", run again with the --allow-env flag\r\n"), - ], - ); -} - -// Regression test for https://github.com/denoland/deno/issues/11451. -itest!(dom_exception_formatting { - args: "run run/dom_exception_formatting.ts", - output: "run/dom_exception_formatting.ts.out", - exit_code: 1, -}); - -itest!(long_data_url_formatting { - args: "run run/long_data_url_formatting.ts", - output: "run/long_data_url_formatting.ts.out", - exit_code: 1, -}); - -itest!(eval_context_throw_dom_exception { - args: "run run/eval_context_throw_dom_exception.js", - output: "run/eval_context_throw_dom_exception.js.out", -}); - -#[test] -#[cfg(unix)] -fn navigator_language_unix() { - let (res, _) = util::run_and_collect_output( - true, - "run navigator_language.ts", - None, - Some(vec![("LC_ALL".to_owned(), "pl_PL".to_owned())]), - false, - ); - assert_eq!(res, "pl-PL\n") -} - -#[test] -fn navigator_language() { - let (res, _) = util::run_and_collect_output( - true, - "run navigator_language.ts", - None, - None, - false, - ); - assert!(!res.is_empty()) -} - -#[test] -#[cfg(unix)] -fn navigator_languages_unix() { - let (res, _) = util::run_and_collect_output( - true, - "run navigator_languages.ts", - None, - Some(vec![ - ("LC_ALL".to_owned(), "pl_PL".to_owned()), - ("NO_COLOR".to_owned(), "1".to_owned()), - ]), - false, - ); - assert_eq!(res, "[ \"pl-PL\" ]\n") -} - -#[test] -fn navigator_languages() { - let (res, _) = util::run_and_collect_output( - true, - "run navigator_languages.ts", - None, - None, - false, - ); - assert!(!res.is_empty()) -} - -/// Regression test for https://github.com/denoland/deno/issues/12740. -#[test] -fn issue12740() { - let mod_dir = TempDir::new(); - let mod1_path = mod_dir.path().join("mod1.ts"); - let mod2_path = mod_dir.path().join("mod2.ts"); - let mut deno_cmd = util::deno_cmd(); - std::fs::write(&mod1_path, "").unwrap(); - let status = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg(&mod1_path) - .stderr(Stdio::null()) - .stdout(Stdio::null()) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - std::fs::write(&mod1_path, "export { foo } from \"./mod2.ts\";").unwrap(); - std::fs::write(&mod2_path, "(").unwrap(); - let status = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg(&mod1_path) - .stderr(Stdio::null()) - .stdout(Stdio::null()) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(!status.success()); -} - -/// Regression test for https://github.com/denoland/deno/issues/12807. -#[test] -fn issue12807() { - let mod_dir = TempDir::new(); - let mod1_path = mod_dir.path().join("mod1.ts"); - let mod2_path = mod_dir.path().join("mod2.ts"); - let mut deno_cmd = util::deno_cmd(); - // With a fresh `DENO_DIR`, run a module with a dependency and a type error. - std::fs::write(&mod1_path, "import './mod2.ts'; Deno.exit('0');").unwrap(); - std::fs::write(&mod2_path, "console.log('Hello, world!');").unwrap(); - let status = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--check") - .arg(&mod1_path) - .stderr(Stdio::null()) - .stdout(Stdio::null()) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(!status.success()); - // Fix the type error and run again. - std::fs::write(&mod1_path, "import './mod2.ts'; Deno.exit(0);").unwrap(); - let status = deno_cmd - .current_dir(util::testdata_path()) - .arg("run") - .arg("--check") - .arg(&mod1_path) - .stderr(Stdio::null()) - .stdout(Stdio::null()) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); -} - -itest!(issue_13562 { - args: "run run/issue13562.ts", - output: "run/issue13562.ts.out", -}); - -itest!(import_assertions_static_import { - args: "run --allow-read import_assertions/static_import.ts", - output: "import_assertions/static_import.out", -}); - -itest!(import_assertions_static_export { - args: "run --allow-read import_assertions/static_export.ts", - output: "import_assertions/static_export.out", -}); - -itest!(import_assertions_static_error { - args: "run --allow-read import_assertions/static_error.ts", - output: "import_assertions/static_error.out", - exit_code: 1, -}); - -itest!(import_assertions_dynamic_import { - args: "run --allow-read import_assertions/dynamic_import.ts", - output: "import_assertions/dynamic_import.out", -}); - -itest!(import_assertions_dynamic_error { - args: "run --allow-read import_assertions/dynamic_error.ts", - output: "import_assertions/dynamic_error.out", - exit_code: 1, -}); - -itest!(import_assertions_type_check { - args: "run --allow-read --check import_assertions/type_check.ts", - output: "import_assertions/type_check.out", - exit_code: 1, -}); - -itest!(delete_window { - args: "run run/delete_window.js", - output_str: Some("true\n"), -}); - -itest!(colors_without_global_this { - args: "run run/colors_without_globalThis.js", - output_str: Some("true\n"), -}); - -itest!(config_auto_discovered_for_local_script { - args: "run --quiet run/with_config/frontend_work.ts", - output_str: Some("ok\n"), -}); - -itest!(no_config_auto_discovery_for_local_script { - args: "run --quiet --no-config --check run/with_config/frontend_work.ts", - output: "run/with_config/no_auto_discovery.out", - exit_code: 1, -}); - -itest!(config_not_auto_discovered_for_remote_script { - args: "run --quiet http://127.0.0.1:4545/run/with_config/server_side_work.ts", - output_str: Some("ok\n"), - http_server: true, -}); - -itest!(wasm_streaming_panic_test { - args: "run run/wasm_streaming_panic_test.js", - output: "run/wasm_streaming_panic_test.js.out", - exit_code: 1, -}); - -// Regression test for https://github.com/denoland/deno/issues/13897. -itest!(fetch_async_error_stack { - args: "run --quiet -A run/fetch_async_error_stack.ts", - output: "run/fetch_async_error_stack.ts.out", - exit_code: 1, -}); - -itest!(unstable_ffi_1 { - args: "run run/ffi/unstable_ffi_1.js", - output: "run/ffi/unstable_ffi_1.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_2 { - args: "run run/ffi/unstable_ffi_2.js", - output: "run/ffi/unstable_ffi_2.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_3 { - args: "run run/ffi/unstable_ffi_3.js", - output: "run/ffi/unstable_ffi_3.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_4 { - args: "run run/ffi/unstable_ffi_4.js", - output: "run/ffi/unstable_ffi_4.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_5 { - args: "run run/ffi/unstable_ffi_5.js", - output: "run/ffi/unstable_ffi_5.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_6 { - args: "run run/ffi/unstable_ffi_6.js", - output: "run/ffi/unstable_ffi_6.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_7 { - args: "run run/ffi/unstable_ffi_7.js", - output: "run/ffi/unstable_ffi_7.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_8 { - args: "run run/ffi/unstable_ffi_8.js", - output: "run/ffi/unstable_ffi_8.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_9 { - args: "run run/ffi/unstable_ffi_9.js", - output: "run/ffi/unstable_ffi_9.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_10 { - args: "run run/ffi/unstable_ffi_10.js", - output: "run/ffi/unstable_ffi_10.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_11 { - args: "run run/ffi/unstable_ffi_11.js", - output: "run/ffi/unstable_ffi_11.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_12 { - args: "run run/ffi/unstable_ffi_12.js", - output: "run/ffi/unstable_ffi_12.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_13 { - args: "run run/ffi/unstable_ffi_13.js", - output: "run/ffi/unstable_ffi_13.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_14 { - args: "run run/ffi/unstable_ffi_14.js", - output: "run/ffi/unstable_ffi_14.js.out", - exit_code: 70, -}); - -itest!(unstable_ffi_15 { - args: "run run/ffi/unstable_ffi_15.js", - output: "run/ffi/unstable_ffi_15.js.out", - exit_code: 70, -}); - -itest!(future_check2 { - args: "run --check run/future_check.ts", - output: "run/future_check2.out", -}); - -itest!(event_listener_error { - args: "run --quiet run/event_listener_error.ts", - output: "run/event_listener_error.ts.out", - exit_code: 1, -}); - -itest!(event_listener_error_handled { - args: "run --quiet run/event_listener_error_handled.ts", - output: "run/event_listener_error_handled.ts.out", -}); - -// https://github.com/denoland/deno/pull/14159#issuecomment-1092285446 -itest!(event_listener_error_immediate_exit { - args: "run --quiet run/event_listener_error_immediate_exit.ts", - output: "run/event_listener_error_immediate_exit.ts.out", - exit_code: 1, -}); - -// https://github.com/denoland/deno/pull/14159#issuecomment-1092285446 -itest!(event_listener_error_immediate_exit_worker { - args: - "run --quiet --unstable -A run/event_listener_error_immediate_exit_worker.ts", - output: "run/event_listener_error_immediate_exit_worker.ts.out", - exit_code: 1, -}); - -itest!(set_timeout_error { - args: "run --quiet run/set_timeout_error.ts", - output: "run/set_timeout_error.ts.out", - exit_code: 1, -}); - -itest!(set_timeout_error_handled { - args: "run --quiet run/set_timeout_error_handled.ts", - output: "run/set_timeout_error_handled.ts.out", -}); - -itest!(aggregate_error { - args: "run --quiet run/aggregate_error.ts", - output: "run/aggregate_error.out", - exit_code: 1, -}); - -itest!(complex_error { - args: "run --quiet run/complex_error.ts", - output: "run/complex_error.ts.out", - exit_code: 1, -}); - -// Regression test for https://github.com/denoland/deno/issues/12143. -itest!(js_root_with_ts_check { - args: "run --quiet --check run/js_root_with_ts_check.js", - output: "run/js_root_with_ts_check.js.out", - exit_code: 1, -}); - -#[test] -fn check_local_then_remote() { - let _http_guard = util::http_server(); - let deno_dir = util::new_deno_dir(); - let output = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--check") - .arg("run/remote_type_error/main.ts") - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - let output = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--check=all") - .arg("run/remote_type_error/main.ts") - .env("NO_COLOR", "1") - .stderr(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - let stderr = std::str::from_utf8(&output.stderr).unwrap(); - assert_contains!(stderr, "Type 'string' is not assignable to type 'number'."); -} - -// Regression test for https://github.com/denoland/deno/issues/15163 -itest!(check_js_points_to_ts { - args: "run --quiet --check --config run/checkjs.tsconfig.json run/check_js_points_to_ts/test.js", - output: "run/check_js_points_to_ts/test.js.out", - exit_code: 1, -}); - -itest!(no_prompt_flag { - args: "run --quiet --unstable --no-prompt run/no_prompt.ts", - output_str: Some(""), -}); - -#[test] -fn deno_no_prompt_environment_variable() { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--unstable") - .arg("run/no_prompt.ts") - .env("DENO_NO_PROMPT", "1") - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); -} - -itest!(report_error { - args: "run --quiet run/report_error.ts", - output: "run/report_error.ts.out", - exit_code: 1, -}); - -itest!(report_error_handled { - args: "run --quiet run/report_error_handled.ts", - output: "run/report_error_handled.ts.out", -}); - -// Regression test for https://github.com/denoland/deno/issues/15513. -itest!(report_error_end_of_program { - args: "run --quiet run/report_error_end_of_program.ts", - output: "run/report_error_end_of_program.ts.out", - exit_code: 1, -}); - -itest!(queue_microtask_error { - args: "run --quiet run/queue_microtask_error.ts", - output: "run/queue_microtask_error.ts.out", - exit_code: 1, -}); - -itest!(queue_microtask_error_handled { - args: "run --quiet run/queue_microtask_error_handled.ts", - output: "run/queue_microtask_error_handled.ts.out", -}); - -itest!(spawn_stdout_inherit { - args: "run --quiet --unstable -A run/spawn_stdout_inherit.ts", - output: "run/spawn_stdout_inherit.ts.out", -}); - -itest!(error_name_non_string { - args: "run --quiet run/error_name_non_string.js", - output: "run/error_name_non_string.js.out", - exit_code: 1, -}); - -itest!(custom_inspect_url { - args: "run run/custom_inspect_url.js", - output: "run/custom_inspect_url.js.out", -}); - -itest!(config_json_import { - args: "run --quiet -c jsx/deno-jsx.json run/config_json_import.ts", - output: "run/config_json_import.ts.out", - http_server: true, -}); - -#[test] -fn running_declaration_files() { - let temp_dir = TempDir::new(); - let files = vec!["file.d.ts", "file.d.cts", "file.d.mts"]; - - for file in files { - temp_dir.write(file, ""); - let mut deno_cmd = util::deno_cmd_with_deno_dir(&temp_dir); - let output = deno_cmd - .current_dir(temp_dir.path()) - .args(["run", file]) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()); - } -} - -itest!(test_and_bench_are_noops_in_run { - args: "run run/test_and_bench_in_run.js", - output_str: Some(""), -}); - -itest!(followup_dyn_import_resolved { - args: "run --unstable --allow-read run/followup_dyn_import_resolves/main.ts", - output: "run/followup_dyn_import_resolves/main.ts.out", -}); - -itest!(unhandled_rejection { - args: "run --check run/unhandled_rejection.ts", - output: "run/unhandled_rejection.ts.out", -}); - -itest!(unhandled_rejection_sync_error { - args: "run --check run/unhandled_rejection_sync_error.ts", - output: "run/unhandled_rejection_sync_error.ts.out", -}); - -itest!(nested_error { - args: "run run/nested_error.ts", - output: "run/nested_error.ts.out", - exit_code: 1, -}); - -itest!(node_env_var_allowlist { - args: "run --unstable --no-prompt run/node_env_var_allowlist.ts", - output: "run/node_env_var_allowlist.ts.out", - exit_code: 1, -}); - -#[test] -fn cache_test() { - let _g = util::http_server(); - let deno_dir = TempDir::new(); - let module_url = - url::Url::parse("http://localhost:4545/run/006_url_imports.ts").unwrap(); - let output = Command::new(util::deno_exe_path()) - .env("DENO_DIR", deno_dir.path()) - .current_dir(util::testdata_path()) - .arg("cache") - .arg("--check=all") - .arg("-L") - .arg("debug") - .arg(module_url.to_string()) - .output() - .expect("Failed to spawn script"); - assert!(output.status.success()); - - let prg = util::deno_exe_path(); - let output = Command::new(&prg) - .env("DENO_DIR", deno_dir.path()) - .env("HTTP_PROXY", "http://nil") - .env("NO_COLOR", "1") - .current_dir(util::testdata_path()) - .arg("run") - .arg(module_url.to_string()) - .output() - .expect("Failed to spawn script"); - - let str_output = std::str::from_utf8(&output.stdout).unwrap(); - - let module_output_path = - util::testdata_path().join("run/006_url_imports.ts.out"); - let mut module_output = String::new(); - let mut module_output_file = std::fs::File::open(module_output_path).unwrap(); - module_output_file - .read_to_string(&mut module_output) - .unwrap(); - - assert_eq!(module_output, str_output); -} - -#[test] -fn cache_invalidation_test() { - let deno_dir = TempDir::new(); - let fixture_path = deno_dir.path().join("fixture.ts"); - { - let mut file = std::fs::File::create(fixture_path.clone()) - .expect("could not create fixture"); - file - .write_all(b"console.log(\"42\");") - .expect("could not write fixture"); - } - let output = Command::new(util::deno_exe_path()) - .env("DENO_DIR", deno_dir.path()) - .current_dir(util::testdata_path()) - .arg("run") - .arg(fixture_path.to_str().unwrap()) - .output() - .expect("Failed to spawn script"); - assert!(output.status.success()); - let actual = std::str::from_utf8(&output.stdout).unwrap(); - assert_eq!(actual, "42\n"); - { - let mut file = std::fs::File::create(fixture_path.clone()) - .expect("could not create fixture"); - file - .write_all(b"console.log(\"43\");") - .expect("could not write fixture"); - } - let output = Command::new(util::deno_exe_path()) - .env("DENO_DIR", deno_dir.path()) - .current_dir(util::testdata_path()) - .arg("run") - .arg(fixture_path.to_str().unwrap()) - .output() - .expect("Failed to spawn script"); - assert!(output.status.success()); - let actual = std::str::from_utf8(&output.stdout).unwrap(); - assert_eq!(actual, "43\n"); -} - -#[test] -fn cache_invalidation_test_no_check() { - let deno_dir = TempDir::new(); - let fixture_path = deno_dir.path().join("fixture.ts"); - { - let mut file = std::fs::File::create(fixture_path.clone()) - .expect("could not create fixture"); - file - .write_all(b"console.log(\"42\");") - .expect("could not write fixture"); - } - let output = Command::new(util::deno_exe_path()) - .env("DENO_DIR", deno_dir.path()) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--no-check") - .arg(fixture_path.to_str().unwrap()) - .output() - .expect("Failed to spawn script"); - assert!(output.status.success()); - let actual = std::str::from_utf8(&output.stdout).unwrap(); - assert_eq!(actual, "42\n"); - { - let mut file = std::fs::File::create(fixture_path.clone()) - .expect("could not create fixture"); - file - .write_all(b"console.log(\"43\");") - .expect("could not write fixture"); - } - let output = Command::new(util::deno_exe_path()) - .env("DENO_DIR", deno_dir.path()) - .current_dir(util::testdata_path()) - .arg("run") - .arg("--no-check") - .arg(fixture_path.to_str().unwrap()) - .output() - .expect("Failed to spawn script"); - assert!(output.status.success()); - let actual = std::str::from_utf8(&output.stdout).unwrap(); - assert_eq!(actual, "43\n"); -} - -#[test] -fn ts_dependency_recompilation() { - let t = TempDir::new(); - let ats = t.path().join("a.ts"); - - std::fs::write( - &ats, - " - import { foo } from \"./b.ts\"; - - function print(str: string): void { - console.log(str); - } - - print(foo);", - ) - .unwrap(); - - let bts = t.path().join("b.ts"); - std::fs::write( - &bts, - " - export const foo = \"foo\";", - ) - .unwrap(); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .env("NO_COLOR", "1") - .arg("run") - .arg("--check") - .arg(&ats) - .output() - .expect("failed to spawn script"); - - let stdout_output = std::str::from_utf8(&output.stdout).unwrap().trim(); - let stderr_output = std::str::from_utf8(&output.stderr).unwrap().trim(); - - assert!(stdout_output.ends_with("foo")); - assert!(stderr_output.starts_with("Check")); - - // Overwrite contents of b.ts and run again - std::fs::write( - &bts, - " - export const foo = 5;", - ) - .expect("error writing file"); - - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .env("NO_COLOR", "1") - .arg("run") - .arg("--check") - .arg(&ats) - .output() - .expect("failed to spawn script"); - - let stdout_output = std::str::from_utf8(&output.stdout).unwrap().trim(); - let stderr_output = std::str::from_utf8(&output.stderr).unwrap().trim(); - - // error: TS2345 [ERROR]: Argument of type '5' is not assignable to parameter of type 'string'. - assert!(stderr_output.contains("TS2345")); - assert!(!output.status.success()); - assert!(stdout_output.is_empty()); -} - -#[test] -fn basic_auth_tokens() { - let _g = util::http_server(); - - let output = util::deno_cmd() - .current_dir(util::root_path()) - .arg("run") - .arg("http://127.0.0.1:4554/run/001_hello.js") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - - assert!(!output.status.success()); - - let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); - assert!(stdout_str.is_empty()); - - let stderr_str = std::str::from_utf8(&output.stderr).unwrap().trim(); - eprintln!("{}", stderr_str); - - assert!(stderr_str - .contains("Module not found \"http://127.0.0.1:4554/run/001_hello.js\".")); - - let output = util::deno_cmd() - .current_dir(util::root_path()) - .arg("run") - .arg("http://127.0.0.1:4554/run/001_hello.js") - .env("DENO_AUTH_TOKENS", "testuser123:testpassabc@127.0.0.1:4554") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - - let stderr_str = std::str::from_utf8(&output.stderr).unwrap().trim(); - eprintln!("{}", stderr_str); - - assert!(output.status.success()); - - let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); - assert_eq!(util::strip_ansi_codes(stdout_str), "Hello World"); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn test_resolve_dns() { - use std::net::SocketAddr; - use std::str::FromStr; - use std::sync::Arc; - use std::time::Duration; - use tokio::net::TcpListener; - use tokio::net::UdpSocket; - use tokio::sync::oneshot; - use trust_dns_server::authority::Catalog; - use trust_dns_server::authority::ZoneType; - use trust_dns_server::proto::rr::Name; - use trust_dns_server::store::in_memory::InMemoryAuthority; - use trust_dns_server::ServerFuture; - - const DNS_PORT: u16 = 4553; - - // Setup DNS server for testing - async fn run_dns_server(tx: oneshot::Sender<()>) { - let zone_file = std::fs::read_to_string( - util::testdata_path().join("run/resolve_dns.zone.in"), - ) - .unwrap(); - let lexer = Lexer::new(&zone_file); - let records = Parser::new().parse( - lexer, - Some(Name::from_str("example.com").unwrap()), - None, - ); - if records.is_err() { - panic!("failed to parse: {:?}", records.err()) - } - let (origin, records) = records.unwrap(); - let authority = Box::new(Arc::new( - InMemoryAuthority::new(origin, records, ZoneType::Primary, false) - .unwrap(), - )); - let mut catalog: Catalog = Catalog::new(); - catalog.upsert(Name::root().into(), authority); - - let mut server_fut = ServerFuture::new(catalog); - let socket_addr = SocketAddr::from(([127, 0, 0, 1], DNS_PORT)); - let tcp_listener = TcpListener::bind(socket_addr).await.unwrap(); - let udp_socket = UdpSocket::bind(socket_addr).await.unwrap(); - server_fut.register_socket(udp_socket); - server_fut.register_listener(tcp_listener, Duration::from_secs(2)); - - // Notifies that the DNS server is ready - tx.send(()).unwrap(); - - server_fut.block_until_done().await.unwrap(); - } - - let (ready_tx, ready_rx) = oneshot::channel(); - let dns_server_fut = run_dns_server(ready_tx); - let handle = tokio::spawn(dns_server_fut); - - // Waits for the DNS server to be ready - ready_rx.await.unwrap(); - - // Pass: `--allow-net` - { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .env("NO_COLOR", "1") - .arg("run") - .arg("--check") - .arg("--allow-net") - .arg("run/resolve_dns.ts") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - let err = String::from_utf8_lossy(&output.stderr); - let out = String::from_utf8_lossy(&output.stdout); - println!("{}", err); - assert!(output.status.success()); - assert!(err.starts_with("Check file")); - - let expected = std::fs::read_to_string( - util::testdata_path().join("run/resolve_dns.ts.out"), - ) - .unwrap(); - assert_eq!(expected, out); - } - - // Pass: `--allow-net=127.0.0.1:4553` - { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .env("NO_COLOR", "1") - .arg("run") - .arg("--check") - .arg("--allow-net=127.0.0.1:4553") - .arg("run/resolve_dns.ts") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - let err = String::from_utf8_lossy(&output.stderr); - let out = String::from_utf8_lossy(&output.stdout); - assert!(output.status.success()); - assert!(err.starts_with("Check file")); - - let expected = std::fs::read_to_string( - util::testdata_path().join("run/resolve_dns.ts.out"), - ) - .unwrap(); - assert_eq!(expected, out); - } - - // Permission error: `--allow-net=deno.land` - { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .env("NO_COLOR", "1") - .arg("run") - .arg("--check") - .arg("--allow-net=deno.land") - .arg("run/resolve_dns.ts") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - let err = String::from_utf8_lossy(&output.stderr); - let out = String::from_utf8_lossy(&output.stdout); - assert!(!output.status.success()); - assert!(err.starts_with("Check file")); - assert!(err.contains(r#"error: Uncaught PermissionDenied: Requires net access to "127.0.0.1:4553""#)); - assert!(out.is_empty()); - } - - // Permission error: no permission specified - { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .env("NO_COLOR", "1") - .arg("run") - .arg("--check") - .arg("run/resolve_dns.ts") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - let err = String::from_utf8_lossy(&output.stderr); - let out = String::from_utf8_lossy(&output.stdout); - assert!(!output.status.success()); - assert!(err.starts_with("Check file")); - assert!(err.contains(r#"error: Uncaught PermissionDenied: Requires net access to "127.0.0.1:4553""#)); - assert!(out.is_empty()); - } - - handle.abort(); -} - -#[tokio::test] -async fn http2_request_url() { - // TLS streams require the presence of an ambient local task set to gracefully - // close dropped connections in the background. - LocalSet::new() - .run_until(async { - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--unstable") - .arg("--quiet") - .arg("--allow-net") - .arg("--allow-read") - .arg("./run/http2_request_url.ts") - .arg("4506") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let stdout = child.stdout.as_mut().unwrap(); - let mut buffer = [0; 5]; - let read = stdout.read(&mut buffer).unwrap(); - assert_eq!(read, 5); - let msg = std::str::from_utf8(&buffer).unwrap(); - assert_eq!(msg, "READY"); - - let cert = reqwest::Certificate::from_pem(include_bytes!( - "../testdata/tls/RootCA.crt" - )) - .unwrap(); - - let client = reqwest::Client::builder() - .add_root_certificate(cert) - .http2_prior_knowledge() - .build() - .unwrap(); - - let res = client.get("http://127.0.0.1:4506").send().await.unwrap(); - assert_eq!(200, res.status()); - - let body = res.text().await.unwrap(); - assert_eq!(body, "http://127.0.0.1:4506/"); - - child.kill().unwrap(); - child.wait().unwrap(); - }) - .await; -} - -#[cfg(not(windows))] -#[test] -fn set_raw_should_not_panic_on_no_tty() { - let output = util::deno_cmd() - .arg("eval") - .arg("Deno.stdin.setRaw(true)") - // stdin set to piped so it certainly does not refer to TTY - .stdin(std::process::Stdio::piped()) - // stderr is piped so we can capture output. - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - let stderr = std::str::from_utf8(&output.stderr).unwrap().trim(); - assert!(stderr.contains("BadResource")); -} - -#[test] -fn timeout_clear() { - // https://github.com/denoland/deno/issues/7599 - - use std::time::Duration; - use std::time::Instant; - - let source_code = r#" -const handle = setTimeout(() => { - console.log("timeout finish"); -}, 10000); -clearTimeout(handle); -console.log("finish"); -"#; - - let mut p = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("-") - .stdin(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let stdin = p.stdin.as_mut().unwrap(); - stdin.write_all(source_code.as_bytes()).unwrap(); - let start = Instant::now(); - let status = p.wait().unwrap(); - let end = Instant::now(); - assert!(status.success()); - // check that program did not run for 10 seconds - // for timeout to clear - assert!(end - start < Duration::new(10, 0)); -} - -#[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::testdata_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!(error_cause { - args: "run run/error_cause.ts", - output: "run/error_cause.ts.out", - exit_code: 1, -}); - -itest!(error_cause_recursive_aggregate { - args: "run error_cause_recursive_aggregate.ts", - output: "error_cause_recursive_aggregate.ts.out", - exit_code: 1, -}); - -itest!(error_cause_recursive_tail { - args: "run error_cause_recursive_tail.ts", - output: "error_cause_recursive_tail.ts.out", - exit_code: 1, -}); - -itest!(error_cause_recursive { - args: "run run/error_cause_recursive.ts", - output: "run/error_cause_recursive.ts.out", - exit_code: 1, -}); - -#[test] -fn websocket() { - let _g = util::http_server(); - - let script = util::testdata_path().join("run/websocket_test.ts"); - let root_ca = util::testdata_path().join("tls/RootCA.pem"); - let status = util::deno_cmd() - .arg("test") - .arg("--unstable") - .arg("--allow-net") - .arg("--cert") - .arg(root_ca) - .arg(script) - .spawn() - .unwrap() - .wait() - .unwrap(); - - assert!(status.success()); -} - -#[ignore] -#[test] -fn websocketstream() { - let _g = util::http_server(); - - let script = util::testdata_path().join("run/websocketstream_test.ts"); - let root_ca = util::testdata_path().join("tls/RootCA.pem"); - let status = util::deno_cmd() - .arg("test") - .arg("--unstable") - .arg("--allow-net") - .arg("--cert") - .arg(root_ca) - .arg(script) - .spawn() - .unwrap() - .wait() - .unwrap(); - - assert!(status.success()); -} - -#[test] -fn websocketstream_ping() { - use deno_runtime::deno_websocket::tokio_tungstenite::tungstenite; - let _g = util::http_server(); - - let script = util::testdata_path().join("run/websocketstream_ping_test.ts"); - let root_ca = util::testdata_path().join("tls/RootCA.pem"); - let mut child = util::deno_cmd() - .arg("test") - .arg("--unstable") - .arg("--allow-net") - .arg("--cert") - .arg(root_ca) - .arg(script) - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let server = std::net::TcpListener::bind("127.0.0.1:4513").unwrap(); - let (stream, _) = server.accept().unwrap(); - let mut socket = tungstenite::accept(stream).unwrap(); - socket - .write_message(tungstenite::Message::Text(String::from("A"))) - .unwrap(); - socket - .write_message(tungstenite::Message::Ping(vec![])) - .unwrap(); - socket - .write_message(tungstenite::Message::Text(String::from("B"))) - .unwrap(); - let message = socket.read_message().unwrap(); - assert_eq!(message, tungstenite::Message::Pong(vec![])); - socket - .write_message(tungstenite::Message::Text(String::from("C"))) - .unwrap(); - socket.close(None).unwrap(); - - assert!(child.wait().unwrap().success()); -} - -#[test] -fn websocket_server_multi_field_connection_header() { - let script = util::testdata_path() - .join("run/websocket_server_multi_field_connection_header_test.ts"); - let root_ca = util::testdata_path().join("tls/RootCA.pem"); - let mut child = util::deno_cmd() - .arg("run") - .arg("--unstable") - .arg("--allow-net") - .arg("--cert") - .arg(root_ca) - .arg(script) - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stdout = child.stdout.as_mut().unwrap(); - let mut buffer = [0; 5]; - let read = stdout.read(&mut buffer).unwrap(); - assert_eq!(read, 5); - let msg = std::str::from_utf8(&buffer).unwrap(); - assert_eq!(msg, "READY"); - - let req = http::request::Builder::new() - .header(http::header::CONNECTION, "keep-alive, Upgrade") - .uri("ws://localhost:4319") - .body(()) - .unwrap(); - let (mut socket, _) = - deno_runtime::deno_websocket::tokio_tungstenite::tungstenite::connect(req) - .unwrap(); - let message = socket.read_message().unwrap(); - assert_eq!(message, deno_runtime::deno_websocket::tokio_tungstenite::tungstenite::Message::Close(None)); - socket.close(None).unwrap(); - assert!(child.wait().unwrap().success()); -} - -// TODO(bartlomieju): this should use `deno run`, not `deno test`; but the -// test hangs then. https://github.com/denoland/deno/issues/14283 -#[test] -#[ignore] -fn websocket_server_idletimeout() { - let script = - util::testdata_path().join("run/websocket_server_idletimeout.ts"); - let root_ca = util::testdata_path().join("tls/RootCA.pem"); - let mut child = util::deno_cmd() - .arg("test") - .arg("--unstable") - .arg("--allow-net") - .arg("--cert") - .arg(root_ca) - .arg(script) - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let stdout = child.stdout.as_mut().unwrap(); - let mut buffer = [0; 5]; - let read = stdout.read(&mut buffer).unwrap(); - assert_eq!(read, 5); - let msg = std::str::from_utf8(&buffer).unwrap(); - assert_eq!(msg, "READY"); - - let req = http::request::Builder::new() - .uri("ws://localhost:4509") - .body(()) - .unwrap(); - let (_ws, _request) = - deno_runtime::deno_websocket::tokio_tungstenite::tungstenite::connect(req) - .unwrap(); - - assert!(child.wait().unwrap().success()); -} - -itest!(auto_discover_lockfile { - args: "run run/auto_discover_lockfile/main.ts", - output: "run/auto_discover_lockfile/main.out", - http_server: true, - exit_code: 10, -}); - -itest!(no_lock_flag { - args: "run --no-lock run/no_lock_flag/main.ts", - output: "run/no_lock_flag/main.out", - http_server: true, - exit_code: 0, -}); - -// Check https://github.com/denoland/deno_std/issues/2882 -itest!(flash_shutdown { - args: "run --unstable --allow-net run/flash_shutdown/main.ts", - exit_code: 0, -}); - -itest!(permission_args { - args: "run run/001_hello.js --allow-net", - output: "run/permission_args.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], -}); - -itest!(permission_args_quiet { - args: "run --quiet run/001_hello.js --allow-net", - output: "run/001_hello.js.out", -}); diff --git a/cli/tests/integration/task_tests.rs b/cli/tests/integration/task_tests.rs deleted file mode 100644 index bc6ddee3b1..0000000000 --- a/cli/tests/integration/task_tests.rs +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use crate::itest; - -// Most of the tests for this are in deno_task_shell. -// These tests are intended to only test integration. - -itest!(task_no_args { - args: "task -q --config task/deno.json", - output: "task/task_no_args.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], - exit_code: 1, -}); - -itest!(task_cwd { - args: "task -q --config task/deno.json --cwd .. echo_cwd", - output: "task/task_cwd.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], - exit_code: 0, -}); - -itest!(task_init_cwd { - args: "task -q --config task/deno.json --cwd .. echo_init_cwd", - output: "task/task_init_cwd.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], - exit_code: 0, -}); - -itest!(task_init_cwd_already_set { - args: "task -q --config task/deno.json echo_init_cwd", - output: "task/task_init_cwd_already_set.out", - envs: vec![ - ("NO_COLOR".to_string(), "1".to_string()), - ("INIT_CWD".to_string(), "HELLO".to_string()) - ], - exit_code: 0, -}); - -itest!(task_cwd_resolves_config_from_specified_dir { - args: "task -q --cwd task", - output: "task/task_no_args.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], - exit_code: 1, -}); - -itest!(task_non_existent { - args: "task --config task/deno.json non_existent", - output: "task/task_non_existent.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], - exit_code: 1, -}); - -#[test] -fn task_emoji() { - // this bug only appears when using a pty/tty - let args = "task --config task/deno.json echo_emoji"; - use test_util::PtyData::*; - test_util::test_pty2(args, vec![Output("Task echo_emoji echo 🔥\r\n🔥")]); -} - -itest!(task_boolean_logic { - args: "task -q --config task/deno.json boolean_logic", - output: "task/task_boolean_logic.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], -}); - -itest!(task_exit_code_5 { - args: "task --config task/deno.json exit_code_5", - output: "task/task_exit_code_5.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], - exit_code: 5, -}); - -itest!(task_additional_args { - args: "task -q --config task/deno.json echo 2", - output: "task/task_additional_args.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], -}); - -itest!(task_additional_args_no_shell_expansion { - args_vec: vec![ - "task", - "-q", - "--config", - "task/deno.json", - "echo", - "$(echo 5)" - ], - output: "task/task_additional_args_no_shell_expansion.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], -}); - -itest!(task_additional_args_nested_strings { - args_vec: vec![ - "task", - "-q", - "--config", - "task/deno.json", - "echo", - "string \"quoted string\"" - ], - output: "task/task_additional_args_nested_strings.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], -}); - -itest!(task_additional_args_no_logic { - args_vec: vec![ - "task", - "-q", - "--config", - "task/deno.json", - "echo", - "||", - "echo", - "5" - ], - output: "task/task_additional_args_no_logic.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], -}); - -itest!(task_deno_exe_no_env { - args_vec: vec!["task", "-q", "--config", "task/deno.json", "deno_echo"], - output: "task/task_deno_exe_no_env.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], - env_clear: true, -}); - -itest!(task_piped_stdin { - args_vec: vec!["task", "-q", "--config", "task/deno.json", "piped"], - output: "task/task_piped_stdin.out", - envs: vec![("NO_COLOR".to_string(), "1".to_string())], -}); diff --git a/cli/tests/integration/test_tests.rs b/cli/tests/integration/test_tests.rs deleted file mode 100644 index 02c4256b12..0000000000 --- a/cli/tests/integration/test_tests.rs +++ /dev/null @@ -1,449 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use crate::itest; -use deno_core::url::Url; -use test_util as util; - -#[test] -fn no_color() { - let (out, _) = util::run_and_collect_output( - false, - "test test/no_color.ts", - None, - Some(vec![("NO_COLOR".to_owned(), "true".to_owned())]), - false, - ); - // ANSI escape codes should be stripped. - assert!(out.contains("success ... ok")); - assert!(out.contains("fail ... FAILED")); - assert!(out.contains("ignored ... ignored")); - assert!(out.contains("FAILED | 1 passed | 1 failed | 1 ignored")); -} - -itest!(overloads { - args: "test test/overloads.ts", - exit_code: 0, - output: "test/overloads.out", -}); - -itest!(meta { - args: "test test/meta.ts", - exit_code: 0, - output: "test/meta.out", -}); - -itest!(pass { - args: "test test/pass.ts", - exit_code: 0, - output: "test/pass.out", -}); - -itest!(ignore { - args: "test test/ignore.ts", - exit_code: 0, - output: "test/ignore.out", -}); - -itest!(ignore_permissions { - args: "test --unstable test/ignore_permissions.ts", - exit_code: 0, - output: "test/ignore_permissions.out", -}); - -itest!(fail { - args: "test test/fail.ts", - exit_code: 1, - output: "test/fail.out", -}); - -itest!(collect { - args: "test --ignore=test/collect/ignore test/collect", - exit_code: 0, - output: "test/collect.out", -}); - -itest!(test_with_config { - args: "test --config test/collect/deno.jsonc test/collect", - exit_code: 0, - output: "test/collect.out", -}); - -itest!(test_with_config2 { - args: "test --config test/collect/deno2.jsonc test/collect", - exit_code: 0, - output: "test/collect2.out", -}); - -itest!(test_with_malformed_config { - args: "test --config test/collect/deno.malformed.jsonc", - exit_code: 1, - output: "test/collect_with_malformed_config.out", -}); - -itest!(parallel_flag { - args: "test test/short-pass.ts --parallel", - exit_code: 0, - output: "test/short-pass.out", -}); - -itest!(parallel_flag_with_env_variable { - args: "test test/short-pass.ts --parallel", - envs: vec![("DENO_JOBS".to_owned(), "2".to_owned())], - exit_code: 0, - output: "test/short-pass.out", -}); - -itest!(jobs_flag { - args: "test test/short-pass.ts --jobs", - exit_code: 0, - output: "test/short-pass-jobs-flag-warning.out", -}); - -itest!(jobs_flag_with_numeric_value { - args: "test test/short-pass.ts --jobs=2", - exit_code: 0, - output: "test/short-pass-jobs-flag-warning.out", -}); - -itest!(load_unload { - args: "test test/load_unload.ts", - exit_code: 0, - output: "test/load_unload.out", -}); - -itest!(interval { - args: "test test/interval.ts", - exit_code: 0, - output: "test/interval.out", -}); - -itest!(doc { - args: "test --doc --allow-all test/doc.ts", - exit_code: 1, - output: "test/doc.out", -}); - -itest!(doc_only { - args: "test --doc --allow-all test/doc_only", - exit_code: 0, - output: "test/doc_only.out", -}); - -itest!(markdown { - args: "test --doc --allow-all test/markdown.md", - exit_code: 1, - output: "test/markdown.out", -}); - -itest!(markdown_windows { - args: "test --doc --allow-all test/markdown_windows.md", - exit_code: 1, - output: "test/markdown_windows.out", -}); - -itest!(markdown_full_block_names { - args: "test --doc --allow-all test/markdown_full_block_names.md", - exit_code: 1, - output: "test/markdown_full_block_names.out", -}); - -itest!(markdown_ignore_html_comment { - args: "test --doc --allow-all test/markdown_with_comment.md", - exit_code: 1, - output: "test/markdown_with_comment.out", -}); - -itest!(text { - args: "test --doc --allow-all test/text.md", - exit_code: 0, - output: "test/text.out", -}); - -itest!(quiet { - args: "test --quiet test/quiet.ts", - exit_code: 0, - output: "test/quiet.out", -}); - -itest!(fail_fast { - args: "test --fail-fast test/fail_fast.ts", - exit_code: 1, - output: "test/fail_fast.out", -}); - -itest!(only { - args: "test test/only.ts", - exit_code: 1, - output: "test/only.out", -}); - -itest!(no_check { - args: "test --no-check test/no_check.ts", - exit_code: 1, - output: "test/no_check.out", -}); - -itest!(no_run { - args: "test --unstable --no-run test/no_run.ts", - output: "test/no_run.out", - exit_code: 1, -}); - -itest!(allow_all { - args: "test --unstable --allow-all test/allow_all.ts", - exit_code: 0, - output: "test/allow_all.out", -}); - -itest!(allow_none { - args: "test --unstable test/allow_none.ts", - exit_code: 1, - output: "test/allow_none.out", -}); - -itest!(ops_sanitizer_unstable { - args: "test --unstable --trace-ops test/ops_sanitizer_unstable.ts", - exit_code: 1, - output: "test/ops_sanitizer_unstable.out", -}); - -itest!(ops_sanitizer_timeout_failure { - args: "test test/ops_sanitizer_timeout_failure.ts", - output: "test/ops_sanitizer_timeout_failure.out", -}); - -itest!(ops_sanitizer_multiple_timeout_tests { - args: "test --trace-ops test/ops_sanitizer_multiple_timeout_tests.ts", - exit_code: 1, - output: "test/ops_sanitizer_multiple_timeout_tests.out", -}); - -itest!(ops_sanitizer_multiple_timeout_tests_no_trace { - args: "test test/ops_sanitizer_multiple_timeout_tests.ts", - exit_code: 1, - output: "test/ops_sanitizer_multiple_timeout_tests_no_trace.out", -}); - -// TODO(@littledivy): re-enable this test, recent optimizations made output non deterministic. -// https://github.com/denoland/deno/issues/14268 -// -// itest!(ops_sanitizer_missing_details { -// args: "test --allow-write --allow-read test/ops_sanitizer_missing_details.ts", -// exit_code: 1, -// output: "test/ops_sanitizer_missing_details.out", -// }); - -itest!(ops_sanitizer_nexttick { - args: "test test/ops_sanitizer_nexttick.ts", - output: "test/ops_sanitizer_nexttick.out", -}); - -itest!(resource_sanitizer { - args: "test --allow-read test/resource_sanitizer.ts", - exit_code: 1, - output: "test/resource_sanitizer.out", -}); - -itest!(exit_sanitizer { - args: "test test/exit_sanitizer.ts", - output: "test/exit_sanitizer.out", - exit_code: 1, -}); - -itest!(clear_timeout { - args: "test test/clear_timeout.ts", - exit_code: 0, - output: "test/clear_timeout.out", -}); - -itest!(finally_timeout { - args: "test test/finally_timeout.ts", - exit_code: 1, - output: "test/finally_timeout.out", -}); - -itest!(unresolved_promise { - args: "test test/unresolved_promise.ts", - exit_code: 1, - output: "test/unresolved_promise.out", -}); - -itest!(unhandled_rejection { - args: "test test/unhandled_rejection.ts", - exit_code: 1, - output: "test/unhandled_rejection.out", -}); - -itest!(filter { - args: "test --filter=foo test/filter", - exit_code: 0, - output: "test/filter.out", -}); - -itest!(shuffle { - args: "test --shuffle test/shuffle", - exit_code: 0, - output_str: Some("[WILDCARD]"), -}); - -itest!(shuffle_with_seed { - args: "test --shuffle=42 test/shuffle", - exit_code: 0, - output: "test/shuffle.out", -}); - -itest!(aggregate_error { - args: "test --quiet test/aggregate_error.ts", - exit_code: 1, - output: "test/aggregate_error.out", -}); - -itest!(steps_passing_steps { - args: "test test/steps/passing_steps.ts", - exit_code: 0, - output: "test/steps/passing_steps.out", -}); - -itest!(steps_failing_steps { - args: "test test/steps/failing_steps.ts", - exit_code: 1, - output: "test/steps/failing_steps.out", -}); - -itest!(steps_ignored_steps { - args: "test test/steps/ignored_steps.ts", - exit_code: 0, - output: "test/steps/ignored_steps.out", -}); - -itest!(steps_invalid_usage { - args: "test test/steps/invalid_usage.ts", - exit_code: 1, - output: "test/steps/invalid_usage.out", -}); - -itest!(steps_output_within { - args: "test test/steps/output_within.ts", - exit_code: 0, - output: "test/steps/output_within.out", -}); - -itest!(no_prompt_by_default { - args: "test --quiet test/no_prompt_by_default.ts", - exit_code: 1, - output: "test/no_prompt_by_default.out", -}); - -itest!(no_prompt_with_denied_perms { - args: "test --quiet --allow-read test/no_prompt_with_denied_perms.ts", - exit_code: 1, - output: "test/no_prompt_with_denied_perms.out", -}); - -itest!(test_with_custom_jsx { - args: "test --quiet --allow-read test/hello_world.ts --config=test/deno_custom_jsx.json", - exit_code: 0, - output: "test/hello_world.out", -}); - -#[test] -fn captured_output() { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("test") - .arg("--allow-run") - .arg("--allow-read") - .arg("--unstable") - .arg("test/captured_output.ts") - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - - let output_start = "------- output -------"; - let output_end = "----- output end -----"; - assert!(output.status.success()); - let output_text = String::from_utf8(output.stdout).unwrap(); - let start = output_text.find(output_start).unwrap() + output_start.len(); - let end = output_text.find(output_end).unwrap(); - // replace zero width space that may appear in test output due - // to test runner output flusher - let output_text = output_text[start..end] - .replace('\u{200B}', "") - .trim() - .to_string(); - let mut lines = output_text.lines().collect::>(); - // the output is racy on either stdout or stderr being flushed - // from the runtime into the rust code, so sort it... the main - // thing here to ensure is that we're capturing the output in - // this block on stdout - lines.sort_unstable(); - assert_eq!(lines.join(" "), "0 1 2 3 4 5 6 7 8 9"); -} - -#[test] -fn recursive_permissions_pledge() { - let output = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("test") - .arg("test/recursive_permissions_pledge.js") - .stderr(std::process::Stdio::piped()) - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - assert!(String::from_utf8(output.stderr).unwrap().contains( - "pledge test permissions called before restoring previous pledge" - )); -} - -#[test] -fn file_protocol() { - let file_url = - Url::from_file_path(util::testdata_path().join("test/file_protocol.ts")) - .unwrap() - .to_string(); - - (util::CheckOutputIntegrationTest { - args_vec: vec!["test", &file_url], - exit_code: 0, - output: "test/file_protocol.out", - ..Default::default() - }) - .run(); -} - -itest!(uncaught_errors { - args: "test --quiet test/uncaught_errors_1.ts test/uncaught_errors_2.ts test/uncaught_errors_3.ts", - output: "test/uncaught_errors.out", - exit_code: 1, -}); - -itest!(check_local_by_default { - args: "test --quiet test/check_local_by_default.ts", - output: "test/check_local_by_default.out", - http_server: true, -}); - -itest!(check_local_by_default2 { - args: "test --quiet test/check_local_by_default2.ts", - output: "test/check_local_by_default2.out", - http_server: true, - exit_code: 1, -}); - -itest!(non_error_thrown { - args: "test --quiet test/non_error_thrown.ts", - output: "test/non_error_thrown.out", - exit_code: 1, -}); - -itest!(parallel_output { - args: "test --parallel --reload test/parallel_output.ts", - output: "test/parallel_output.out", - exit_code: 1, -}); diff --git a/cli/tests/integration/upgrade_tests.rs b/cli/tests/integration/upgrade_tests.rs deleted file mode 100644 index 959d46fb42..0000000000 --- a/cli/tests/integration/upgrade_tests.rs +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use std::process::{Command, Stdio}; -use test_util as util; -use test_util::TempDir; - -// Warning: this test requires internet access. -// TODO(#7412): reenable. test is flaky -#[test] -#[ignore] -fn upgrade_in_tmpdir() { - let temp_dir = TempDir::new(); - let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); - assert!(exe_path.exists()); - let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); - let status = Command::new(&exe_path) - .arg("upgrade") - .arg("--force") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - let _mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); - // TODO(ry) assert!(mtime1 < mtime2); -} - -// Warning: this test requires internet access. -// TODO(#7412): reenable. test is flaky -#[test] -#[ignore] -fn upgrade_with_space_in_path() { - let temp_dir = TempDir::new_with_prefix("directory with spaces"); - let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); - assert!(exe_path.exists()); - let status = Command::new(&exe_path) - .arg("upgrade") - .arg("--force") - .env("TMP", temp_dir.path()) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); -} - -// Warning: this test requires internet access. -// TODO(#7412): reenable. test is flaky -#[test] -#[ignore] -fn upgrade_with_version_in_tmpdir() { - let temp_dir = TempDir::new(); - let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); - assert!(exe_path.exists()); - let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); - let status = Command::new(&exe_path) - .arg("upgrade") - .arg("--force") - .arg("--version") - .arg("1.11.5") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - let upgraded_deno_version = String::from_utf8( - Command::new(&exe_path).arg("-V").output().unwrap().stdout, - ) - .unwrap(); - assert!(upgraded_deno_version.contains("1.11.5")); - let _mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); - // TODO(ry) assert!(mtime1 < mtime2); -} - -// Warning: this test requires internet access. -// TODO(#7412): reenable. test is flaky -#[test] -#[ignore] -fn upgrade_with_canary_in_tmpdir() { - let temp_dir = TempDir::new(); - let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); - assert!(exe_path.exists()); - let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); - let status = Command::new(&exe_path) - .arg("upgrade") - .arg("--canary") - .arg("--version") - .arg("e6685f0f01b8a11a5eaff020f5babcfde76b3038") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - let upgraded_deno_version = String::from_utf8( - Command::new(&exe_path).arg("-V").output().unwrap().stdout, - ) - .unwrap(); - assert!(upgraded_deno_version.contains("e6685f0")); - let _mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); - // TODO(ry) assert!(mtime1 < mtime2); -} - -// Warning: this test requires internet access. -// TODO(#7412): reenable. test is flaky -#[test] -#[ignore] -fn upgrade_with_out_in_tmpdir() { - let temp_dir = TempDir::new(); - let exe_path = temp_dir.path().join("deno"); - let new_exe_path = temp_dir.path().join("foo"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); - assert!(exe_path.exists()); - let mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); - let status = Command::new(&exe_path) - .arg("upgrade") - .arg("--version") - .arg("1.11.5") - .arg("--output") - .arg(new_exe_path.to_str().unwrap()) - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - assert!(new_exe_path.exists()); - let mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); - assert_eq!(mtime1, mtime2); // Original exe_path was not changed. - - let v = String::from_utf8( - Command::new(&new_exe_path) - .arg("-V") - .output() - .unwrap() - .stdout, - ) - .unwrap(); - assert!(v.contains("1.11.5")); -} - -// Warning: this test requires internet access. -// TODO(#7412): reenable. test is flaky -#[test] -#[ignore] -fn upgrade_invalid_stable_version() { - let temp_dir = TempDir::new(); - let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); - assert!(exe_path.exists()); - let output = Command::new(&exe_path) - .arg("upgrade") - .arg("--version") - .arg("foobar") - .stderr(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - assert_eq!( - "error: Invalid semver passed\n", - util::strip_ansi_codes(&String::from_utf8(output.stderr).unwrap()) - ); -} - -// Warning: this test requires internet access. -// TODO(#7412): reenable. test is flaky -#[test] -#[ignore] -fn upgrade_invalid_canary_version() { - let temp_dir = TempDir::new(); - let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); - assert!(exe_path.exists()); - let output = Command::new(&exe_path) - .arg("upgrade") - .arg("--canary") - .arg("--version") - .arg("foobar") - .stderr(Stdio::piped()) - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(!output.status.success()); - assert_eq!( - "error: Invalid commit hash passed\n", - util::strip_ansi_codes(&String::from_utf8(output.stderr).unwrap()) - ); -} diff --git a/cli/tests/integration/vendor_tests.rs b/cli/tests/integration/vendor_tests.rs deleted file mode 100644 index efd57b96d9..0000000000 --- a/cli/tests/integration/vendor_tests.rs +++ /dev/null @@ -1,574 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use deno_core::serde_json; -use deno_core::serde_json::json; -use pretty_assertions::assert_eq; -use std::fmt::Write as _; -use std::path::PathBuf; -use std::process::Stdio; -use test_util as util; -use test_util::TempDir; -use util::http_server; -use util::new_deno_dir; - -#[test] -fn output_dir_exists() { - let t = TempDir::new(); - t.write("mod.ts", ""); - t.create_dir_all("vendor"); - t.write("vendor/mod.ts", ""); - - let deno = util::deno_cmd() - .current_dir(t.path()) - .env("NO_COLOR", "1") - .arg("vendor") - .arg("mod.ts") - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!( - String::from_utf8_lossy(&output.stderr).trim(), - concat!( - "error: Output directory was not empty. Please specify an empty ", - "directory or use --force to ignore this error and potentially ", - "overwrite its contents.", - ), - ); - assert!(!output.status.success()); - - // ensure it errors when using the `--output` arg too - let deno = util::deno_cmd() - .current_dir(t.path()) - .env("NO_COLOR", "1") - .arg("vendor") - .arg("--output") - .arg("vendor") - .arg("mod.ts") - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!( - String::from_utf8_lossy(&output.stderr).trim(), - concat!( - "error: Output directory was not empty. Please specify an empty ", - "directory or use --force to ignore this error and potentially ", - "overwrite its contents.", - ), - ); - assert!(!output.status.success()); - - // now use `--force` - let status = util::deno_cmd() - .current_dir(t.path()) - .env("NO_COLOR", "1") - .arg("vendor") - .arg("mod.ts") - .arg("--force") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); -} - -#[test] -fn standard_test() { - let _server = http_server(); - let t = TempDir::new(); - let vendor_dir = t.path().join("vendor2"); - t.write( - "my_app.ts", - "import {Logger} from 'http://localhost:4545/vendor/query_reexport.ts?testing'; new Logger().log('outputted');", - ); - - let deno = util::deno_cmd() - .current_dir(t.path()) - .arg("vendor") - .arg("my_app.ts") - .arg("--output") - .arg("vendor2") - .env("NO_COLOR", "1") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!( - String::from_utf8_lossy(&output.stderr).trim(), - format!( - concat!( - "Download http://localhost:4545/vendor/query_reexport.ts?testing\n", - "Download http://localhost:4545/vendor/logger.ts?test\n", - "{}", - ), - success_text("2 modules", "vendor2", true), - ) - ); - assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), ""); - assert!(output.status.success()); - - assert!(vendor_dir.exists()); - assert!(!t.path().join("vendor").exists()); - let import_map: serde_json::Value = - serde_json::from_str(&t.read_to_string("vendor2/import_map.json")).unwrap(); - assert_eq!( - import_map, - json!({ - "imports": { - "http://localhost:4545/vendor/query_reexport.ts?testing": "./localhost_4545/vendor/query_reexport.ts", - "http://localhost:4545/": "./localhost_4545/", - }, - "scopes": { - "./localhost_4545/": { - "./localhost_4545/vendor/logger.ts?test": "./localhost_4545/vendor/logger.ts" - } - } - }), - ); - - // try running the output with `--no-remote` - let deno = util::deno_cmd() - .current_dir(t.path()) - .env("NO_COLOR", "1") - .arg("run") - .arg("--no-remote") - .arg("--check") - .arg("--quiet") - .arg("--import-map") - .arg("vendor2/import_map.json") - .arg("my_app.ts") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!(String::from_utf8_lossy(&output.stderr).trim(), ""); - assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "outputted"); - assert!(output.status.success()); -} - -#[test] -fn import_map_output_dir() { - let _server = http_server(); - let t = TempDir::new(); - t.write("mod.ts", ""); - t.create_dir_all("vendor"); - t.write( - "vendor/import_map.json", - // will be ignored - "{ \"imports\": { \"https://localhost:4545/\": \"./localhost/\" }}", - ); - t.write( - "deno.json", - "{ \"import_map\": \"./vendor/import_map.json\" }", - ); - t.write( - "my_app.ts", - "import {Logger} from 'http://localhost:4545/vendor/logger.ts'; new Logger().log('outputted');", - ); - - let deno = util::deno_cmd() - .current_dir(t.path()) - .env("NO_COLOR", "1") - .arg("vendor") - .arg("--force") - .arg("--import-map") - .arg("vendor/import_map.json") - .arg("my_app.ts") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!( - String::from_utf8_lossy(&output.stderr).trim(), - format!( - concat!( - "Ignoring import map. Specifying an import map file ({}) in the deno ", - "vendor output directory is not supported. If you wish to use an ", - "import map while vendoring, please specify one located outside this ", - "directory.\n", - "Download http://localhost:4545/vendor/logger.ts\n", - "{}", - ), - PathBuf::from("vendor").join("import_map.json").display(), - success_text_updated_deno_json("1 module", "vendor/"), - ) - ); - assert!(output.status.success()); -} - -#[test] -fn remote_module_test() { - let _server = http_server(); - let t = TempDir::new(); - let vendor_dir = t.path().join("vendor"); - - let deno = util::deno_cmd() - .current_dir(t.path()) - .env("NO_COLOR", "1") - .arg("vendor") - .arg("http://localhost:4545/vendor/query_reexport.ts") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!( - String::from_utf8_lossy(&output.stderr).trim(), - format!( - concat!( - "Download http://localhost:4545/vendor/query_reexport.ts\n", - "Download http://localhost:4545/vendor/logger.ts?test\n", - "{}", - ), - success_text("2 modules", "vendor/", true), - ) - ); - assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), ""); - assert!(output.status.success()); - assert!(vendor_dir.exists()); - assert!(vendor_dir - .join("localhost_4545/vendor/query_reexport.ts") - .exists()); - assert!(vendor_dir.join("localhost_4545/vendor/logger.ts").exists()); - let import_map: serde_json::Value = - serde_json::from_str(&t.read_to_string("vendor/import_map.json")).unwrap(); - assert_eq!( - import_map, - json!({ - "imports": { - "http://localhost:4545/": "./localhost_4545/", - }, - "scopes": { - "./localhost_4545/": { - "./localhost_4545/vendor/logger.ts?test": "./localhost_4545/vendor/logger.ts", - } - } - }), - ); -} - -#[test] -fn existing_import_map_no_remote() { - let _server = http_server(); - let t = TempDir::new(); - t.write( - "mod.ts", - "import {Logger} from 'http://localhost:4545/vendor/logger.ts';", - ); - let import_map_filename = "imports2.json"; - let import_map_text = - r#"{ "imports": { "http://localhost:4545/vendor/": "./logger/" } }"#; - t.write(import_map_filename, import_map_text); - t.create_dir_all("logger"); - t.write("logger/logger.ts", "export class Logger {}"); - - let deno = util::deno_cmd() - .current_dir(t.path()) - .env("NO_COLOR", "1") - .arg("vendor") - .arg("mod.ts") - .arg("--import-map") - .arg(import_map_filename) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!( - String::from_utf8_lossy(&output.stderr).trim(), - success_text("0 modules", "vendor/", false) - ); - assert!(output.status.success()); - // it should not have found any remote dependencies because - // the provided import map mapped it to a local directory - assert_eq!(t.read_to_string(import_map_filename), import_map_text); -} - -#[test] -fn existing_import_map_mixed_with_remote() { - let _server = http_server(); - let deno_dir = new_deno_dir(); - let t = TempDir::new(); - t.write( - "mod.ts", - "import {Logger} from 'http://localhost:4545/vendor/logger.ts';", - ); - - let status = util::deno_cmd_with_deno_dir(&deno_dir) - .current_dir(t.path()) - .arg("vendor") - .arg("mod.ts") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - - assert_eq!( - t.read_to_string("vendor/import_map.json"), - r#"{ - "imports": { - "http://localhost:4545/": "./localhost_4545/" - } -} -"#, - ); - - // make the import map specific to support vendoring mod.ts in the next step - t.write( - "vendor/import_map.json", - r#"{ - "imports": { - "http://localhost:4545/vendor/logger.ts": "./localhost_4545/vendor/logger.ts" - } -} -"#, - ); - - t.write( - "mod.ts", - concat!( - "import {Logger} from 'http://localhost:4545/vendor/logger.ts';\n", - "import {Logger as OtherLogger} from 'http://localhost:4545/vendor/mod.ts';\n", - ), - ); - - // now vendor with the existing import map in a separate vendor directory - let deno = util::deno_cmd_with_deno_dir(&deno_dir) - .env("NO_COLOR", "1") - .current_dir(t.path()) - .arg("vendor") - .arg("mod.ts") - .arg("--import-map") - .arg("vendor/import_map.json") - .arg("--output") - .arg("vendor2") - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!( - String::from_utf8_lossy(&output.stderr).trim(), - format!( - concat!("Download http://localhost:4545/vendor/mod.ts\n", "{}",), - success_text("1 module", "vendor2", true), - ) - ); - assert!(output.status.success()); - - // tricky scenario here where the output directory now contains a mapping - // back to the previous vendor location - assert_eq!( - t.read_to_string("vendor2/import_map.json"), - r#"{ - "imports": { - "http://localhost:4545/vendor/logger.ts": "../vendor/localhost_4545/vendor/logger.ts", - "http://localhost:4545/": "./localhost_4545/" - }, - "scopes": { - "./localhost_4545/": { - "./localhost_4545/vendor/logger.ts": "../vendor/localhost_4545/vendor/logger.ts" - } - } -} -"#, - ); - - // ensure it runs - let status = util::deno_cmd() - .current_dir(t.path()) - .arg("run") - .arg("--check") - .arg("--no-remote") - .arg("--import-map") - .arg("vendor2/import_map.json") - .arg("mod.ts") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); -} - -#[test] -fn dynamic_import() { - let _server = http_server(); - let t = TempDir::new(); - t.write( - "mod.ts", - "import {Logger} from 'http://localhost:4545/vendor/dynamic.ts'; new Logger().log('outputted');", - ); - - let status = util::deno_cmd() - .current_dir(t.path()) - .arg("vendor") - .arg("mod.ts") - .spawn() - .unwrap() - .wait() - .unwrap(); - assert!(status.success()); - let import_map: serde_json::Value = - serde_json::from_str(&t.read_to_string("vendor/import_map.json")).unwrap(); - assert_eq!( - import_map, - json!({ - "imports": { - "http://localhost:4545/": "./localhost_4545/", - } - }), - ); - - // try running the output with `--no-remote` - let deno = util::deno_cmd() - .current_dir(t.path()) - .env("NO_COLOR", "1") - .arg("run") - .arg("--allow-read=.") - .arg("--no-remote") - .arg("--check") - .arg("--quiet") - .arg("--import-map") - .arg("vendor/import_map.json") - .arg("mod.ts") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!(String::from_utf8_lossy(&output.stderr).trim(), ""); - assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "outputted"); - assert!(output.status.success()); -} - -#[test] -fn dynamic_non_analyzable_import() { - let _server = http_server(); - let t = TempDir::new(); - t.write( - "mod.ts", - "import {Logger} from 'http://localhost:4545/vendor/dynamic_non_analyzable.ts'; new Logger().log('outputted');", - ); - - let deno = util::deno_cmd() - .current_dir(t.path()) - .env("NO_COLOR", "1") - .arg("vendor") - .arg("--reload") - .arg("mod.ts") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - // todo(https://github.com/denoland/deno_graph/issues/138): it should warn about - // how it couldn't analyze the dynamic import - assert_eq!( - String::from_utf8_lossy(&output.stderr).trim(), - format!( - "Download http://localhost:4545/vendor/dynamic_non_analyzable.ts\n{}", - success_text("1 module", "vendor/", true), - ) - ); - assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), ""); - assert!(output.status.success()); -} - -#[test] -fn update_existing_config_test() { - let _server = http_server(); - let t = TempDir::new(); - t.write( - "my_app.ts", - "import {Logger} from 'http://localhost:4545/vendor/logger.ts'; new Logger().log('outputted');", - ); - t.write("deno.json", "{\n}"); - - let deno = util::deno_cmd() - .current_dir(t.path()) - .arg("vendor") - .arg("my_app.ts") - .arg("--output") - .arg("vendor2") - .env("NO_COLOR", "1") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!( - String::from_utf8_lossy(&output.stderr).trim(), - format!( - "Download http://localhost:4545/vendor/logger.ts\n{}", - success_text_updated_deno_json("1 module", "vendor2",) - ) - ); - assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), ""); - assert!(output.status.success()); - - // try running the output with `--no-remote` and not specifying a `--vendor` - let deno = util::deno_cmd() - .current_dir(t.path()) - .env("NO_COLOR", "1") - .arg("run") - .arg("--no-remote") - .arg("--check") - .arg("--quiet") - .arg("my_app.ts") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let output = deno.wait_with_output().unwrap(); - assert_eq!(String::from_utf8_lossy(&output.stderr).trim(), ""); - assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "outputted"); - assert!(output.status.success()); -} - -fn success_text(module_count: &str, dir: &str, has_import_map: bool) -> String { - let mut text = format!("Vendored {} into {} directory.", module_count, dir); - if has_import_map { - let f = format!( - concat!( - "\n\nTo use vendored modules, specify the `--import-map {}import_map.json` flag when ", - r#"invoking Deno subcommands or add an `"importMap": ""` "#, - "entry to a deno.json file.", - ), - if dir != "vendor/" { - format!("{}{}", dir.trim_end_matches('/'), if cfg!(windows) { '\\' } else {'/'}) - } else { - dir.to_string() - } - ); - write!(text, "{}", f).unwrap(); - } - text -} - -fn success_text_updated_deno_json(module_count: &str, dir: &str) -> String { - format!( - concat!( - "Vendored {} into {} directory.\n\n", - "Updated your local Deno configuration file with a reference to the ", - "new vendored import map at {}import_map.json. Invoking Deno subcommands will ", - "now automatically resolve using the vendored modules. You may override ", - "this by providing the `--import-map ` flag or by ", - "manually editing your Deno configuration file.", - ), - module_count, - dir, - if dir != "vendor/" { - format!( - "{}{}", - dir.trim_end_matches('/'), - if cfg!(windows) { '\\' } else { '/' } - ) - } else { - dir.to_string() - } - ) -} diff --git a/cli/tests/integration/watcher_tests.rs b/cli/tests/integration/watcher_tests.rs deleted file mode 100644 index cd3dc40cfc..0000000000 --- a/cli/tests/integration/watcher_tests.rs +++ /dev/null @@ -1,1234 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use flaky_test::flaky_test; -use std::fs::write; -use std::io::BufRead; -use test_util as util; -use test_util::assert_contains; -use test_util::TempDir; - -const CLEAR_SCREEN: &str = r#"[2J"#; - -// Helper function to skip watcher output that contains "Restarting" -// phrase. -fn skip_restarting_line( - stderr_lines: &mut impl Iterator, -) -> String { - loop { - let msg = stderr_lines.next().unwrap(); - if !msg.contains("Restarting") { - return msg; - } - } -} - -fn read_all_lints(stderr_lines: &mut impl Iterator) -> String { - let mut str = String::new(); - for t in stderr_lines { - let t = util::strip_ansi_codes(&t); - if t.starts_with("Watcher File change detected") { - continue; - } - if t.starts_with("Watcher") { - break; - } - if t.starts_with('(') { - str.push_str(&t); - str.push('\n'); - } - } - str -} - -fn wait_for( - condition: impl Fn(&str) -> bool, - lines: &mut impl Iterator, -) { - loop { - let msg = lines.next().unwrap(); - if condition(&msg) { - break; - } - } -} - -fn wait_contains(s: &str, lines: &mut impl Iterator) { - wait_for(|msg| msg.contains(s), lines) -} - -fn read_line(s: &str, lines: &mut impl Iterator) -> String { - lines.find(|m| m.contains(s)).unwrap() -} - -fn check_alive_then_kill(mut child: std::process::Child) { - assert!(child.try_wait().unwrap().is_none()); - child.kill().unwrap(); -} - -fn child_lines( - child: &mut std::process::Child, -) -> (impl Iterator, impl Iterator) { - let stdout_lines = std::io::BufReader::new(child.stdout.take().unwrap()) - .lines() - .map(|r| { - let line = r.unwrap(); - eprintln!("STDOUT: {}", line); - line - }); - let stderr_lines = std::io::BufReader::new(child.stderr.take().unwrap()) - .lines() - .map(|r| { - let line = r.unwrap(); - eprintln!("STERR: {}", line); - line - }); - (stdout_lines, stderr_lines) -} - -#[test] -fn lint_watch_test() { - let t = TempDir::new(); - let badly_linted_original = - util::testdata_path().join("lint/watch/badly_linted.js"); - let badly_linted_output = - util::testdata_path().join("lint/watch/badly_linted.js.out"); - let badly_linted_fixed1 = - util::testdata_path().join("lint/watch/badly_linted_fixed1.js"); - let badly_linted_fixed1_output = - util::testdata_path().join("lint/watch/badly_linted_fixed1.js.out"); - let badly_linted_fixed2 = - util::testdata_path().join("lint/watch/badly_linted_fixed2.js"); - let badly_linted_fixed2_output = - util::testdata_path().join("lint/watch/badly_linted_fixed2.js.out"); - let badly_linted = t.path().join("badly_linted.js"); - - std::fs::copy(&badly_linted_original, &badly_linted).unwrap(); - - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("lint") - .arg(&badly_linted) - .arg("--watch") - .arg("--unstable") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); - let next_line = stderr_lines.next().unwrap(); - assert_contains!(&next_line, "Lint started"); - let mut output = read_all_lints(&mut stderr_lines); - let expected = std::fs::read_to_string(badly_linted_output).unwrap(); - assert_eq!(output, expected); - - // Change content of the file again to be badly-linted1 - std::fs::copy(&badly_linted_fixed1, &badly_linted).unwrap(); - std::thread::sleep(std::time::Duration::from_secs(1)); - - output = read_all_lints(&mut stderr_lines); - let expected = std::fs::read_to_string(badly_linted_fixed1_output).unwrap(); - assert_eq!(output, expected); - - // Change content of the file again to be badly-linted1 - std::fs::copy(&badly_linted_fixed2, &badly_linted).unwrap(); - - output = read_all_lints(&mut stderr_lines); - let expected = std::fs::read_to_string(badly_linted_fixed2_output).unwrap(); - assert_eq!(output, expected); - - // the watcher process is still alive - assert!(child.try_wait().unwrap().is_none()); - - child.kill().unwrap(); - drop(t); -} - -#[test] -fn lint_watch_without_args_test() { - let t = TempDir::new(); - let badly_linted_original = - util::testdata_path().join("lint/watch/badly_linted.js"); - let badly_linted_output = - util::testdata_path().join("lint/watch/badly_linted.js.out"); - let badly_linted_fixed1 = - util::testdata_path().join("lint/watch/badly_linted_fixed1.js"); - let badly_linted_fixed1_output = - util::testdata_path().join("lint/watch/badly_linted_fixed1.js.out"); - let badly_linted_fixed2 = - util::testdata_path().join("lint/watch/badly_linted_fixed2.js"); - let badly_linted_fixed2_output = - util::testdata_path().join("lint/watch/badly_linted_fixed2.js.out"); - let badly_linted = t.path().join("badly_linted.js"); - - std::fs::copy(&badly_linted_original, &badly_linted).unwrap(); - - let mut child = util::deno_cmd() - .current_dir(t.path()) - .arg("lint") - .arg("--watch") - .arg("--unstable") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); - - let next_line = stderr_lines.next().unwrap(); - assert_contains!(&next_line, "Lint started"); - let mut output = read_all_lints(&mut stderr_lines); - let expected = std::fs::read_to_string(badly_linted_output).unwrap(); - assert_eq!(output, expected); - - // Change content of the file again to be badly-linted1 - std::fs::copy(&badly_linted_fixed1, &badly_linted).unwrap(); - - output = read_all_lints(&mut stderr_lines); - let expected = std::fs::read_to_string(badly_linted_fixed1_output).unwrap(); - assert_eq!(output, expected); - - // Change content of the file again to be badly-linted1 - std::fs::copy(&badly_linted_fixed2, &badly_linted).unwrap(); - std::thread::sleep(std::time::Duration::from_secs(1)); - - output = read_all_lints(&mut stderr_lines); - let expected = std::fs::read_to_string(badly_linted_fixed2_output).unwrap(); - assert_eq!(output, expected); - - // the watcher process is still alive - assert!(child.try_wait().unwrap().is_none()); - - child.kill().unwrap(); - drop(t); -} - -#[test] -fn lint_all_files_on_each_change_test() { - let t = TempDir::new(); - let badly_linted_fixed0 = - util::testdata_path().join("lint/watch/badly_linted.js"); - let badly_linted_fixed1 = - util::testdata_path().join("lint/watch/badly_linted_fixed1.js"); - let badly_linted_fixed2 = - util::testdata_path().join("lint/watch/badly_linted_fixed2.js"); - - let badly_linted_1 = t.path().join("badly_linted_1.js"); - let badly_linted_2 = t.path().join("badly_linted_2.js"); - std::fs::copy(&badly_linted_fixed0, &badly_linted_1).unwrap(); - std::fs::copy(&badly_linted_fixed1, &badly_linted_2).unwrap(); - - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("lint") - .arg(t.path()) - .arg("--watch") - .arg("--unstable") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); - - assert_contains!(read_line("Checked", &mut stderr_lines), "Checked 2 files"); - - std::fs::copy(&badly_linted_fixed2, &badly_linted_2).unwrap(); - - assert_contains!(read_line("Checked", &mut stderr_lines), "Checked 2 files"); - - assert!(child.try_wait().unwrap().is_none()); - - child.kill().unwrap(); - drop(t); -} - -#[test] -fn fmt_watch_test() { - let fmt_testdata_path = util::testdata_path().join("fmt"); - let t = TempDir::new(); - let fixed = fmt_testdata_path.join("badly_formatted_fixed.js"); - let badly_formatted_original = fmt_testdata_path.join("badly_formatted.mjs"); - let badly_formatted = t.path().join("badly_formatted.js"); - std::fs::copy(&badly_formatted_original, &badly_formatted).unwrap(); - - let mut child = util::deno_cmd() - .current_dir(&fmt_testdata_path) - .arg("fmt") - .arg(&badly_formatted) - .arg("--watch") - .arg("--unstable") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); - - let next_line = stderr_lines.next().unwrap(); - assert_contains!(&next_line, "Fmt started"); - assert_contains!( - skip_restarting_line(&mut stderr_lines), - "badly_formatted.js" - ); - assert_contains!(read_line("Checked", &mut stderr_lines), "Checked 1 file"); - - let expected = std::fs::read_to_string(fixed.clone()).unwrap(); - let actual = std::fs::read_to_string(badly_formatted.clone()).unwrap(); - assert_eq!(actual, expected); - - // Change content of the file again to be badly formatted - std::fs::copy(&badly_formatted_original, &badly_formatted).unwrap(); - - assert_contains!( - skip_restarting_line(&mut stderr_lines), - "badly_formatted.js" - ); - assert_contains!(read_line("Checked", &mut stderr_lines), "Checked 1 file"); - - // Check if file has been automatically formatted by watcher - let expected = std::fs::read_to_string(fixed).unwrap(); - let actual = std::fs::read_to_string(badly_formatted).unwrap(); - assert_eq!(actual, expected); - check_alive_then_kill(child); -} - -#[test] -fn fmt_watch_without_args_test() { - let fmt_testdata_path = util::testdata_path().join("fmt"); - let t = TempDir::new(); - let fixed = fmt_testdata_path.join("badly_formatted_fixed.js"); - let badly_formatted_original = fmt_testdata_path.join("badly_formatted.mjs"); - let badly_formatted = t.path().join("badly_formatted.js"); - std::fs::copy(&badly_formatted_original, &badly_formatted).unwrap(); - - let mut child = util::deno_cmd() - .current_dir(t.path()) - .arg("fmt") - .arg("--watch") - .arg("--unstable") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); - - let next_line = stderr_lines.next().unwrap(); - assert_contains!(&next_line, "Fmt started"); - assert_contains!( - skip_restarting_line(&mut stderr_lines), - "badly_formatted.js" - ); - assert_contains!(read_line("Checked", &mut stderr_lines), "Checked 1 file"); - - let expected = std::fs::read_to_string(fixed.clone()).unwrap(); - let actual = std::fs::read_to_string(badly_formatted.clone()).unwrap(); - assert_eq!(actual, expected); - - // Change content of the file again to be badly formatted - std::fs::copy(&badly_formatted_original, &badly_formatted).unwrap(); - assert_contains!( - skip_restarting_line(&mut stderr_lines), - "badly_formatted.js" - ); - assert_contains!(read_line("Checked", &mut stderr_lines), "Checked 1 file"); - - // Check if file has been automatically formatted by watcher - let expected = std::fs::read_to_string(fixed).unwrap(); - let actual = std::fs::read_to_string(badly_formatted).unwrap(); - assert_eq!(actual, expected); - check_alive_then_kill(child); -} - -#[test] -fn fmt_check_all_files_on_each_change_test() { - let t = TempDir::new(); - let fmt_testdata_path = util::testdata_path().join("fmt"); - let badly_formatted_original = fmt_testdata_path.join("badly_formatted.mjs"); - let badly_formatted_1 = t.path().join("badly_formatted_1.js"); - let badly_formatted_2 = t.path().join("badly_formatted_2.js"); - std::fs::copy(&badly_formatted_original, &badly_formatted_1).unwrap(); - std::fs::copy(&badly_formatted_original, &badly_formatted_2).unwrap(); - - let mut child = util::deno_cmd() - .current_dir(&fmt_testdata_path) - .arg("fmt") - .arg(t.path()) - .arg("--watch") - .arg("--check") - .arg("--unstable") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); - - assert_contains!( - read_line("error", &mut stderr_lines), - "Found 2 not formatted files in 2 files" - ); - - // Change content of the file again to be badly formatted - std::fs::copy(&badly_formatted_original, &badly_formatted_1).unwrap(); - - assert_contains!( - read_line("error", &mut stderr_lines), - "Found 2 not formatted files in 2 files" - ); - - check_alive_then_kill(child); -} - -#[test] -fn bundle_js_watch() { - use std::path::PathBuf; - // Test strategy extends this of test bundle_js by adding watcher - let t = TempDir::new(); - let file_to_watch = t.path().join("file_to_watch.ts"); - write(&file_to_watch, "console.log('Hello world');").unwrap(); - assert!(file_to_watch.is_file()); - let t = TempDir::new(); - let bundle = t.path().join("mod6.bundle.js"); - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg(&file_to_watch) - .arg(&bundle) - .arg("--watch") - .arg("--unstable") - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - - let (_stdout_lines, mut stderr_lines) = child_lines(&mut deno); - - assert_contains!(stderr_lines.next().unwrap(), "Check"); - let next_line = stderr_lines.next().unwrap(); - assert_contains!(&next_line, "Bundle started"); - assert_contains!(stderr_lines.next().unwrap(), "file_to_watch.ts"); - assert_contains!(stderr_lines.next().unwrap(), "mod6.bundle.js"); - let file = PathBuf::from(&bundle); - assert!(file.is_file()); - wait_contains("Bundle finished", &mut stderr_lines); - - write(&file_to_watch, "console.log('Hello world2');").unwrap(); - - assert_contains!(stderr_lines.next().unwrap(), "Check"); - let next_line = stderr_lines.next().unwrap(); - assert_contains!(&next_line, CLEAR_SCREEN); - assert_contains!(&next_line, "File change detected!"); - assert_contains!(stderr_lines.next().unwrap(), "file_to_watch.ts"); - assert_contains!(stderr_lines.next().unwrap(), "mod6.bundle.js"); - let file = PathBuf::from(&bundle); - assert!(file.is_file()); - wait_contains("Bundle finished", &mut stderr_lines); - - // Confirm that the watcher keeps on working even if the file is updated and has invalid syntax - write(&file_to_watch, "syntax error ^^").unwrap(); - - assert_contains!(stderr_lines.next().unwrap(), "File change detected!"); - assert_contains!(stderr_lines.next().unwrap(), "error: "); - wait_contains("Bundle failed", &mut stderr_lines); - check_alive_then_kill(deno); -} - -/// Confirm that the watcher continues to work even if module resolution fails at the *first* attempt -#[test] -fn bundle_watch_not_exit() { - let t = TempDir::new(); - let file_to_watch = t.path().join("file_to_watch.ts"); - write(&file_to_watch, "syntax error ^^").unwrap(); - let target_file = t.path().join("target.js"); - - let mut deno = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("bundle") - .arg(&file_to_watch) - .arg(&target_file) - .arg("--watch") - .arg("--unstable") - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (_stdout_lines, mut stderr_lines) = child_lines(&mut deno); - - let next_line = stderr_lines.next().unwrap(); - assert_contains!(&next_line, "Bundle started"); - assert_contains!(stderr_lines.next().unwrap(), "error:"); - assert_contains!(stderr_lines.next().unwrap(), "Bundle failed"); - // the target file hasn't been created yet - assert!(!target_file.is_file()); - - // Make sure the watcher actually restarts and works fine with the proper syntax - write(&file_to_watch, "console.log(42);").unwrap(); - - assert_contains!(stderr_lines.next().unwrap(), "Check"); - let next_line = stderr_lines.next().unwrap(); - assert_contains!(&next_line, CLEAR_SCREEN); - assert_contains!(&next_line, "File change detected!"); - assert_contains!(stderr_lines.next().unwrap(), "file_to_watch.ts"); - assert_contains!(stderr_lines.next().unwrap(), "target.js"); - - wait_contains("Bundle finished", &mut stderr_lines); - - // bundled file is created - assert!(target_file.is_file()); - check_alive_then_kill(deno); -} - -#[test] -fn run_watch_no_dynamic() { - let t = TempDir::new(); - let file_to_watch = t.path().join("file_to_watch.js"); - write(&file_to_watch, "console.log('Hello world');").unwrap(); - - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--watch") - .arg("--unstable") - .arg("-L") - .arg("debug") - .arg(&file_to_watch) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); - - wait_contains("Hello world", &mut stdout_lines); - wait_for( - |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), - &mut stderr_lines, - ); - - // Change content of the file - write(&file_to_watch, "console.log('Hello world2');").unwrap(); - - wait_contains("Restarting", &mut stderr_lines); - wait_contains("Hello world2", &mut stdout_lines); - wait_for( - |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), - &mut stderr_lines, - ); - - // Add dependency - let another_file = t.path().join("another_file.js"); - write(&another_file, "export const foo = 0;").unwrap(); - write( - &file_to_watch, - "import { foo } from './another_file.js'; console.log(foo);", - ) - .unwrap(); - - wait_contains("Restarting", &mut stderr_lines); - wait_contains("0", &mut stdout_lines); - wait_for( - |m| m.contains("Watching paths") && m.contains("another_file.js"), - &mut stderr_lines, - ); - - // Confirm that restarting occurs when a new file is updated - write(&another_file, "export const foo = 42;").unwrap(); - - wait_contains("Restarting", &mut stderr_lines); - wait_contains("42", &mut stdout_lines); - wait_for( - |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), - &mut stderr_lines, - ); - - // Confirm that the watcher keeps on working even if the file is updated and has invalid syntax - write(&file_to_watch, "syntax error ^^").unwrap(); - - wait_contains("Restarting", &mut stderr_lines); - wait_contains("error:", &mut stderr_lines); - wait_for( - |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), - &mut stderr_lines, - ); - - // Then restore the file - write( - &file_to_watch, - "import { foo } from './another_file.js'; console.log(foo);", - ) - .unwrap(); - - wait_contains("Restarting", &mut stderr_lines); - wait_contains("42", &mut stdout_lines); - wait_for( - |m| m.contains("Watching paths") && m.contains("another_file.js"), - &mut stderr_lines, - ); - - // Update the content of the imported file with invalid syntax - write(&another_file, "syntax error ^^").unwrap(); - - wait_contains("Restarting", &mut stderr_lines); - wait_contains("error:", &mut stderr_lines); - wait_for( - |m| m.contains("Watching paths") && m.contains("another_file.js"), - &mut stderr_lines, - ); - - // Modify the imported file and make sure that restarting occurs - write(&another_file, "export const foo = 'modified!';").unwrap(); - - wait_contains("Restarting", &mut stderr_lines); - wait_contains("modified!", &mut stdout_lines); - wait_contains("Watching paths", &mut stderr_lines); - check_alive_then_kill(child); -} - -// TODO(bartlomieju): this test became flaky on macOS runner; it is unclear -// if that's because of a bug in code or the runner itself. We should reenable -// it once we upgrade to XL runners for macOS. -#[cfg(not(target_os = "macos"))] -#[test] -fn run_watch_external_watch_files() { - let t = TempDir::new(); - let file_to_watch = t.path().join("file_to_watch.js"); - write(&file_to_watch, "console.log('Hello world');").unwrap(); - - let external_file_to_watch = t.path().join("external_file_to_watch.txt"); - write(&external_file_to_watch, "Hello world").unwrap(); - - let mut watch_arg = "--watch=".to_owned(); - let external_file_to_watch_str = external_file_to_watch - .clone() - .into_os_string() - .into_string() - .unwrap(); - watch_arg.push_str(&external_file_to_watch_str); - - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg(watch_arg) - .arg("-L") - .arg("debug") - .arg("--unstable") - .arg(&file_to_watch) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); - wait_contains("Process started", &mut stderr_lines); - wait_contains("Hello world", &mut stdout_lines); - wait_for( - |m| { - m.contains("Watching paths") && m.contains("external_file_to_watch.txt") - }, - &mut stderr_lines, - ); - - // Change content of the external file - write(&external_file_to_watch, "Hello world2").unwrap(); - - wait_contains("Restarting", &mut stderr_lines); - wait_contains("Process finished", &mut stderr_lines); - check_alive_then_kill(child); -} - -#[test] -fn run_watch_load_unload_events() { - let t = TempDir::new(); - let file_to_watch = t.path().join("file_to_watch.js"); - write( - &file_to_watch, - r#" - setInterval(() => {}, 0); - window.addEventListener("load", () => { - console.log("load"); - }); - - window.addEventListener("unload", () => { - console.log("unload"); - }); - "#, - ) - .unwrap(); - - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--watch") - .arg("--unstable") - .arg("-L") - .arg("debug") - .arg(&file_to_watch) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); - - // Wait for the first load event to fire - wait_contains("load", &mut stdout_lines); - wait_for( - |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), - &mut stderr_lines, - ); - - // Change content of the file, this time without an interval to keep it alive. - write( - &file_to_watch, - r#" - window.addEventListener("load", () => { - console.log("load"); - }); - - window.addEventListener("unload", () => { - console.log("unload"); - }); - "#, - ) - .unwrap(); - - // Wait for the restart - wait_contains("Restarting", &mut stderr_lines); - - // Confirm that the unload event was dispatched from the first run - wait_contains("unload", &mut stdout_lines); - - // Followed by the load event of the second run - wait_contains("load", &mut stdout_lines); - - // Which is then unloaded as there is nothing keeping it alive. - wait_contains("unload", &mut stdout_lines); - check_alive_then_kill(child); -} - -/// Confirm that the watcher continues to work even if module resolution fails at the *first* attempt -#[test] -fn run_watch_not_exit() { - let t = TempDir::new(); - let file_to_watch = t.path().join("file_to_watch.js"); - write(&file_to_watch, "syntax error ^^").unwrap(); - - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--watch") - .arg("--unstable") - .arg("-L") - .arg("debug") - .arg(&file_to_watch) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); - - wait_contains("Process started", &mut stderr_lines); - wait_contains("error:", &mut stderr_lines); - wait_for( - |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), - &mut stderr_lines, - ); - - // Make sure the watcher actually restarts and works fine with the proper syntax - write(&file_to_watch, "console.log(42);").unwrap(); - - wait_contains("Restarting", &mut stderr_lines); - wait_contains("42", &mut stdout_lines); - wait_contains("Process finished", &mut stderr_lines); - check_alive_then_kill(child); -} - -#[test] -fn run_watch_with_import_map_and_relative_paths() { - fn create_relative_tmp_file( - directory: &TempDir, - filename: &'static str, - filecontent: &'static str, - ) -> std::path::PathBuf { - let absolute_path = directory.path().join(filename); - write(&absolute_path, filecontent).unwrap(); - let relative_path = absolute_path - .strip_prefix(util::testdata_path()) - .unwrap() - .to_owned(); - assert!(relative_path.is_relative()); - relative_path - } - let temp_directory = TempDir::new_in(&util::testdata_path()); - let file_to_watch = create_relative_tmp_file( - &temp_directory, - "file_to_watch.js", - "console.log('Hello world');", - ); - let import_map_path = create_relative_tmp_file( - &temp_directory, - "import_map.json", - "{\"imports\": {}}", - ); - - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--unstable") - .arg("--watch") - .arg("--import-map") - .arg(&import_map_path) - .arg(&file_to_watch) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); - let next_line = stderr_lines.next().unwrap(); - assert_contains!(&next_line, "Process started"); - assert_contains!(stderr_lines.next().unwrap(), "Process finished"); - assert_contains!(stdout_lines.next().unwrap(), "Hello world"); - - check_alive_then_kill(child); -} - -#[test] -fn run_watch_error_messages() { - let t = TempDir::new(); - let file_to_watch = t.path().join("file_to_watch.js"); - write( - &file_to_watch, - "throw SyntaxError(`outer`, {cause: TypeError(`inner`)})", - ) - .unwrap(); - - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--watch") - .arg(&file_to_watch) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (_, mut stderr_lines) = child_lines(&mut child); - - wait_contains("Process started", &mut stderr_lines); - wait_contains("error: Uncaught SyntaxError: outer", &mut stderr_lines); - wait_contains("Caused by: TypeError: inner", &mut stderr_lines); - wait_contains("Process finished", &mut stderr_lines); - - check_alive_then_kill(child); -} - -#[test] -fn test_watch() { - let t = TempDir::new(); - - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("test") - .arg("--watch") - .arg("--unstable") - .arg("--no-check") - .arg(t.path()) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); - - assert_eq!(stdout_lines.next().unwrap(), ""); - assert_contains!(stdout_lines.next().unwrap(), "0 passed | 0 failed"); - wait_contains("Test finished", &mut stderr_lines); - - let foo_file = t.path().join("foo.js"); - let bar_file = t.path().join("bar.js"); - let foo_test = t.path().join("foo_test.js"); - let bar_test = t.path().join("bar_test.js"); - write(&foo_file, "export default function foo() { 1 + 1 }").unwrap(); - write(&bar_file, "export default function bar() { 2 + 2 }").unwrap(); - write( - &foo_test, - "import foo from './foo.js'; Deno.test('foo', foo);", - ) - .unwrap(); - write( - &bar_test, - "import bar from './bar.js'; Deno.test('bar', bar);", - ) - .unwrap(); - - assert_eq!(stdout_lines.next().unwrap(), ""); - assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); - assert_contains!(stdout_lines.next().unwrap(), "foo", "bar"); - assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); - assert_contains!(stdout_lines.next().unwrap(), "foo", "bar"); - stdout_lines.next(); - stdout_lines.next(); - stdout_lines.next(); - wait_contains("Test finished", &mut stderr_lines); - - // Change content of the file - write( - &foo_test, - "import foo from './foo.js'; Deno.test('foobar', foo);", - ) - .unwrap(); - - assert_contains!(stderr_lines.next().unwrap(), "Restarting"); - assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); - assert_contains!(stdout_lines.next().unwrap(), "foobar"); - stdout_lines.next(); - stdout_lines.next(); - stdout_lines.next(); - wait_contains("Test finished", &mut stderr_lines); - - // Add test - let another_test = t.path().join("new_test.js"); - write(&another_test, "Deno.test('another one', () => 3 + 3)").unwrap(); - assert_contains!(stderr_lines.next().unwrap(), "Restarting"); - assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); - assert_contains!(stdout_lines.next().unwrap(), "another one"); - stdout_lines.next(); - stdout_lines.next(); - stdout_lines.next(); - wait_contains("Test finished", &mut stderr_lines); - - // Confirm that restarting occurs when a new file is updated - write(&another_test, "Deno.test('another one', () => 3 + 3); Deno.test('another another one', () => 4 + 4)") - .unwrap(); - assert_contains!(stderr_lines.next().unwrap(), "Restarting"); - assert_contains!(stdout_lines.next().unwrap(), "running 2 tests"); - assert_contains!(stdout_lines.next().unwrap(), "another one"); - assert_contains!(stdout_lines.next().unwrap(), "another another one"); - stdout_lines.next(); - stdout_lines.next(); - stdout_lines.next(); - wait_contains("Test finished", &mut stderr_lines); - - // Confirm that the watcher keeps on working even if the file is updated and has invalid syntax - write(&another_test, "syntax error ^^").unwrap(); - assert_contains!(stderr_lines.next().unwrap(), "Restarting"); - assert_contains!(stderr_lines.next().unwrap(), "error:"); - assert_contains!(stderr_lines.next().unwrap(), "Test failed"); - - // Then restore the file - write(&another_test, "Deno.test('another one', () => 3 + 3)").unwrap(); - assert_contains!(stderr_lines.next().unwrap(), "Restarting"); - assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); - assert_contains!(stdout_lines.next().unwrap(), "another one"); - stdout_lines.next(); - stdout_lines.next(); - stdout_lines.next(); - wait_contains("Test finished", &mut stderr_lines); - - // Confirm that the watcher keeps on working even if the file is updated and the test fails - // This also confirms that it restarts when dependencies change - write( - &foo_file, - "export default function foo() { throw new Error('Whoops!'); }", - ) - .unwrap(); - assert_contains!(stderr_lines.next().unwrap(), "Restarting"); - assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); - assert_contains!(stdout_lines.next().unwrap(), "FAILED"); - wait_for(|m| m.contains("FAILED"), &mut stdout_lines); - stdout_lines.next(); - wait_contains("Test finished", &mut stderr_lines); - - // Then restore the file - write(&foo_file, "export default function foo() { 1 + 1 }").unwrap(); - assert_contains!(stderr_lines.next().unwrap(), "Restarting"); - assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); - assert_contains!(stdout_lines.next().unwrap(), "foo"); - stdout_lines.next(); - stdout_lines.next(); - stdout_lines.next(); - wait_contains("Test finished", &mut stderr_lines); - - // Test that circular dependencies work fine - write( - &foo_file, - "import './bar.js'; export default function foo() { 1 + 1 }", - ) - .unwrap(); - write( - &bar_file, - "import './foo.js'; export default function bar() { 2 + 2 }", - ) - .unwrap(); - check_alive_then_kill(child); -} - -#[flaky_test] -fn test_watch_doc() { - let t = TempDir::new(); - - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("test") - .arg("--watch") - .arg("--doc") - .arg("--unstable") - .arg(t.path()) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); - - assert_eq!(stdout_lines.next().unwrap(), ""); - assert_contains!(stdout_lines.next().unwrap(), "0 passed | 0 failed"); - wait_contains("Test finished", &mut stderr_lines); - - let foo_file = t.path().join("foo.ts"); - write( - &foo_file, - r#" - export default function foo() {} - "#, - ) - .unwrap(); - - write( - &foo_file, - r#" - /** - * ```ts - * import foo from "./foo.ts"; - * ``` - */ - export default function foo() {} - "#, - ) - .unwrap(); - - // We only need to scan for a Check file://.../foo.ts$3-6 line that - // corresponds to the documentation block being type-checked. - assert_contains!(skip_restarting_line(&mut stderr_lines), "foo.ts$3-6"); - check_alive_then_kill(child); -} - -#[test] -fn test_watch_module_graph_error_referrer() { - let t = TempDir::new(); - let file_to_watch = t.path().join("file_to_watch.js"); - write(&file_to_watch, "import './nonexistent.js';").unwrap(); - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--watch") - .arg("--unstable") - .arg(&file_to_watch) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (_, mut stderr_lines) = child_lines(&mut child); - let line1 = stderr_lines.next().unwrap(); - assert_contains!(&line1, "Process started"); - let line2 = stderr_lines.next().unwrap(); - assert_contains!(&line2, "error: Module not found"); - assert_contains!(&line2, "nonexistent.js"); - let line3 = stderr_lines.next().unwrap(); - assert_contains!(&line3, " at "); - assert_contains!(&line3, "file_to_watch.js"); - wait_contains("Process finished", &mut stderr_lines); - check_alive_then_kill(child); -} - -// Regression test for https://github.com/denoland/deno/issues/15428. -#[test] -fn test_watch_unload_handler_error_on_drop() { - let t = TempDir::new(); - let file_to_watch = t.path().join("file_to_watch.js"); - write( - &file_to_watch, - r#" - addEventListener("unload", () => { - throw new Error("foo"); - }); - setTimeout(() => { - throw new Error("bar"); - }); - "#, - ) - .unwrap(); - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--watch") - .arg(&file_to_watch) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (_, mut stderr_lines) = child_lines(&mut child); - wait_contains("Process started", &mut stderr_lines); - wait_contains("Uncaught Error: bar", &mut stderr_lines); - wait_contains("Process finished", &mut stderr_lines); - check_alive_then_kill(child); -} - -#[test] -fn run_watch_dynamic_imports() { - let t = TempDir::new(); - let file_to_watch = t.path().join("file_to_watch.js"); - write( - &file_to_watch, - r#" - console.log("Hopefully dynamic import will be watched..."); - await import("./imported.js"); - "#, - ) - .unwrap(); - let file_to_watch2 = t.path().join("imported.js"); - write( - &file_to_watch2, - r#" - import "./imported2.js"; - console.log("I'm dynamically imported and I cause restarts!"); - "#, - ) - .unwrap(); - let file_to_watch3 = t.path().join("imported2.js"); - write( - &file_to_watch3, - r#" - console.log("I'm statically imported from the dynamic import"); - "#, - ) - .unwrap(); - - let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) - .arg("run") - .arg("--watch") - .arg("--unstable") - .arg("--allow-read") - .arg("-L") - .arg("debug") - .arg(&file_to_watch) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); - - assert_contains!(stderr_lines.next().unwrap(), "Process started"); - - wait_contains( - "Hopefully dynamic import will be watched...", - &mut stdout_lines, - ); - wait_contains( - "I'm statically imported from the dynamic import", - &mut stdout_lines, - ); - wait_contains( - "I'm dynamically imported and I cause restarts!", - &mut stdout_lines, - ); - - wait_contains("finished", &mut stderr_lines); - wait_for( - |m| m.contains("Watching paths") && m.contains("imported2.js"), - &mut stderr_lines, - ); - - write( - &file_to_watch3, - r#" - console.log("I'm statically imported from the dynamic import and I've changed"); - "#, - ) - .unwrap(); - - wait_contains("Restarting", &mut stderr_lines); - wait_contains( - "Hopefully dynamic import will be watched...", - &mut stdout_lines, - ); - wait_contains( - "I'm statically imported from the dynamic import and I've changed", - &mut stdout_lines, - ); - wait_contains( - "I'm dynamically imported and I cause restarts!", - &mut stdout_lines, - ); - - check_alive_then_kill(child); -} - -// https://github.com/denoland/deno/issues/16267 -#[test] -fn run_watch_flash() { - let filename = "watch_flash.js"; - let t = TempDir::new(); - let file_to_watch = t.path().join(filename); - write( - &file_to_watch, - r#" - console.log("Starting flash server..."); - Deno.serve({ - onListen() { - console.error("First server is listening"); - }, - handler: () => {}, - port: 4601, - }); - "#, - ) - .unwrap(); - - let mut child = util::deno_cmd() - .current_dir(t.path()) - .arg("run") - .arg("--watch") - .arg("--unstable") - .arg("--allow-net") - .arg("-L") - .arg("debug") - .arg(&file_to_watch) - .env("NO_COLOR", "1") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); - - wait_contains("Starting flash server...", &mut stdout_lines); - wait_for( - |m| m.contains("Watching paths") && m.contains(filename), - &mut stderr_lines, - ); - - write( - &file_to_watch, - r#" - console.log("Restarting flash server..."); - Deno.serve({ - onListen() { - console.error("Second server is listening"); - }, - handler: () => {}, - port: 4601, - }); - "#, - ) - .unwrap(); - - wait_contains("File change detected! Restarting!", &mut stderr_lines); - wait_contains("Restarting flash server...", &mut stdout_lines); - wait_contains("Second server is listening", &mut stderr_lines); - - check_alive_then_kill(child); -} diff --git a/cli/tests/integration/worker_tests.rs b/cli/tests/integration/worker_tests.rs deleted file mode 100644 index b864c15da5..0000000000 --- a/cli/tests/integration/worker_tests.rs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -use crate::itest; - -itest!(workers { - args: "test --reload --location http://127.0.0.1:4545/ -A --unstable workers/test.ts", - output: "workers/test.ts.out", - http_server: true, -}); - -itest!(worker_error { - args: "run -A workers/worker_error.ts", - output: "workers/worker_error.ts.out", - exit_code: 1, -}); - -itest!(worker_nested_error { - args: "run -A workers/worker_nested_error.ts", - output: "workers/worker_nested_error.ts.out", - exit_code: 1, -}); - -itest!(worker_async_error { - args: "run -A --quiet --reload workers/worker_async_error.ts", - output: "workers/worker_async_error.ts.out", - http_server: true, - exit_code: 1, -}); - -itest!(worker_message_handler_error { - args: "run -A --quiet --reload workers/worker_message_handler_error.ts", - output: "workers/worker_message_handler_error.ts.out", - http_server: true, - exit_code: 1, -}); - -itest!(nonexistent_worker { - args: "run --allow-read workers/nonexistent_worker.ts", - output: "workers/nonexistent_worker.out", - exit_code: 1, -}); - -itest!(_084_worker_custom_inspect { - args: "run --allow-read workers/custom_inspect/main.ts", - output: "workers/custom_inspect/main.out", -}); - -itest!(error_worker_permissions_local { - args: "run --reload workers/error_worker_permissions_local.ts", - output: "workers/error_worker_permissions_local.ts.out", - exit_code: 1, -}); - -itest!(error_worker_permissions_remote { - args: "run --reload workers/error_worker_permissions_remote.ts", - http_server: true, - output: "workers/error_worker_permissions_remote.ts.out", - exit_code: 1, -}); - -itest!(worker_permissions_remote_remote { - args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_remote_remote.ts", - output: "workers/permissions_remote_remote.ts.out", - http_server: true, - exit_code: 1, -}); - -itest!(worker_permissions_dynamic_remote { - args: "run --quiet --reload --allow-net --unstable workers/permissions_dynamic_remote.ts", - output: "workers/permissions_dynamic_remote.ts.out", - http_server: true, - exit_code: 1, -}); - -itest!(worker_permissions_data_remote { - args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_data_remote.ts", - output: "workers/permissions_data_remote.ts.out", - http_server: true, - exit_code: 1, -}); - -itest!(worker_permissions_blob_remote { - args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_blob_remote.ts", - output: "workers/permissions_blob_remote.ts.out", - http_server: true, - exit_code: 1, -}); - -itest!(worker_permissions_data_local { - args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_data_local.ts", - output: "workers/permissions_data_local.ts.out", - http_server: true, - exit_code: 1, -}); - -itest!(worker_permissions_blob_local { - args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_blob_local.ts", - output: "workers/permissions_blob_local.ts.out", - http_server: true, - exit_code: 1, -}); - -itest!(worker_terminate_tla_crash { - args: "run --quiet --reload workers/terminate_tla_crash.js", - output: "workers/terminate_tla_crash.js.out", -}); - -itest!(worker_error_event { - args: "run --quiet -A workers/error_event.ts", - output: "workers/error_event.ts.out", - exit_code: 1, -}); diff --git a/cli/tests/integration_tests.rs b/cli/tests/integration_tests.rs deleted file mode 100644 index ae6bf98f6f..0000000000 --- a/cli/tests/integration_tests.rs +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. - -// The tests exist in a sub folder instead of as separate files in -// this directory so that cargo doesn't compile each file as a new crate. - -mod integration; diff --git a/cli/tests/js_unit_tests.rs b/cli/tests/js_unit_tests.rs new file mode 100644 index 0000000000..3d887600c3 --- /dev/null +++ b/cli/tests/js_unit_tests.rs @@ -0,0 +1,45 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +use test_util as util; + +mod js { + use super::*; + + #[test] + fn js_unit_tests_lint() { + let status = util::deno_cmd() + .arg("lint") + .arg("--unstable") + .arg(util::tests_path().join("unit")) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + + #[test] + fn js_unit_tests() { + let _g = util::http_server(); + + // Note that the unit tests are not safe for concurrency and must be run with a concurrency limit + // of one because there are some chdir tests in there. + // TODO(caspervonb) split these tests into two groups: parallel and serial. + let mut deno = util::deno_cmd() + .current_dir(util::root_path()) + .arg("test") + .arg("--unstable") + .arg("--location=http://js-unit-tests/foo/bar") + .arg("--no-prompt") + .arg("-A") + .arg(util::tests_path().join("unit")) + .spawn() + .expect("failed to spawn script"); + + let status = deno.wait().expect("failed to wait for the child process"); + assert_eq!(Some(0), status.code()); + assert!(status.success()); + } +} diff --git a/cli/tests/lint_tests.rs b/cli/tests/lint_tests.rs new file mode 100644 index 0000000000..36bf412923 --- /dev/null +++ b/cli/tests/lint_tests.rs @@ -0,0 +1,139 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +use test_util as util; + +mod lint { + use super::*; + + #[test] + fn ignore_unexplicit_files() { + let output = util::deno_cmd() + .current_dir(util::root_path()) + .env("NO_COLOR", "1") + .arg("lint") + .arg("--unstable") + .arg("--ignore=./") + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + assert_eq!( + String::from_utf8_lossy(&output.stderr), + "error: No target files found.\n" + ); + } + + itest!(all { + args: "lint lint/without_config/file1.js lint/without_config/file2.ts lint/without_config/ignored_file.ts", + output: "lint/expected.out", + exit_code: 1, +}); + + itest!(quiet { + args: "lint --quiet lint/without_config/file1.js", + output: "lint/expected_quiet.out", + exit_code: 1, + }); + + itest!(json { + args: + "lint --json lint/without_config/file1.js lint/without_config/file2.ts lint/without_config/ignored_file.ts lint/without_config/malformed.js", + output: "lint/expected_json.out", + exit_code: 1, +}); + + itest!(compact { + args: + "lint --compact lint/without_config/file1.js lint/without_config/ignored_file.tss", + output: "lint/expected_compact.out", + exit_code: 1, +}); + + itest!(ignore { + args: + "lint --ignore=lint/without_config/file1.js,lint/without_config/malformed.js,lint/without_config/lint_with_config/ lint/without_config/", + output: "lint/expected_ignore.out", + exit_code: 1, +}); + + itest!(glob { + args: "lint --ignore=lint/without_config/malformed.js,lint/with_config/ lint/without_config/", + output: "lint/expected_glob.out", + exit_code: 1, +}); + + itest!(stdin { + args: "lint -", + input: Some("let _a: any;"), + output: "lint/expected_from_stdin.out", + exit_code: 1, + }); + + itest!(stdin_json { + args: "lint --json -", + input: Some("let _a: any;"), + output: "lint/expected_from_stdin_json.out", + exit_code: 1, + }); + + itest!(rules { + args: "lint --rules", + output: "lint/expected_rules.out", + exit_code: 0, + }); + + // Make sure that the rules are printed if quiet option is enabled. + itest!(rules_quiet { + args: "lint --rules -q", + output: "lint/expected_rules.out", + exit_code: 0, + }); + + itest!(lint_with_config { + args: "lint --config lint/Deno.jsonc lint/with_config/", + output: "lint/with_config.out", + exit_code: 1, + }); + + itest!(lint_with_report_config { + args: "lint --config lint/Deno.compact.format.jsonc lint/with_config/", + output: "lint/with_report_config_compact.out", + exit_code: 1, + }); + + // Check if CLI flags take precedence + itest!(lint_with_report_config_override { + args: + "lint --config lint/Deno.compact.format.jsonc lint/with_config/ --json", + output: "lint/with_report_config_override.out", + exit_code: 1, + }); + + itest!(lint_with_config_and_flags { + args: "lint --config lint/Deno.jsonc --ignore=lint/with_config/a.ts", + output: "lint/with_config_and_flags.out", + exit_code: 1, + }); + + itest!(lint_with_config_without_tags { + args: "lint --config lint/Deno.no_tags.jsonc lint/with_config/", + output: "lint/with_config_without_tags.out", + exit_code: 1, + }); + + itest!(lint_with_malformed_config { + args: "lint --config lint/Deno.malformed.jsonc", + output: "lint/with_malformed_config.out", + exit_code: 1, + }); + + itest!(lint_with_malformed_config2 { + args: "lint --config lint/Deno.malformed2.jsonc", + output: "lint/with_malformed_config2.out", + exit_code: 1, + }); +} diff --git a/cli/tests/lsp_tests.rs b/cli/tests/lsp_tests.rs new file mode 100644 index 0000000000..066f3efa81 --- /dev/null +++ b/cli/tests/lsp_tests.rs @@ -0,0 +1,6383 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod lsp { + use deno_ast::ModuleSpecifier; + use deno_core::serde::de::DeserializeOwned; + use deno_core::serde::Deserialize; + use deno_core::serde::Serialize; + use deno_core::serde_json; + use deno_core::serde_json::json; + use deno_core::serde_json::Value; + use deno_core::url::Url; + use pretty_assertions::assert_eq; + use std::collections::HashSet; + use std::fs; + use std::process::Stdio; + use test_util::deno_cmd_with_deno_dir; + use test_util::deno_exe_path; + use test_util::env_vars_for_npm_tests; + use test_util::http_server; + use test_util::lsp::LspClient; + use test_util::testdata_path; + use test_util::TempDir; + use tower_lsp::lsp_types as lsp; + + fn load_fixture(path: &str) -> Value { + load_fixture_as(path) + } + + fn load_fixture_as(path: &str) -> T + where + T: DeserializeOwned, + { + let fixture_str = load_fixture_str(path); + serde_json::from_str::(&fixture_str).unwrap() + } + + fn load_fixture_str(path: &str) -> String { + let fixtures_path = testdata_path().join("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, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", load_fixture(init_path)) + .unwrap(); + client.write_notification("initialized", json!({})).unwrap(); + client + } + + fn did_open( + client: &mut LspClient, + params: V, + ) -> Vec + where + V: Serialize, + { + client + .write_notification("textDocument/didOpen", params) + .unwrap(); + + handle_configuration_request( + client, + json!([{ + "enable": true, + "codeLens": { + "test": true + } + }]), + ); + read_diagnostics(client).0 + } + + fn handle_configuration_request(client: &mut LspClient, result: Value) { + let (id, method, _) = client.read_request::().unwrap(); + assert_eq!(method, "workspace/configuration"); + client.write_response(id, result).unwrap(); + } + + fn read_diagnostics(client: &mut LspClient) -> CollectedDiagnostics { + // diagnostics come in batches of three unless they're cancelled + let mut diagnostics = vec![]; + for _ in 0..3 { + let (method, response) = client + .read_notification::() + .unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + diagnostics.push(response.unwrap()); + } + CollectedDiagnostics(diagnostics) + } + + fn shutdown(client: &mut LspClient) { + client + .write_request::<_, _, Value>("shutdown", json!(null)) + .unwrap(); + client.write_notification("exit", json!(null)).unwrap(); + } + + pub fn ensure_directory_specifier( + mut specifier: ModuleSpecifier, + ) -> ModuleSpecifier { + let path = specifier.path(); + if !path.ends_with('/') { + let new_path = format!("{}/", path); + specifier.set_path(&new_path); + } + specifier + } + + struct TestSession { + client: LspClient, + open_file_count: usize, + } + + impl TestSession { + pub fn from_file(init_path: &str) -> Self { + Self::from_client(init(init_path)) + } + + pub fn from_client(client: LspClient) -> Self { + Self { + client, + open_file_count: 0, + } + } + + pub fn did_open(&mut self, params: V) -> CollectedDiagnostics + where + V: Serialize, + { + self + .client + .write_notification("textDocument/didOpen", params) + .unwrap(); + + let (id, method, _) = self.client.read_request::().unwrap(); + assert_eq!(method, "workspace/configuration"); + self + .client + .write_response( + id, + json!([{ + "enable": true, + "codeLens": { + "test": true + } + }]), + ) + .unwrap(); + + self.open_file_count += 1; + self.read_diagnostics() + } + + pub fn read_diagnostics(&mut self) -> CollectedDiagnostics { + let mut all_diagnostics = Vec::new(); + for _ in 0..self.open_file_count { + all_diagnostics.extend(read_diagnostics(&mut self.client).0); + } + CollectedDiagnostics(all_diagnostics) + } + + pub fn shutdown_and_exit(&mut self) { + shutdown(&mut self.client); + } + } + + #[derive(Debug, Clone)] + struct CollectedDiagnostics(Vec); + + impl CollectedDiagnostics { + /// Gets the diagnostics that the editor will see after all the publishes. + pub fn viewed(&self) -> Vec { + self + .viewed_messages() + .into_iter() + .flat_map(|m| m.diagnostics) + .collect() + } + + /// Gets the messages that the editor will see after all the publishes. + pub fn viewed_messages(&self) -> Vec { + // go over the publishes in reverse order in order to get + // the final messages that will be shown in the editor + let mut messages = Vec::new(); + let mut had_specifier = HashSet::new(); + for message in self.0.iter().rev() { + if had_specifier.insert(message.uri.clone()) { + messages.insert(0, message.clone()); + } + } + messages + } + + pub fn with_source(&self, source: &str) -> lsp::PublishDiagnosticsParams { + self + .viewed_messages() + .iter() + .find(|p| { + p.diagnostics + .iter() + .any(|d| d.source == Some(source.to_string())) + }) + .map(ToOwned::to_owned) + .unwrap() + } + + pub fn with_file_and_source( + &self, + specifier: &str, + source: &str, + ) -> lsp::PublishDiagnosticsParams { + let specifier = ModuleSpecifier::parse(specifier).unwrap(); + self + .viewed_messages() + .iter() + .find(|p| { + p.uri == specifier + && p + .diagnostics + .iter() + .any(|d| d.source == Some(source.to_string())) + }) + .map(ToOwned::to_owned) + .unwrap() + } + } + + #[test] + fn lsp_startup_shutdown() { + let mut client = init("initialize_params.json"); + shutdown(&mut client); + } + + #[test] + fn lsp_init_tsconfig() { + let temp_dir = TempDir::new(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); + let tsconfig = + serde_json::to_vec_pretty(&load_fixture("lib.tsconfig.json")).unwrap(); + fs::write(temp_dir.path().join("lib.tsconfig.json"), tsconfig).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!("./lib.tsconfig.json")); + params.initialization_options = Some(Value::Object(map)); + } + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + + client.write_notification("initialized", json!({})).unwrap(); + + let diagnostics = did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "location.pathname;\n" + } + }), + ); + + let diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics); + assert_eq!(diagnostics.count(), 0); + + 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(); + 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, false).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_tsconfig_bad_config_path() { + let mut client = init("initialize_params_bad_config_option.json"); + let (method, maybe_params) = client.read_notification().unwrap(); + assert_eq!(method, "window/showMessage"); + assert_eq!(maybe_params, Some(lsp::ShowMessageParams { + typ: lsp::MessageType::WARNING, + message: "The path to the configuration file (\"bad_tsconfig.json\") is not resolvable.".to_string() + })); + let diagnostics = did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "console.log(Deno.args);\n" + } + }), + ); + let diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics); + assert_eq!(diagnostics.count(), 0); + } + + #[test] + fn lsp_triple_slash_types() { + let temp_dir = TempDir::new(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).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()); + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).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": "/// \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_import_map() { + let temp_dir = TempDir::new(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); + let import_map = + serde_json::to_vec_pretty(&load_fixture("import-map.json")).unwrap(); + fs::write(temp_dir.path().join("import-map.json"), import_map).unwrap(); + fs::create_dir(temp_dir.path().join("lib")).unwrap(); + fs::write( + temp_dir.path().join("lib").join("b.ts"), + r#"export const b = "b";"#, + ) + .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("importMap".to_string(), json!("import-map.json")); + params.initialization_options = Some(Value::Object(map)); + } + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + + client.write_notification("initialized", json!({})).unwrap(); + let uri = Url::from_file_path(temp_dir.path().join("a.ts")).unwrap(); + + let diagnostics = did_open( + &mut client, + json!({ + "textDocument": { + "uri": uri, + "languageId": "typescript", + "version": 1, + "text": "import { b } from \"/~/b.ts\";\n\nconsole.log(b);\n" + } + }), + ); + + let diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics); + assert_eq!(diagnostics.count(), 0); + + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": uri + }, + "position": { + "line": 2, + "character": 12 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value":"(alias) const b: \"b\"\nimport b" + }, + "" + ], + "range": { + "start": { + "line": 2, + "character": 12 + }, + "end": { + "line": 2, + "character": 13 + } + } + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_import_map_data_url() { + let mut client = init("initialize_params_import_map.json"); + let diagnostics = did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "import example from \"example\";\n" + } + }), + ); + + let mut diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics); + // This indicates that the import map from initialize_params_import_map.json + // is applied correctly. + assert!(diagnostics.any(|diagnostic| diagnostic.code + == Some(lsp::NumberOrString::String("no-cache".to_string())) + && diagnostic + .message + .contains("https://deno.land/x/example/mod.ts"))); + shutdown(&mut client); + } + + #[test] + fn lsp_import_map_config_file() { + let temp_dir = TempDir::new(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); + + let deno_import_map_jsonc = + serde_json::to_vec_pretty(&load_fixture("deno.import_map.jsonc")) + .unwrap(); + fs::write( + temp_dir.path().join("deno.import_map.jsonc"), + deno_import_map_jsonc, + ) + .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!("./deno.import_map.jsonc")); + params.initialization_options = Some(Value::Object(map)); + } + let import_map = + serde_json::to_vec_pretty(&load_fixture("import-map.json")).unwrap(); + fs::write(temp_dir.path().join("import-map.json"), import_map).unwrap(); + fs::create_dir(temp_dir.path().join("lib")).unwrap(); + fs::write( + temp_dir.path().join("lib").join("b.ts"), + r#"export const b = "b";"#, + ) + .unwrap(); + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + + client.write_notification("initialized", json!({})).unwrap(); + let uri = Url::from_file_path(temp_dir.path().join("a.ts")).unwrap(); + + let diagnostics = did_open( + &mut client, + json!({ + "textDocument": { + "uri": uri, + "languageId": "typescript", + "version": 1, + "text": "import { b } from \"/~/b.ts\";\n\nconsole.log(b);\n" + } + }), + ); + + let diagnostics = diagnostics.into_iter().flat_map(|x| x.diagnostics); + assert_eq!(diagnostics.count(), 0); + + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": uri + }, + "position": { + "line": 2, + "character": 12 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value":"(alias) const b: \"b\"\nimport b" + }, + "" + ], + "range": { + "start": { + "line": 2, + "character": 12 + }, + "end": { + "line": 2, + "character": 13 + } + } + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_deno_task() { + let temp_dir = TempDir::new(); + let workspace_root = temp_dir.path().canonicalize().unwrap(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); + fs::write( + workspace_root.join("deno.jsonc"), + r#"{ + "tasks": { + "build": "deno test", + "some:test": "deno bundle mod.ts" + } + }"#, + ) + .unwrap(); + + params.root_uri = Some(Url::from_file_path(workspace_root).unwrap()); + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>("deno/task", json!(null)) + .unwrap(); + + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!([ + { + "name": "build", + "detail": "deno test" + }, + { + "name": "some:test", + "detail": "deno bundle mod.ts" + } + ])) + ); + } + + #[test] + fn lsp_import_assertions() { + let mut client = init("initialize_params_import_map.json"); + client + .write_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": "file:///a/test.json", + "languageId": "json", + "version": 1, + "text": "{\"a\":1}" + } + }), + ) + .unwrap(); + handle_configuration_request( + &mut client, + json!([{ + "enable": true, + "codeLens": { + "test": true + } + }]), + ); + + let diagnostics = CollectedDiagnostics(did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/a.ts", + "languageId": "typescript", + "version": 1, + "text": "import a from \"./test.json\";\n\nconsole.log(a);\n" + } + }), + )); + + assert_eq!( + json!( + diagnostics + .with_file_and_source("file:///a/a.ts", "deno") + .diagnostics + ), + json!([ + { + "range": { + "start": { + "line": 0, + "character": 14 + }, + "end": { + "line": 0, + "character": 27 + } + }, + "severity": 1, + "code": "no-assert-type", + "source": "deno", + "message": "The module is a JSON module and not being imported with an import assertion. Consider adding `assert { type: \"json\" }` to the import statement." + } + ]) + ); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeAction", + load_fixture("code_action_params_import_assertion.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_action_response_import_assertion.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_import_map_import_completions() { + let temp_dir = TempDir::new(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); + let import_map = + serde_json::to_vec_pretty(&load_fixture("import-map-completions.json")) + .unwrap(); + fs::write(temp_dir.path().join("import-map.json"), import_map).unwrap(); + fs::create_dir(temp_dir.path().join("lib")).unwrap(); + fs::write( + temp_dir.path().join("lib").join("b.ts"), + r#"export const b = "b";"#, + ) + .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("importMap".to_string(), json!("import-map.json")); + params.initialization_options = Some(Value::Object(map)); + } + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + + client.write_notification("initialized", json!({})).unwrap(); + let uri = Url::from_file_path(temp_dir.path().join("a.ts")).unwrap(); + + did_open( + &mut client, + json!({ + "textDocument": { + "uri": uri, + "languageId": "typescript", + "version": 1, + "text": "import * as a from \"/~/b.ts\";\nimport * as b from \"\"" + } + }), + ); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/completion", + json!({ + "textDocument": { + "uri": uri + }, + "position": { + "line": 1, + "character": 20 + }, + "context": { + "triggerKind": 2, + "triggerCharacter": "\"" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "isIncomplete": false, + "items": [ + { + "label": ".", + "kind": 19, + "detail": "(local)", + "sortText": "1", + "insertText": ".", + "commitCharacters": ["\"", "'"], + }, + { + "label": "..", + "kind": 19, + "detail": "(local)", + "sortText": "1", + "insertText": "..", + "commitCharacters": ["\"", "'"], + }, + { + "label": "std", + "kind": 19, + "detail": "(import map)", + "sortText": "std", + "insertText": "std", + "commitCharacters": ["\"", "'"], + }, + { + "label": "fs", + "kind": 17, + "detail": "(import map)", + "sortText": "fs", + "insertText": "fs", + "commitCharacters": ["\"", "'"], + }, + { + "label": "/~", + "kind": 19, + "detail": "(import map)", + "sortText": "/~", + "insertText": "/~", + "commitCharacters": ["\"", "'"], + } + ] + })) + ); + + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": uri, + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 1, + "character": 20 + }, + "end": { + "line": 1, + "character": 20 + } + }, + "text": "/~/" + } + ] + }), + ) + .unwrap(); + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/completion", + json!({ + "textDocument": { + "uri": uri + }, + "position": { + "line": 1, + "character": 23 + }, + "context": { + "triggerKind": 2, + "triggerCharacter": "/" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "isIncomplete": false, + "items": [ + { + "label": "b.ts", + "kind": 9, + "detail": "(import map)", + "sortText": "1", + "filterText": "/~/b.ts", + "textEdit": { + "range": { + "start": { + "line": 1, + "character": 20 + }, + "end": { + "line": 1, + "character": 23 + } + }, + "newText": "/~/b.ts" + }, + "commitCharacters": ["\"", "'"], + } + ] + })) + ); + + shutdown(&mut client); + } + + #[test] + fn lsp_hover() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "console.log(Deno.args);\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 19 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value": "const Deno.args: string[]" + }, + "Returns the script arguments to the program.\n\nGive the following command line invocation of Deno:\n\n```sh\ndeno run --allow-read https://deno.land/std/examples/cat.ts /etc/passwd\n```\n\nThen `Deno.args` will contain:\n\n```\n[ \"/etc/passwd\" ]\n```\n\nIf you are looking for a structured way to parse arguments, there is the\n[`std/flags`](https://deno.land/std/flags) module as part of the Deno\nstandard library.", + "\n\n*@category* - Runtime Environment", + ], + "range": { + "start": { + "line": 0, + "character": 17 + }, + "end": { + "line": 0, + "character": 21 + } + } + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_hover_asset() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "console.log(Date.now());\n" + } + }), + ); + let (_, maybe_error) = client + .write_request::<_, _, Value>( + "textDocument/definition", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 14 + } + }), + ) + .unwrap(); + assert!(maybe_error.is_none()); + let (_, maybe_error) = client + .write_request::<_, _, Value>( + "deno/virtualTextDocument", + json!({ + "textDocument": { + "uri": "deno:/asset/lib.deno.shared_globals.d.ts" + } + }), + ) + .unwrap(); + assert!(maybe_error.is_none()); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "deno:/asset/lib.es2015.symbol.wellknown.d.ts" + }, + "position": { + "line": 109, + "character": 13 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value": "interface Date", + }, + "Enables basic storage and retrieval of dates and times." + ], + "range": { + "start": { + "line": 109, + "character": 10, + }, + "end": { + "line": 109, + "character": 14, + } + } + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_hover_disabled() { + let mut client = init("initialize_params_disabled.json"); + client + .write_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "console.log(Date.now());\n" + } + }), + ) + .unwrap(); + + handle_configuration_request(&mut client, json!([{ "enable": false }])); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 19 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!(null))); + shutdown(&mut client); + } + + #[test] + fn lsp_inlay_hints() { + let mut client = init("initialize_params_hints.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": r#"function a(b: string) { + return b; + } + + a("foo"); + + enum C { + A, + } + + parseInt("123", 8); + + const d = Date.now(); + + class E { + f = Date.now(); + } + + ["a"].map((v) => v + v); + "# + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/inlayHint", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 19, + "character": 0, + } + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + json!(maybe_res), + json!([ + { + "position": { + "line": 0, + "character": 21 + }, + "label": ": string", + "kind": 1, + "paddingLeft": true + }, + { + "position": { + "line": 4, + "character": 10 + }, + "label": "b:", + "kind": 2, + "paddingRight": true + }, + { + "position": { + "line": 7, + "character": 11 + }, + "label": "= 0", + "paddingLeft": true + }, + { + "position": { + "line": 10, + "character": 17 + }, + "label": "string:", + "kind": 2, + "paddingRight": true + }, + { + "position": { + "line": 10, + "character": 24 + }, + "label": "radix:", + "kind": 2, + "paddingRight": true + }, + { + "position": { + "line": 12, + "character": 15 + }, + "label": ": number", + "kind": 1, + "paddingLeft": true + }, + { + "position": { + "line": 15, + "character": 11 + }, + "label": ": number", + "kind": 1, + "paddingLeft": true + }, + { + "position": { + "line": 18, + "character": 18 + }, + "label": "callbackfn:", + "kind": 2, + "paddingRight": true + }, + { + "position": { + "line": 18, + "character": 20 + }, + "label": ": string", + "kind": 1, + "paddingLeft": true + }, + { + "position": { + "line": 18, + "character": 21 + }, + "label": ": string", + "kind": 1, + "paddingLeft": true + } + ]) + ); + } + + #[test] + fn lsp_inlay_hints_not_enabled() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": r#"function a(b: string) { + return b; + } + + a("foo"); + + enum C { + A, + } + + parseInt("123", 8); + + const d = Date.now(); + + class E { + f = Date.now(); + } + + ["a"].map((v) => v + v); + "# + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/inlayHint", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 19, + "character": 0, + } + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(json!(maybe_res), json!(null)); + } + + #[test] + fn lsp_workspace_enable_paths() { + let mut params: lsp::InitializeParams = serde_json::from_value( + load_fixture("initialize_params_workspace_enable_paths.json"), + ) + .unwrap(); + // we aren't actually writing anything to the tempdir in this test, but we + // just need a legitimate file path on the host system so that logic that + // tries to convert to and from the fs paths works on all env + let temp_dir = TempDir::new(); + + let root_specifier = + ensure_directory_specifier(Url::from_file_path(temp_dir.path()).unwrap()); + + params.root_uri = Some(root_specifier.clone()); + params.workspace_folders = Some(vec![lsp::WorkspaceFolder { + uri: root_specifier.clone(), + name: "project".to_string(), + }]); + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + + client.write_notification("initialized", json!({})).unwrap(); + + handle_configuration_request( + &mut client, + json!([{ + "enable": false, + "enablePaths": [ + "./worker" + ], + }]), + ); + + did_open( + &mut client, + json!({ + "textDocument": { + "uri": root_specifier.join("./file.ts").unwrap(), + "languageId": "typescript", + "version": 1, + "text": "console.log(Date.now());\n" + } + }), + ); + + did_open( + &mut client, + json!({ + "textDocument": { + "uri": root_specifier.join("./other/file.ts").unwrap(), + "languageId": "typescript", + "version": 1, + "text": "console.log(Date.now());\n" + } + }), + ); + + did_open( + &mut client, + json!({ + "textDocument": { + "uri": root_specifier.join("./worker/file.ts").unwrap(), + "languageId": "typescript", + "version": 1, + "text": "console.log(Date.now());\n" + } + }), + ); + + did_open( + &mut client, + json!({ + "textDocument": { + "uri": root_specifier.join("./worker/subdir/file.ts").unwrap(), + "languageId": "typescript", + "version": 1, + "text": "console.log(Date.now());\n" + } + }), + ); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": root_specifier.join("./file.ts").unwrap(), + }, + "position": { + "line": 0, + "character": 19 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!(null))); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": root_specifier.join("./other/file.ts").unwrap(), + }, + "position": { + "line": 0, + "character": 19 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!(null))); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": root_specifier.join("./worker/file.ts").unwrap(), + }, + "position": { + "line": 0, + "character": 19 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value": "(method) DateConstructor.now(): number", + }, + "Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC)." + ], + "range": { + "start": { + "line": 0, + "character": 17, + }, + "end": { + "line": 0, + "character": 20, + } + } + })) + ); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": root_specifier.join("./worker/subdir/file.ts").unwrap(), + }, + "position": { + "line": 0, + "character": 19 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value": "(method) DateConstructor.now(): number", + }, + "Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC)." + ], + "range": { + "start": { + "line": 0, + "character": 17, + }, + "end": { + "line": 0, + "character": 20, + } + } + })) + ); + + shutdown(&mut client); + } + + #[test] + fn lsp_hover_unstable_disabled() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "console.log(Deno.dlopen);\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 19 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value": "any" + } + ], + "range": { + "start": { + "line": 0, + "character": 17 + }, + "end": { + "line": 0, + "character": 23 + } + } + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_hover_unstable_enabled() { + let mut client = init("initialize_params_unstable.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "console.log(Deno.ppid);\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 19 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents":[ + { + "language":"typescript", + "value":"const Deno.ppid: number" + }, + "The process ID of parent process of this instance of the Deno CLI.\n\n```ts\nconsole.log(Deno.ppid);\n```", + "\n\n*@category* - Runtime Environment", + ], + "range":{ + "start":{ + "line":0, + "character":17 + }, + "end":{ + "line":0, + "character":21 + } + } + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_hover_change_mbc() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "const a = `编写软件很难`;\nconst b = `👍🦕😃`;\nconsole.log(a, b);\n" + } + }), + ); + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 1, + "character": 11 + }, + "end": { + "line": 1, + // the LSP uses utf16 encoded characters indexes, so + // after the deno emoiji is character index 15 + "character": 15 + } + }, + "text": "" + } + ] + }), + ) + .unwrap(); + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 2, + "character": 15 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value": "const b: \"😃\"", + }, + "", + ], + "range": { + "start": { + "line": 2, + "character": 15, + }, + "end": { + "line": 2, + "character": 16, + }, + } + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_hover_closed_document() { + let temp_dir_guard = TempDir::new(); + let temp_dir = temp_dir_guard.path(); + let a_path = temp_dir.join("a.ts"); + fs::write(a_path, r#"export const a = "a";"#).unwrap(); + let b_path = temp_dir.join("b.ts"); + fs::write(&b_path, r#"export * from "./a.ts";"#).unwrap(); + let b_specifier = Url::from_file_path(b_path).unwrap(); + let c_path = temp_dir.join("c.ts"); + fs::write(&c_path, "import { a } from \"./b.ts\";\nconsole.log(a);\n") + .unwrap(); + let c_specifier = Url::from_file_path(c_path).unwrap(); + + let mut client = init("initialize_params.json"); + client + .write_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": b_specifier, + "languageId": "typescript", + "version": 1, + "text": r#"export * from "./a.ts";"# + } + }), + ) + .unwrap(); + let (id, method, _) = client.read_request::().unwrap(); + assert_eq!(method, "workspace/configuration"); + client + .write_response(id, json!([{ "enable": true }])) + .unwrap(); + + client + .write_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": c_specifier, + "languageId": "typescript", + "version": 1, + "text": "import { a } from \"./b.ts\";\nconsole.log(a);\n", + } + }), + ) + .unwrap(); + let (id, method, _) = client.read_request::().unwrap(); + assert_eq!(method, "workspace/configuration"); + client + .write_response(id, json!([{ "enable": true }])) + .unwrap(); + + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": c_specifier, + }, + "position": { + "line": 0, + "character": 10 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value": "(alias) const a: \"a\"\nimport a" + }, + "" + ], + "range": { + "start": { + "line": 0, + "character": 9 + }, + "end": { + "line": 0, + "character": 10 + } + } + })) + ); + client + .write_notification( + "textDocument/didClose", + json!({ + "textDocument": { + "uri": b_specifier, + } + }), + ) + .unwrap(); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": c_specifier, + }, + "position": { + "line": 0, + "character": 10 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value": "(alias) const a: \"a\"\nimport a" + }, + "" + ], + "range": { + "start": { + "line": 0, + "character": 9 + }, + "end": { + "line": 0, + "character": 10 + } + } + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_hover_dependency() { + let _g = http_server(); + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file_01.ts", + "languageId": "typescript", + "version": 1, + "text": "export const a = \"a\";\n", + } + }), + ); + did_open( + &mut client, + load_fixture("did_open_params_import_hover.json"), + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "deno/cache", + json!({ + "referrer": { + "uri": "file:///a/file.ts", + }, + "uris": [], + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "position": { + "line": 0, + "character": 28 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": { + "kind": "markdown", + "value": "**Resolved Dependency**\n\n**Code**: http​://127.0.0.1:4545/xTypeScriptTypes.js\n\n**Types**: http​://127.0.0.1:4545/xTypeScriptTypes.d.ts\n" + }, + "range": { + "start": { + "line": 0, + "character": 19 + }, + "end":{ + "line": 0, + "character": 62 + } + } + })) + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "position": { + "line": 3, + "character": 28 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": { + "kind": "markdown", + "value": "**Resolved Dependency**\n\n**Code**: http​://127.0.0.1:4545/subdir/type_reference.js\n\n**Types**: http​://127.0.0.1:4545/subdir/type_reference.d.ts\n" + }, + "range": { + "start": { + "line": 3, + "character": 19 + }, + "end":{ + "line": 3, + "character": 67 + } + } + })) + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "position": { + "line": 4, + "character": 28 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": { + "kind": "markdown", + "value": "**Resolved Dependency**\n\n**Code**: http​://127.0.0.1:4545/subdir/mod1.ts\n" + }, + "range": { + "start": { + "line": 4, + "character": 19 + }, + "end":{ + "line": 4, + "character": 57 + } + } + })) + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "position": { + "line": 5, + "character": 28 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": { + "kind": "markdown", + "value": "**Resolved Dependency**\n\n**Code**: _(a data url)_\n" + }, + "range": { + "start": { + "line": 5, + "character": 19 + }, + "end":{ + "line": 5, + "character": 132 + } + } + })) + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "position": { + "line": 6, + "character": 28 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": { + "kind": "markdown", + "value": "**Resolved Dependency**\n\n**Code**: file​:///a/file_01.ts\n" + }, + "range": { + "start": { + "line": 6, + "character": 19 + }, + "end":{ + "line": 6, + "character": 33 + } + } + })) + ); + } + + // This tests for a regression covered by denoland/deno#12753 where the lsp was + // unable to resolve dependencies when there was an invalid syntax in the module + #[test] + fn lsp_hover_deps_preserved_when_invalid_parse() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file1.ts", + "languageId": "typescript", + "version": 1, + "text": "export type Foo = { bar(): string };\n" + } + }), + ); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file2.ts", + "languageId": "typescript", + "version": 1, + "text": "import { Foo } from './file1.ts'; declare const f: Foo; f\n" + } + }), + ); + let (maybe_res, maybe_error) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file2.ts" + }, + "position": { + "line": 0, + "character": 56 + } + }), + ) + .unwrap(); + assert!(maybe_error.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value": "const f: Foo", + }, + "" + ], + "range": { + "start": { + "line": 0, + "character": 56, + }, + "end": { + "line": 0, + "character": 57, + } + } + })) + ); + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file2.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 0, + "character": 57 + }, + "end": { + "line": 0, + "character": 58 + } + }, + "text": "." + } + ] + }), + ) + .unwrap(); + let (maybe_res, maybe_error) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file2.ts" + }, + "position": { + "line": 0, + "character": 56 + } + }), + ) + .unwrap(); + assert!(maybe_error.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value": "const f: Foo", + }, + "" + ], + "range": { + "start": { + "line": 0, + "character": 56, + }, + "end": { + "line": 0, + "character": 57, + } + } + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_hover_typescript_types() { + let _g = http_server(); + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "import * as a from \"http://127.0.0.1:4545/xTypeScriptTypes.js\";\n\nconsole.log(a.foo);\n", + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "deno/cache", + json!({ + "referrer": { + "uri": "file:///a/file.ts", + }, + "uris": [ + { + "uri": "http://127.0.0.1:4545/xTypeScriptTypes.js", + } + ], + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 24 + } + }), + ) + .unwrap(); + assert!(maybe_res.is_some()); + assert!(maybe_err.is_none()); + assert_eq!( + json!(maybe_res.unwrap()), + json!({ + "contents": { + "kind": "markdown", + "value": "**Resolved Dependency**\n\n**Code**: http​://127.0.0.1:4545/xTypeScriptTypes.js\n\n**Types**: http​://127.0.0.1:4545/xTypeScriptTypes.d.ts\n" + }, + "range": { + "start": { + "line": 0, + "character": 19 + }, + "end": { + "line": 0, + "character": 62 + } + } + }) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_hover_jsdoc_symbol_link() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/b.ts", + "languageId": "typescript", + "version": 1, + "text": "export function hello() {}\n" + } + }), + ); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "import { hello } from \"./b.ts\";\n\nhello();\n\nconst b = \"b\";\n\n/** JSDoc {@link hello} and {@linkcode b} */\nfunction a() {}\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 7, + "character": 10 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": [ + { + "language": "typescript", + "value": "function a(): void" + }, + "JSDoc [hello](file:///a/file.ts#L1,10) and [`b`](file:///a/file.ts#L5,7)" + ], + "range": { + "start": { + "line": 7, + "character": 9 + }, + "end": { + "line": 7, + "character": 10 + } + } + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_goto_type_definition() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "interface A {\n a: string;\n}\n\nexport class B implements A {\n a = \"a\";\n log() {\n console.log(this.a);\n }\n}\n\nconst b = new B();\nb;\n", + } + }), + ); + let (maybe_res, maybe_error) = client + .write_request::<_, _, Value>( + "textDocument/typeDefinition", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 12, + "character": 1 + } + }), + ) + .unwrap(); + assert!(maybe_error.is_none()); + assert_eq!( + maybe_res, + Some(json!([ + { + "targetUri": "file:///a/file.ts", + "targetRange": { + "start": { + "line": 4, + "character": 0 + }, + "end": { + "line": 9, + "character": 1 + } + }, + "targetSelectionRange": { + "start": { + "line": 4, + "character": 13 + }, + "end": { + "line": 4, + "character": 14 + } + } + } + ])) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_call_hierarchy() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "function foo() {\n return false;\n}\n\nclass Bar {\n baz() {\n return foo();\n }\n}\n\nfunction main() {\n const bar = new Bar();\n bar.baz();\n}\n\nmain();" + } + }), + ); + let (maybe_res, maybe_error) = client + .write_request( + "textDocument/prepareCallHierarchy", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 5, + "character": 3 + } + }), + ) + .unwrap(); + assert!(maybe_error.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("prepare_call_hierarchy_response.json")) + ); + let (maybe_res, maybe_error) = client + .write_request( + "callHierarchy/incomingCalls", + load_fixture("incoming_calls_params.json"), + ) + .unwrap(); + assert!(maybe_error.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("incoming_calls_response.json")) + ); + let (maybe_res, maybe_error) = client + .write_request( + "callHierarchy/outgoingCalls", + load_fixture("outgoing_calls_params.json"), + ) + .unwrap(); + assert!(maybe_error.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("outgoing_calls_response.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_large_doc_changes() { + let mut client = init("initialize_params.json"); + did_open(&mut client, load_fixture("did_open_params_large.json")); + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 444, + "character": 11 + }, + "end": { + "line": 444, + "character": 14 + } + }, + "text": "+++" + } + ] + }), + ) + .unwrap(); + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 445, + "character": 4 + }, + "end": { + "line": 445, + "character": 4 + } + }, + "text": "// " + } + ] + }), + ) + .unwrap(); + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 477, + "character": 4 + }, + "end": { + "line": 477, + "character": 9 + } + }, + "text": "error" + } + ] + }), + ) + .unwrap(); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 421, + "character": 30 + } + }), + ) + .unwrap(); + assert!(maybe_res.is_some()); + assert!(maybe_err.is_none()); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 444, + "character": 6 + } + }), + ) + .unwrap(); + assert!(maybe_res.is_some()); + assert!(maybe_err.is_none()); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 461, + "character": 34 + } + }), + ) + .unwrap(); + assert!(maybe_res.is_some()); + assert!(maybe_err.is_none()); + shutdown(&mut client); + + assert!(client.duration().as_millis() <= 15000); + } + + #[test] + fn lsp_document_symbol() { + let mut client = init("initialize_params.json"); + did_open(&mut client, load_fixture("did_open_params_doc_symbol.json")); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/documentSymbol", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("document_symbol_response.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_folding_range() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "// #region 1\n/*\n * Some comment\n */\nclass Foo {\n bar(a, b) {\n if (a === b) {\n return true;\n }\n return false;\n }\n}\n// #endregion" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/foldingRange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!([ + { + "startLine": 0, + "endLine": 12, + "kind": "region" + }, + { + "startLine": 1, + "endLine": 3, + "kind": "comment" + }, + { + "startLine": 4, + "endLine": 10 + }, + { + "startLine": 5, + "endLine": 9 + }, + { + "startLine": 6, + "endLine": 7 + } + ])) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_rename() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + // this should not rename in comments and strings + "text": "let variable = 'a'; // variable\nconsole.log(variable);\n\"variable\";\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/rename", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 4 + }, + "newName": "variable_modified" + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(load_fixture("rename_response.json"))); + shutdown(&mut client); + } + + #[test] + fn lsp_selection_range() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "class Foo {\n bar(a, b) {\n if (a === b) {\n return true;\n }\n return false;\n }\n}" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/selectionRange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "positions": [ + { + "line": 2, + "character": 8 + } + ] + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("selection_range_response.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_semantic_tokens() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + load_fixture("did_open_params_semantic_tokens.json"), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/semanticTokens/full", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "data": [ + 0, 5, 6, 1, 1, 0, 9, 6, 8, 9, 0, 8, 6, 8, 9, 2, 15, 3, 10, 5, 0, 4, 1, + 6, 1, 0, 12, 7, 2, 16, 1, 8, 1, 7, 41, 0, 4, 1, 6, 0, 0, 2, 5, 11, 16, + 1, 9, 1, 7, 40, 3, 10, 4, 2, 1, 1, 11, 1, 9, 9, 1, 2, 3, 11, 1, 3, 6, 3, + 0, 1, 0, 15, 4, 2, 0, 1, 30, 1, 6, 9, 1, 2, 3, 11,1, 1, 9, 9, 9, 3, 0, + 16, 3, 0, 0, 1, 17, 12, 11, 3, 0, 24, 3, 0, 0, 0, 4, 9, 9, 2 + ] + })) + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/semanticTokens/range", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 6, + "character": 0 + } + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "data": [ + 0, 5, 6, 1, 1, 0, 9, 6, 8, 9, 0, 8, 6, 8, 9, 2, 15, 3, 10, 5, 0, 4, 1, + 6, 1, 0, 12, 7, 2, 16, 1, 8, 1, 7, 41, 0, 4, 1, 6, 0, 0, 2, 5, 11, 16, + 1, 9, 1, 7, 40 + ] + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_code_lens() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "class A {\n a = \"a\";\n\n b() {\n console.log(this.a);\n }\n\n c() {\n this.a = \"c\";\n }\n}\n\nconst a = new A();\na.b();\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeLens", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(load_fixture("code_lens_response.json"))); + let (maybe_res, maybe_err) = client + .write_request( + "codeLens/resolve", + json!({ + "range": { + "start": { + "line": 0, + "character": 6 + }, + "end": { + "line": 0, + "character": 7 + } + }, + "data": { + "specifier": "file:///a/file.ts", + "source": "references" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_lens_resolve_response.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_code_lens_impl() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "interface A {\n b(): void;\n}\n\nclass B implements A {\n b() {\n console.log(\"b\");\n }\n}\n\ninterface C {\n c: string;\n}\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeLens", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_lens_response_impl.json")) + ); + let (maybe_res, maybe_err) = client + .write_request( + "codeLens/resolve", + json!({ + "range": { + "start": { + "line": 0, + "character": 10 + }, + "end": { + "line": 0, + "character": 11 + } + }, + "data": { + "specifier": "file:///a/file.ts", + "source": "implementations" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_lens_resolve_response_impl.json")) + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "codeLens/resolve", + json!({ + "range": { + "start": { + "line": 10, + "character": 10 + }, + "end": { + "line": 10, + "character": 11 + } + }, + "data": { + "specifier": "file:///a/file.ts", + "source": "implementations" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "range": { + "start": { + "line": 10, + "character": 10 + }, + "end": { + "line": 10, + "character": 11 + } + }, + "command": { + "title": "0 implementations", + "command": "" + } + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_code_lens_test() { + let mut client = init("initialize_params_code_lens_test.json"); + did_open( + &mut client, + load_fixture("did_open_params_test_code_lens.json"), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeLens", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_lens_response_test.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_code_lens_test_disabled() { + let mut client = init("initialize_params_code_lens_test_disabled.json"); + client + .write_notification( + "textDocument/didOpen", + load_fixture("did_open_params_test_code_lens.json"), + ) + .unwrap(); + + let (id, method, _) = client.read_request::().unwrap(); + assert_eq!(method, "workspace/configuration"); + client + .write_response( + id, + json!([{ + "enable": true, + "codeLens": { + "test": false + } + }]), + ) + .unwrap(); + + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + let (method, _) = client.read_notification::().unwrap(); + assert_eq!(method, "textDocument/publishDiagnostics"); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeLens", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!([]))); + shutdown(&mut client); + } + + #[test] + fn lsp_code_lens_non_doc_nav_tree() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "console.log(Date.now());\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/references", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 3 + }, + "context": { + "includeDeclaration": true + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "deno/virtualTextDocument", + json!({ + "textDocument": { + "uri": "deno:/asset/lib.deno.shared_globals.d.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Vec>( + "textDocument/codeLens", + json!({ + "textDocument": { + "uri": "deno:/asset/lib.deno.shared_globals.d.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let res = maybe_res.unwrap(); + assert!(res.len() > 50); + let (maybe_res, maybe_err) = client + .write_request::<_, _, lsp::CodeLens>( + "codeLens/resolve", + json!({ + "range": { + "start": { + "line": 416, + "character": 12 + }, + "end": { + "line": 416, + "character": 19 + } + }, + "data": { + "specifier": "asset:///lib.deno.shared_globals.d.ts", + "source": "references" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + shutdown(&mut client); + } + + #[test] + fn lsp_nav_tree_updates() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "interface A {\n b(): void;\n}\n\nclass B implements A {\n b() {\n console.log(\"b\");\n }\n}\n\ninterface C {\n c: string;\n}\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeLens", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_lens_response_impl.json")) + ); + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 10, + "character": 0 + }, + "end": { + "line": 13, + "character": 0 + } + }, + "text": "" + } + ] + }), + ) + .unwrap(); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeLens", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_lens_response_changed.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_signature_help() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "/**\n * Adds two numbers.\n * @param a This is a first number.\n * @param b This is a second number.\n */\nfunction add(a: number, b: number) {\n return a + b;\n}\n\nadd(" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/signatureHelp", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "character": 4, + "line": 9 + }, + "context": { + "triggerKind": 2, + "triggerCharacter": "(", + "isRetrigger": false + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "signatures": [ + { + "label": "add(a: number, b: number): number", + "documentation": { + "kind": "markdown", + "value": "Adds two numbers." + }, + "parameters": [ + { + "label": "a: number", + "documentation": { + "kind": "markdown", + "value": "This is a first number." + } + }, + { + "label": "b: number", + "documentation": { + "kind": "markdown", + "value": "This is a second number." + } + } + ] + } + ], + "activeSignature": 0, + "activeParameter": 0 + })) + ); + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 9, + "character": 4 + }, + "end": { + "line": 9, + "character": 4 + } + }, + "text": "123, " + } + ] + }), + ) + .unwrap(); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/signatureHelp", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "character": 8, + "line": 9 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "signatures": [ + { + "label": "add(a: number, b: number): number", + "documentation": { + "kind": "markdown", + "value": "Adds two numbers." + }, + "parameters": [ + { + "label": "a: number", + "documentation": { + "kind": "markdown", + "value": "This is a first number." + } + }, + { + "label": "b: number", + "documentation": { + "kind": "markdown", + "value": "This is a second number." + } + } + ] + } + ], + "activeSignature": 0, + "activeParameter": 1 + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_code_actions() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "export function a(): void {\n await Promise.resolve(\"a\");\n}\n\nexport function b(): void {\n await Promise.resolve(\"b\");\n}\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeAction", + load_fixture("code_action_params.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(load_fixture("code_action_response.json"))); + let (maybe_res, maybe_err) = client + .write_request( + "codeAction/resolve", + load_fixture("code_action_resolve_params.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_action_resolve_response.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_code_actions_deno_cache() { + let mut session = TestSession::from_file("initialize_params.json"); + let diagnostics = session.did_open(json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "import * as a from \"https://deno.land/x/a/mod.ts\";\n\nconsole.log(a);\n" + } + })); + assert_eq!( + diagnostics.with_source("deno"), + load_fixture_as("diagnostics_deno_deps.json") + ); + + let (maybe_res, maybe_err) = session + .client + .write_request( + "textDocument/codeAction", + load_fixture("code_action_params_cache.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_action_response_cache.json")) + ); + session.shutdown_and_exit(); + } + + #[test] + fn lsp_code_actions_deno_cache_npm() { + let mut session = TestSession::from_file("initialize_params.json"); + let diagnostics = session.did_open(json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "import chalk from \"npm:chalk\";\n\nconsole.log(chalk.green);\n" + } + })); + assert_eq!( + diagnostics.with_source("deno"), + load_fixture_as("code_actions/cache_npm/diagnostics.json") + ); + + let (maybe_res, maybe_err) = session + .client + .write_request( + "textDocument/codeAction", + load_fixture("code_actions/cache_npm/cache_action.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_actions/cache_npm/cache_response.json")) + ); + session.shutdown_and_exit(); + } + + #[test] + fn lsp_code_actions_imports() { + let mut session = TestSession::from_file("initialize_params.json"); + session.did_open(json!({ + "textDocument": { + "uri": "file:///a/file00.ts", + "languageId": "typescript", + "version": 1, + "text": "export const abc = \"abc\";\nexport const def = \"def\";\n" + } + })); + session.did_open(json!({ + "textDocument": { + "uri": "file:///a/file01.ts", + "languageId": "typescript", + "version": 1, + "text": "\nconsole.log(abc);\nconsole.log(def)\n" + } + })); + + let (maybe_res, maybe_err) = session + .client + .write_request( + "textDocument/codeAction", + load_fixture("code_action_params_imports.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_action_response_imports.json")) + ); + let (maybe_res, maybe_err) = session + .client + .write_request( + "codeAction/resolve", + load_fixture("code_action_resolve_params_imports.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_action_resolve_response_imports.json")) + ); + + session.shutdown_and_exit(); + } + + #[test] + fn lsp_code_actions_refactor() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "var x: { a?: number; b?: string } = {};\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeAction", + load_fixture("code_action_params_refactor.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_action_response_refactor.json")) + ); + let (maybe_res, maybe_err) = client + .write_request( + "codeAction/resolve", + load_fixture("code_action_resolve_params_refactor.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_action_resolve_response_refactor.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_code_actions_refactor_no_disabled_support() { + let mut client = init("initialize_params_ca_no_disabled.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "interface A {\n a: string;\n}\n\ninterface B {\n b: string;\n}\n\nclass AB implements A, B {\n a = \"a\";\n b = \"b\";\n}\n\nnew AB().a;\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeAction", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 14, + "character": 0 + } + }, + "context": { + "diagnostics": [], + "only": [ + "refactor" + ] + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_action_response_no_disabled.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_code_actions_deadlock() { + let mut client = init("initialize_params.json"); + client + .write_notification( + "textDocument/didOpen", + load_fixture("did_open_params_large.json"), + ) + .unwrap(); + let (id, method, _) = client.read_request::().unwrap(); + assert_eq!(method, "workspace/configuration"); + client + .write_response(id, json!([{ "enable": true }])) + .unwrap(); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/semanticTokens/full", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + read_diagnostics(&mut client); + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 444, + "character": 11 + }, + "end": { + "line": 444, + "character": 14 + } + }, + "text": "+++" + } + ] + }), + ) + .unwrap(); + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 445, + "character": 4 + }, + "end": { + "line": 445, + "character": 4 + } + }, + "text": "// " + } + ] + }), + ) + .unwrap(); + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 477, + "character": 4 + }, + "end": { + "line": 477, + "character": 9 + } + }, + "text": "error" + } + ] + }), + ) + .unwrap(); + // diagnostics only trigger after changes have elapsed in a separate thread, + // so we need to delay the next messages a little bit to attempt to create a + // potential for a deadlock with the codeAction + std::thread::sleep(std::time::Duration::from_millis(50)); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "position": { + "line": 609, + "character": 33, + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/codeAction", + load_fixture("code_action_params_deadlock.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + + read_diagnostics(&mut client); + + shutdown(&mut client); + } + + #[test] + fn lsp_completions() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "Deno." + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/completion", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 5 + }, + "context": { + "triggerKind": 2, + "triggerCharacter": "." + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + if let Some(lsp::CompletionResponse::List(list)) = maybe_res { + assert!(!list.is_incomplete); + assert!(list.items.len() > 90); + } else { + panic!("unexpected response"); + } + let (maybe_res, maybe_err) = client + .write_request( + "completionItem/resolve", + load_fixture("completion_resolve_params.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("completion_resolve_response.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_completions_optional() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "interface A {\n b?: string;\n}\n\nconst o: A = {};\n\nfunction c(s: string) {}\n\nc(o.)" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/completion", + load_fixture("completion_request_params_optional.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "isIncomplete": false, + "items": [ + { + "label": "b?", + "kind": 5, + "sortText": "11", + "filterText": "b", + "insertText": "b", + "commitCharacters": [".", ",", ";", "("], + "data": { + "tsc": { + "specifier": "file:///a/file.ts", + "position": 79, + "name": "b", + "useCodeSnippet": false + } + } + } + ] + })) + ); + let (maybe_res, maybe_err) = client + .write_request( + "completionItem/resolve", + load_fixture("completion_resolve_params_optional.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "label": "b?", + "kind": 5, + "detail": "(property) A.b?: string | undefined", + "documentation": { + "kind": "markdown", + "value": "" + }, + "sortText": "1", + "filterText": "b", + "insertText": "b" + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_completions_auto_import() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/b.ts", + "languageId": "typescript", + "version": 1, + "text": "export const foo = \"foo\";\n", + } + }), + ); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "export {};\n\n", + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/completion", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 2, + "character": 0, + }, + "context": { + "triggerKind": 1, + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + if let Some(lsp::CompletionResponse::List(list)) = maybe_res { + assert!(!list.is_incomplete); + if !list.items.iter().any(|item| item.label == "foo") { + panic!("completions items missing 'foo' symbol"); + } + } else { + panic!("unexpected completion response"); + } + let (maybe_res, maybe_err) = client + .write_request( + "completionItem/resolve", + json!({ + "label": "foo", + "kind": 6, + "sortText": "￿16", + "commitCharacters": [ + ".", + ",", + ";", + "(" + ], + "data": { + "tsc": { + "specifier": "file:///a/file.ts", + "position": 12, + "name": "foo", + "source": "./b", + "data": { + "exportName": "foo", + "moduleSpecifier": "./b", + "fileName": "file:///a/b.ts" + }, + "useCodeSnippet": false + } + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "label": "foo", + "kind": 6, + "detail": "const foo: \"foo\"", + "documentation": { + "kind": "markdown", + "value": "" + }, + "sortText": "￿16", + "additionalTextEdits": [ + { + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 0 + } + }, + "newText": "import { foo } from \"./b.ts\";\n\n" + } + ], + "commitCharacters": [ + ".", + ",", + ";", + "(" + ] + })) + ); + } + + #[test] + fn lsp_completions_snippet() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/a.tsx", + "languageId": "typescriptreact", + "version": 1, + "text": "function A({ type }: { type: string }) {\n return type;\n}\n\nfunction B() {\n return ( + "deno/cache", + json!({ + "referrer": { + "uri": "file:///a/file.ts", + }, + "uris": [ + { + "uri": "npm:@denotest/cjs-default-export", + }, + { + "uri": "npm:chalk", + } + ] + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + + // check importing a cjs default import + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 2, + "character": 0 + }, + "end": { + "line": 2, + "character": 0 + } + }, + "text": "cjsDefault." + } + ] + }), + ) + .unwrap(); + read_diagnostics(&mut client); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/completion", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 2, + "character": 11 + }, + "context": { + "triggerKind": 2, + "triggerCharacter": "." + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + if let Some(lsp::CompletionResponse::List(list)) = maybe_res { + assert!(!list.is_incomplete); + assert_eq!(list.items.len(), 3); + assert!(list.items.iter().any(|i| i.label == "default")); + assert!(list.items.iter().any(|i| i.label == "MyClass")); + } else { + panic!("unexpected response"); + } + let (maybe_res, maybe_err) = client + .write_request( + "completionItem/resolve", + load_fixture("completions/npm/resolve_params.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("completions/npm/resolve_response.json")) + ); + + // now check chalk, which is esm + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "version": 3 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 2, + "character": 0 + }, + "end": { + "line": 2, + "character": 11 + } + }, + "text": "chalk." + } + ] + }), + ) + .unwrap(); + read_diagnostics(&mut client); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/completion", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 2, + "character": 6 + }, + "context": { + "triggerKind": 2, + "triggerCharacter": "." + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + if let Some(lsp::CompletionResponse::List(list)) = maybe_res { + assert!(!list.is_incomplete); + assert!(list.items.iter().any(|i| i.label == "green")); + assert!(list.items.iter().any(|i| i.label == "red")); + } else { + panic!("unexpected response"); + } + + shutdown(&mut client); + } + + #[test] + fn lsp_npm_specifier_unopened_file() { + let _g = http_server(); + let mut client = init("initialize_params.json"); + + // create other.ts, which re-exports an npm specifier + client.deno_dir().write( + "other.ts", + "export { default as chalk } from 'npm:chalk@5';", + ); + + // cache the other.ts file to the DENO_DIR + let deno = deno_cmd_with_deno_dir(client.deno_dir()) + .current_dir(client.deno_dir().path()) + .arg("cache") + .arg("--quiet") + .arg("other.ts") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert!(output.status.success()); + assert_eq!(output.status.code(), Some(0)); + + let stdout = String::from_utf8(output.stdout).unwrap(); + assert!(stdout.is_empty()); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stderr.is_empty()); + + // open main.ts, which imports other.ts (unopened) + let main_url = + ModuleSpecifier::from_file_path(client.deno_dir().path().join("main.ts")) + .unwrap(); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": main_url, + "languageId": "typescript", + "version": 1, + "text": "import { chalk } from './other.ts';\n\n", + } + }), + ); + + client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": main_url, + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 2, + "character": 0 + }, + "end": { + "line": 2, + "character": 0 + } + }, + "text": "chalk." + } + ] + }), + ) + .unwrap(); + read_diagnostics(&mut client); + + // now ensure completions work + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/completion", + json!({ + "textDocument": { + "uri": main_url + }, + "position": { + "line": 2, + "character": 6 + }, + "context": { + "triggerKind": 2, + "triggerCharacter": "." + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + if let Some(lsp::CompletionResponse::List(list)) = maybe_res { + assert!(!list.is_incomplete); + assert_eq!(list.items.len(), 63); + assert!(list.items.iter().any(|i| i.label == "ansi256")); + } else { + panic!("unexpected response"); + } + } + + #[test] + fn lsp_completions_registry() { + let _g = http_server(); + let mut client = init("initialize_params_registry.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "import * as a from \"http://localhost:4545/x/a@\"" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/completion", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 46 + }, + "context": { + "triggerKind": 2, + "triggerCharacter": "@" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + if let Some(lsp::CompletionResponse::List(list)) = maybe_res { + assert!(!list.is_incomplete); + assert_eq!(list.items.len(), 3); + } else { + panic!("unexpected response"); + } + let (maybe_res, maybe_err) = client + .write_request( + "completionItem/resolve", + load_fixture("completion_resolve_params_registry.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("completion_resolve_response_registry.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_completions_registry_empty() { + let _g = http_server(); + let mut client = init("initialize_params_registry.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "import * as a from \"\"" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/completion", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 20 + }, + "context": { + "triggerKind": 2, + "triggerCharacter": "\"" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("completion_request_response_empty.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_auto_discover_registry() { + let _g = http_server(); + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "import * as a from \"http://localhost:4545/x/a@\"" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/completion", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 46 + }, + "context": { + "triggerKind": 2, + "triggerCharacter": "@" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let (method, maybe_res) = client.read_notification().unwrap(); + assert_eq!(method, "deno/registryState"); + assert_eq!( + maybe_res, + Some(json!({ + "origin": "http://localhost:4545", + "suggestions": true, + })) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_cache_location() { + let _g = http_server(); + let temp_dir = TempDir::new(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params_registry.json")) + .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("cache".to_string(), json!(".cache")); + params.initialization_options = Some(Value::Object(map)); + } + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + client.write_notification("initialized", json!({})).unwrap(); + let mut session = TestSession::from_client(client); + + session.did_open(json!({ + "textDocument": { + "uri": "file:///a/file_01.ts", + "languageId": "typescript", + "version": 1, + "text": "export const a = \"a\";\n", + } + })); + let diagnostics = + session.did_open(load_fixture("did_open_params_import_hover.json")); + assert_eq!(diagnostics.viewed().len(), 7); + let (maybe_res, maybe_err) = session + .client + .write_request::<_, _, Value>( + "deno/cache", + json!({ + "referrer": { + "uri": "file:///a/file.ts", + }, + "uris": [], + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let (maybe_res, maybe_err) = session + .client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "position": { + "line": 0, + "character": 28 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": { + "kind": "markdown", + "value": "**Resolved Dependency**\n\n**Code**: http​://127.0.0.1:4545/xTypeScriptTypes.js\n\n**Types**: http​://127.0.0.1:4545/xTypeScriptTypes.d.ts\n" + }, + "range": { + "start": { + "line": 0, + "character": 19 + }, + "end":{ + "line": 0, + "character": 62 + } + } + })) + ); + let (maybe_res, maybe_err) = session + .client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "position": { + "line": 7, + "character": 28 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": { + "kind": "markdown", + "value": "**Resolved Dependency**\n\n**Code**: http​://localhost:4545/x/a/mod.ts\n\n\n---\n\n**a**\n\nmod.ts" + }, + "range": { + "start": { + "line": 7, + "character": 19 + }, + "end": { + "line": 7, + "character": 53 + } + } + })) + ); + let cache_path = temp_dir.path().join(".cache"); + assert!(cache_path.is_dir()); + assert!(cache_path.join("gen").is_dir()); + session.shutdown_and_exit(); + } + + /// Sets the TLS root certificate on startup, which allows the LSP to connect to + /// the custom signed test server and be able to retrieve the registry config + /// and cache files. + #[test] + fn lsp_tls_cert() { + let _g = http_server(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params_tls_cert.json")) + .unwrap(); + + params.root_uri = Some(Url::from_file_path(testdata_path()).unwrap()); + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + client.write_notification("initialized", json!({})).unwrap(); + let mut session = TestSession::from_client(client); + + session.did_open(json!({ + "textDocument": { + "uri": "file:///a/file_01.ts", + "languageId": "typescript", + "version": 1, + "text": "export const a = \"a\";\n", + } + })); + let diagnostics = + session.did_open(load_fixture("did_open_params_tls_cert.json")); + let diagnostics = diagnostics.viewed(); + assert_eq!(diagnostics.len(), 7); + let (maybe_res, maybe_err) = session + .client + .write_request::<_, _, Value>( + "deno/cache", + json!({ + "referrer": { + "uri": "file:///a/file.ts", + }, + "uris": [], + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let (maybe_res, maybe_err) = session + .client + .write_request( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "position": { + "line": 0, + "character": 28 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": { + "kind": "markdown", + "value": "**Resolved Dependency**\n\n**Code**: https​://localhost:5545/xTypeScriptTypes.js\n" + }, + "range": { + "start": { + "line": 0, + "character": 19 + }, + "end":{ + "line": 0, + "character": 63 + } + } + })) + ); + let (maybe_res, maybe_err) = session + .client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + }, + "position": { + "line": 7, + "character": 28 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": { + "kind": "markdown", + "value": "**Resolved Dependency**\n\n**Code**: http​://localhost:4545/x/a/mod.ts\n\n\n---\n\n**a**\n\nmod.ts" + }, + "range": { + "start": { + "line": 7, + "character": 19 + }, + "end": { + "line": 7, + "character": 53 + } + } + })) + ); + session.shutdown_and_exit(); + } + + #[test] + fn lsp_diagnostics_warn_redirect() { + let _g = http_server(); + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "import * as a from \"http://127.0.0.1:4545/x_deno_warning.js\";\n\nconsole.log(a)\n", + }, + }), + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "deno/cache", + json!({ + "referrer": { + "uri": "file:///a/file.ts", + }, + "uris": [ + { + "uri": "http://127.0.0.1:4545/x_deno_warning.js", + } + ], + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let diagnostics = read_diagnostics(&mut client); + assert_eq!( + diagnostics.with_source("deno"), + lsp::PublishDiagnosticsParams { + uri: Url::parse("file:///a/file.ts").unwrap(), + diagnostics: vec![ + lsp::Diagnostic { + range: lsp::Range { + start: lsp::Position { + line: 0, + character: 19 + }, + end: lsp::Position { + line: 0, + character: 60 + } + }, + severity: Some(lsp::DiagnosticSeverity::WARNING), + code: Some(lsp::NumberOrString::String("deno-warn".to_string())), + source: Some("deno".to_string()), + message: "foobar".to_string(), + ..Default::default() + }, + lsp::Diagnostic { + range: lsp::Range { + start: lsp::Position { + line: 0, + character: 19 + }, + end: lsp::Position { + line: 0, + character: 60 + } + }, + severity: Some(lsp::DiagnosticSeverity::INFORMATION), + code: Some(lsp::NumberOrString::String("redirect".to_string())), + source: Some("deno".to_string()), + message: "The import of \"http://127.0.0.1:4545/x_deno_warning.js\" was redirected to \"http://127.0.0.1:4545/lsp/x_deno_warning_redirect.js\".".to_string(), + data: Some(json!({"specifier": "http://127.0.0.1:4545/x_deno_warning.js", "redirect": "http://127.0.0.1:4545/lsp/x_deno_warning_redirect.js"})), + ..Default::default() + } + ], + version: Some(1), + } + ); + shutdown(&mut client); + } + + #[test] + fn lsp_redirect_quick_fix() { + let _g = http_server(); + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "import * as a from \"http://127.0.0.1:4545/x_deno_warning.js\";\n\nconsole.log(a)\n", + }, + }), + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "deno/cache", + json!({ + "referrer": { + "uri": "file:///a/file.ts", + }, + "uris": [ + { + "uri": "http://127.0.0.1:4545/x_deno_warning.js", + } + ], + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let diagnostics = read_diagnostics(&mut client) + .with_source("deno") + .diagnostics; + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeAction", + json!(json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "range": { + "start": { + "line": 0, + "character": 19 + }, + "end": { + "line": 0, + "character": 60 + } + }, + "context": { + "diagnostics": diagnostics, + "only": [ + "quickfix" + ] + } + })), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_action_redirect_response.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_diagnostics_deprecated() { + let mut client = init("initialize_params.json"); + let diagnostics = did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "/** @deprecated */\nexport const a = \"a\";\n\na;\n", + }, + }), + ); + assert_eq!( + json!(diagnostics), + json!([ + { + "uri": "file:///a/file.ts", + "diagnostics": [], + "version": 1 + }, + { + "uri": "file:///a/file.ts", + "diagnostics": [], + "version": 1 + }, + { + "uri": "file:///a/file.ts", + "diagnostics": [ + { + "range": { + "start": { + "line": 3, + "character": 0 + }, + "end": { + "line": 3, + "character": 1 + } + }, + "severity": 4, + "code": 6385, + "source": "deno-ts", + "message": "'a' is deprecated.", + "relatedInformation": [], + "tags": [ + 2 + ] + } + ], + "version": 1 + } + ]) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_diagnostics_deno_types() { + let mut client = init("initialize_params.json"); + client + .write_notification( + "textDocument/didOpen", + load_fixture("did_open_params_deno_types.json"), + ) + .unwrap(); + let (id, method, _) = client.read_request::().unwrap(); + assert_eq!(method, "workspace/configuration"); + client + .write_response(id, json!([{ "enable": true }])) + .unwrap(); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/documentSymbol", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + } + }), + ) + .unwrap(); + assert!(maybe_res.is_some()); + assert!(maybe_err.is_none()); + let diagnostics = read_diagnostics(&mut client); + assert_eq!(diagnostics.viewed().len(), 5); + shutdown(&mut client); + } + + #[test] + fn lsp_diagnostics_refresh_dependents() { + let mut session = TestSession::from_file("initialize_params.json"); + session.did_open(json!({ + "textDocument": { + "uri": "file:///a/file_00.ts", + "languageId": "typescript", + "version": 1, + "text": "export const a = \"a\";\n", + }, + })); + session.did_open(json!({ + "textDocument": { + "uri": "file:///a/file_01.ts", + "languageId": "typescript", + "version": 1, + "text": "export * from \"./file_00.ts\";\n", + }, + })); + let diagnostics = session.did_open(json!({ + "textDocument": { + "uri": "file:///a/file_02.ts", + "languageId": "typescript", + "version": 1, + "text": "import { a, b } from \"./file_01.ts\";\n\nconsole.log(a, b);\n" + } + })); + assert_eq!( + json!(diagnostics.with_file_and_source("file:///a/file_02.ts", "deno-ts")), + json!({ + "uri": "file:///a/file_02.ts", + "diagnostics": [ + { + "range": { + "start": { + "line": 0, + "character": 12 + }, + "end": { + "line": 0, + "character": 13 + } + }, + "severity": 1, + "code": 2305, + "source": "deno-ts", + "message": "Module '\"./file_01.ts\"' has no exported member 'b'." + } + ], + "version": 1 + }) + ); + + // fix the code causing the diagnostic + session + .client + .write_notification( + "textDocument/didChange", + json!({ + "textDocument": { + "uri": "file:///a/file_00.ts", + "version": 2 + }, + "contentChanges": [ + { + "range": { + "start": { + "line": 1, + "character": 0 + }, + "end": { + "line": 1, + "character": 0 + } + }, + "text": "export const b = \"b\";\n" + } + ] + }), + ) + .unwrap(); + let diagnostics = session.read_diagnostics(); + assert_eq!(diagnostics.viewed().len(), 0); // no diagnostics now + + session.shutdown_and_exit(); + assert_eq!(session.client.queue_len(), 0); + } + + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + pub struct PerformanceAverage { + pub name: String, + pub count: u32, + pub average_duration: u32, + } + + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct PerformanceAverages { + averages: Vec, + } + + #[test] + fn lsp_performance() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "console.log(Deno.args);\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 19 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let (maybe_res, maybe_err) = client + .write_request::<_, _, PerformanceAverages>( + "deno/performance", + json!(null), + ) + .unwrap(); + assert!(maybe_err.is_none()); + if let Some(res) = maybe_res { + assert_eq!(res.averages.len(), 13); + } else { + panic!("unexpected result"); + } + shutdown(&mut client); + } + + #[test] + fn lsp_format_no_changes() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "console;\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/formatting", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "options": { + "tabSize": 2, + "insertSpaces": true + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!(null))); + client.assert_no_notification("window/showMessage"); + shutdown(&mut client); + } + + #[test] + fn lsp_format_error() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "console test test\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/formatting", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "options": { + "tabSize": 2, + "insertSpaces": true + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!(null))); + shutdown(&mut client); + } + + #[test] + fn lsp_format_mbc() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "const bar = '👍🇺🇸😃'\nconsole.log('hello deno')\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/formatting", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "options": { + "tabSize": 2, + "insertSpaces": true + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!(load_fixture("formatting_mbc_response.json"))) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_format_exclude_with_config() { + let temp_dir = TempDir::new(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); + let deno_fmt_jsonc = + serde_json::to_vec_pretty(&load_fixture("deno.fmt.exclude.jsonc")) + .unwrap(); + fs::write(temp_dir.path().join("deno.fmt.jsonc"), deno_fmt_jsonc).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!("./deno.fmt.jsonc")); + params.initialization_options = Some(Value::Object(map)); + } + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + + let file_uri = + ModuleSpecifier::from_file_path(temp_dir.path().join("ignored.ts")) + .unwrap() + .to_string(); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": file_uri, + "languageId": "typescript", + "version": 1, + "text": "function myFunc(){}" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/formatting", + json!({ + "textDocument": { + "uri": file_uri + }, + "options": { + "tabSize": 2, + "insertSpaces": true + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!(null))); + shutdown(&mut client); + } + + #[test] + fn lsp_format_exclude_default_config() { + let temp_dir = TempDir::new(); + let workspace_root = temp_dir.path().canonicalize().unwrap(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); + let deno_jsonc = + serde_json::to_vec_pretty(&load_fixture("deno.fmt.exclude.jsonc")) + .unwrap(); + fs::write(workspace_root.join("deno.jsonc"), deno_jsonc).unwrap(); + + params.root_uri = + Some(Url::from_file_path(workspace_root.clone()).unwrap()); + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + + let file_uri = + ModuleSpecifier::from_file_path(workspace_root.join("ignored.ts")) + .unwrap() + .to_string(); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": file_uri, + "languageId": "typescript", + "version": 1, + "text": "function myFunc(){}" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/formatting", + json!({ + "textDocument": { + "uri": file_uri + }, + "options": { + "tabSize": 2, + "insertSpaces": true + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!(null))); + shutdown(&mut client); + } + + #[test] + fn lsp_format_json() { + let mut client = init("initialize_params.json"); + client + .write_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": "file:///a/file.json", + "languageId": "json", + "version": 1, + "text": "{\"key\":\"value\"}" + } + }), + ) + .unwrap(); + + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/formatting", + json!({ + "textDocument": { + "uri": "file:///a/file.json" + }, + "options": { + "tabSize": 2, + "insertSpaces": true + } + }), + ) + .unwrap(); + + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!([ + { + "range": { + "start": { + "line": 0, + "character": 1 + }, + "end": { + "line": 0, + "character": 1 + } + }, + "newText": " " + }, + { + "range": { + "start": { "line": 0, "character": 7 }, + "end": { "line": 0, "character": 7 } + }, + "newText": " " + }, + { + "range": { + "start": { "line": 0, "character": 14 }, + "end": { "line": 0, "character": 15 } + }, + "newText": " }\n" + } + ])) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_json_no_diagnostics() { + let mut client = init("initialize_params.json"); + client + .write_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": "file:///a/file.json", + "languageId": "json", + "version": 1, + "text": "{\"key\":\"value\"}" + } + }), + ) + .unwrap(); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/semanticTokens/full", + json!({ + "textDocument": { + "uri": "file:///a/file.json" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!(null))); + + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.json" + }, + "position": { + "line": 0, + "character": 3 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!(null))); + + shutdown(&mut client); + } + + #[test] + fn lsp_format_markdown() { + let mut client = init("initialize_params.json"); + client + .write_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": "file:///a/file.md", + "languageId": "markdown", + "version": 1, + "text": "# Hello World" + } + }), + ) + .unwrap(); + + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/formatting", + json!({ + "textDocument": { + "uri": "file:///a/file.md" + }, + "options": { + "tabSize": 2, + "insertSpaces": true + } + }), + ) + .unwrap(); + + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!([ + { + "range": { + "start": { "line": 0, "character": 1 }, + "end": { "line": 0, "character": 3 } + }, + "newText": "" + }, + { + "range": { + "start": { "line": 0, "character": 15 }, + "end": { "line": 0, "character": 15 } + }, + "newText": "\n" + } + ])) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_format_with_config() { + let temp_dir = TempDir::new(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); + let deno_fmt_jsonc = + serde_json::to_vec_pretty(&load_fixture("deno.fmt.jsonc")).unwrap(); + fs::write(temp_dir.path().join("deno.fmt.jsonc"), deno_fmt_jsonc).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!("./deno.fmt.jsonc")); + params.initialization_options = Some(Value::Object(map)); + } + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + + client + .write_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "export async function someVeryLongFunctionName() {\nconst response = fetch(\"http://localhost:4545/some/non/existent/path.json\");\nconsole.log(response.text());\nconsole.log(\"finished!\")\n}" + } + }), + ) + .unwrap(); + + // The options below should be ignored in favor of configuration from config file. + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/formatting", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "options": { + "tabSize": 2, + "insertSpaces": true + } + }), + ) + .unwrap(); + + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!([{ + "range": { + "start": { + "line": 1, + "character": 0 + }, + "end": { + "line": 1, + "character": 0 + } + }, + "newText": "\t" + }, + { + "range": { + "start": { + "line": 1, + "character": 23 + }, + "end": { + "line": 1, + "character": 24 + } + }, + "newText": "\n\t\t'" + }, + { + "range": { + "start": { + "line": 1, + "character": 73 + }, + "end": { + "line": 1, + "character": 74 + } + }, + "newText": "',\n\t" + }, + { + "range": { + "start": { + "line": 2, + "character": 0 + }, + "end": { + "line": 2, + "character": 0 + } + }, + "newText": "\t" + }, + { + "range": { + "start": { + "line": 3, + "character": 0 + }, + "end": { + "line": 3, + "character": 0 + } + }, + "newText": "\t" + }, + { + "range": { + "start": { + "line": 3, + "character": 12 + }, + "end": { + "line": 3, + "character": 13 + } + }, + "newText": "'" + }, + { + "range": { + "start": { + "line": 3, + "character": 22 + }, + "end": { + "line": 3, + "character": 24 + } + }, + "newText": "');" + }, + { + "range": { + "start": { + "line": 4, + "character": 1 + }, + "end": { + "line": 4, + "character": 1 + } + }, + "newText": "\n" + }] + )) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_markdown_no_diagnostics() { + let mut client = init("initialize_params.json"); + client + .write_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": "file:///a/file.md", + "languageId": "markdown", + "version": 1, + "text": "# Hello World" + } + }), + ) + .unwrap(); + + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/semanticTokens/full", + json!({ + "textDocument": { + "uri": "file:///a/file.md" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!(null))); + + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.md" + }, + "position": { + "line": 0, + "character": 3 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!(maybe_res, Some(json!(null))); + + shutdown(&mut client); + } + + #[test] + fn lsp_configuration_did_change() { + let _g = http_server(); + let mut client = init("initialize_params_did_config_change.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "import * as a from \"http://localhost:4545/x/a@\"" + } + }), + ); + client + .write_notification( + "workspace/didChangeConfiguration", + json!({ + "settings": {} + }), + ) + .unwrap(); + let (id, method, _) = client.read_request::().unwrap(); + assert_eq!(method, "workspace/configuration"); + client + .write_response( + id, + json!([{ + "enable": true, + "codeLens": { + "implementations": true, + "references": true + }, + "importMap": null, + "lint": true, + "suggest": { + "autoImports": true, + "completeFunctionCalls": false, + "names": true, + "paths": true, + "imports": { + "hosts": { + "http://localhost:4545/": true + } + } + }, + "unstable": false + }]), + ) + .unwrap(); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/completion", + json!({ + "textDocument": { + "uri": "file:///a/file.ts" + }, + "position": { + "line": 0, + "character": 46 + }, + "context": { + "triggerKind": 2, + "triggerCharacter": "@" + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + if let Some(lsp::CompletionResponse::List(list)) = maybe_res { + assert!(!list.is_incomplete); + assert_eq!(list.items.len(), 3); + } else { + panic!("unexpected response"); + } + let (maybe_res, maybe_err) = client + .write_request( + "completionItem/resolve", + load_fixture("completion_resolve_params_registry.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("completion_resolve_response_registry.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_workspace_symbol() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "export class A {\n fieldA: string;\n fieldB: string;\n}\n", + } + }), + ); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file_01.ts", + "languageId": "typescript", + "version": 1, + "text": "export class B {\n fieldC: string;\n fieldD: string;\n}\n", + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "workspace/symbol", + json!({ + "query": "field" + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!([ + { + "name": "fieldA", + "kind": 8, + "location": { + "uri": "file:///a/file.ts", + "range": { + "start": { + "line": 1, + "character": 2 + }, + "end": { + "line": 1, + "character": 17 + } + } + }, + "containerName": "A" + }, + { + "name": "fieldB", + "kind": 8, + "location": { + "uri": "file:///a/file.ts", + "range": { + "start": { + "line": 2, + "character": 2 + }, + "end": { + "line": 2, + "character": 17 + } + } + }, + "containerName": "A" + }, + { + "name": "fieldC", + "kind": 8, + "location": { + "uri": "file:///a/file_01.ts", + "range": { + "start": { + "line": 1, + "character": 2 + }, + "end": { + "line": 1, + "character": 17 + } + } + }, + "containerName": "B" + }, + { + "name": "fieldD", + "kind": 8, + "location": { + "uri": "file:///a/file_01.ts", + "range": { + "start": { + "line": 2, + "character": 2 + }, + "end": { + "line": 2, + "character": 17 + } + } + }, + "containerName": "B" + } + ])) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_code_actions_ignore_lint() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": "let message = 'Hello, Deno!';\nconsole.log(message);\n" + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeAction", + load_fixture("code_action_ignore_lint_params.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_action_ignore_lint_response.json")) + ); + shutdown(&mut client); + } + + /// This test exercises updating an existing deno-lint-ignore-file comment. + #[test] + fn lsp_code_actions_update_ignore_lint() { + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.ts", + "languageId": "typescript", + "version": 1, + "text": +"#!/usr/bin/env -S deno run +// deno-lint-ignore-file camelcase +let snake_case = 'Hello, Deno!'; +console.log(snake_case); +", + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request( + "textDocument/codeAction", + load_fixture("code_action_update_ignore_lint_params.json"), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(load_fixture("code_action_update_ignore_lint_response.json")) + ); + shutdown(&mut client); + } + + #[test] + fn lsp_lint_with_config() { + let temp_dir = TempDir::new(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); + let deno_lint_jsonc = + serde_json::to_vec_pretty(&load_fixture("deno.lint.jsonc")).unwrap(); + fs::write(temp_dir.path().join("deno.lint.jsonc"), deno_lint_jsonc) + .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!("./deno.lint.jsonc")); + params.initialization_options = Some(Value::Object(map)); + } + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + let mut session = TestSession::from_client(client); + + let diagnostics = session.did_open(load_fixture("did_open_lint.json")); + let diagnostics = diagnostics.viewed(); + assert_eq!(diagnostics.len(), 1); + assert_eq!( + diagnostics[0].code, + Some(lsp::NumberOrString::String("ban-untagged-todo".to_string())) + ); + session.shutdown_and_exit(); + } + + #[test] + fn lsp_lint_exclude_with_config() { + let temp_dir = TempDir::new(); + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); + let deno_lint_jsonc = + serde_json::to_vec_pretty(&load_fixture("deno.lint.exclude.jsonc")) + .unwrap(); + fs::write(temp_dir.path().join("deno.lint.jsonc"), deno_lint_jsonc) + .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!("./deno.lint.jsonc")); + params.initialization_options = Some(Value::Object(map)); + } + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + + let diagnostics = did_open( + &mut client, + json!({ + "textDocument": { + "uri": ModuleSpecifier::from_file_path(temp_dir.path().join("ignored.ts")).unwrap().to_string(), + "languageId": "typescript", + "version": 1, + "text": "// TODO: fixme\nexport async function non_camel_case() {\nconsole.log(\"finished!\")\n}" + } + }), + ); + let diagnostics = diagnostics + .into_iter() + .flat_map(|x| x.diagnostics) + .collect::>(); + assert_eq!(diagnostics, Vec::new()); + shutdown(&mut client); + } + + #[test] + fn lsp_jsx_import_source_pragma() { + let _g = http_server(); + let mut client = init("initialize_params.json"); + did_open( + &mut client, + json!({ + "textDocument": { + "uri": "file:///a/file.tsx", + "languageId": "typescriptreact", + "version": 1, + "text": +"/** @jsxImportSource http://localhost:4545/jsx */ + +function A() { + return \"hello\"; +} + +export function B() { + return ; +} +", + } + }), + ); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "deno/cache", + json!({ + "referrer": { + "uri": "file:///a/file.tsx", + }, + "uris": [ + { + "uri": "http://127.0.0.1:4545/jsx/jsx-runtime", + } + ], + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let (maybe_res, maybe_err) = client + .write_request::<_, _, Value>( + "textDocument/hover", + json!({ + "textDocument": { + "uri": "file:///a/file.tsx" + }, + "position": { + "line": 0, + "character": 25 + } + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert_eq!( + maybe_res, + Some(json!({ + "contents": { + "kind": "markdown", + "value": "**Resolved Dependency**\n\n**Code**: http​://localhost:4545/jsx/jsx-runtime\n", + }, + "range": { + "start": { + "line": 0, + "character": 21 + }, + "end": { + "line": 0, + "character": 46 + } + } + })) + ); + shutdown(&mut client); + } + + #[derive(Debug, Clone, Deserialize, PartialEq)] + #[serde(rename_all = "camelCase")] + struct TestData { + id: String, + label: String, + steps: Option>, + range: Option, + } + + #[derive(Debug, Deserialize, PartialEq)] + #[serde(rename_all = "camelCase")] + enum TestModuleNotificationKind { + Insert, + Replace, + } + + #[derive(Debug, Deserialize)] + #[serde(rename_all = "camelCase")] + struct TestModuleNotificationParams { + text_document: lsp::TextDocumentIdentifier, + kind: TestModuleNotificationKind, + label: String, + tests: Vec, + } + + #[derive(Debug, Deserialize)] + #[serde(rename_all = "camelCase")] + struct EnqueuedTestModule { + text_document: lsp::TextDocumentIdentifier, + ids: Vec, + } + + #[derive(Debug, Deserialize)] + #[serde(rename_all = "camelCase")] + struct TestRunResponseParams { + enqueued: Vec, + } + + #[test] + fn lsp_testing_api() { + let mut params: lsp::InitializeParams = + serde_json::from_value(load_fixture("initialize_params.json")).unwrap(); + let temp_dir = TempDir::new(); + + let root_specifier = + ensure_directory_specifier(Url::from_file_path(temp_dir.path()).unwrap()); + + let module_path = temp_dir.path().join("./test.ts"); + let specifier = ModuleSpecifier::from_file_path(&module_path).unwrap(); + let contents = r#" +Deno.test({ + name: "test a", + fn() { + console.log("test a"); + } +}); +"#; + fs::write(&module_path, contents).unwrap(); + fs::write(temp_dir.path().join("./deno.jsonc"), r#"{}"#).unwrap(); + + params.root_uri = Some(root_specifier); + + let deno_exe = deno_exe_path(); + let mut client = LspClient::new(&deno_exe, false).unwrap(); + client + .write_request::<_, _, Value>("initialize", params) + .unwrap(); + + client.write_notification("initialized", json!({})).unwrap(); + + client + .write_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": specifier, + "languageId": "typescript", + "version": 1, + "text": contents, + } + }), + ) + .unwrap(); + + handle_configuration_request( + &mut client, + json!([{ + "enable": true, + "codeLens": { + "test": true + } + }]), + ); + + for _ in 0..4 { + let result = client.read_notification::(); + assert!(result.is_ok()); + let (method, notification) = result.unwrap(); + if method.as_str() == "deno/testModule" { + let params: TestModuleNotificationParams = + serde_json::from_value(notification.unwrap()).unwrap(); + assert_eq!(params.text_document.uri, specifier); + assert_eq!(params.kind, TestModuleNotificationKind::Replace); + assert_eq!(params.label, "test.ts"); + assert_eq!(params.tests.len(), 1); + let test = ¶ms.tests[0]; + assert_eq!(test.label, "test a"); + assert!(test.steps.is_none()); + assert_eq!( + test.range, + Some(lsp::Range { + start: lsp::Position { + line: 1, + character: 5, + }, + end: lsp::Position { + line: 1, + character: 9, + } + }) + ); + } + } + + let (maybe_res, maybe_err) = client + .write_request::<_, _, TestRunResponseParams>( + "deno/testRun", + json!({ + "id": 1, + "kind": "run", + }), + ) + .unwrap(); + assert!(maybe_err.is_none()); + assert!(maybe_res.is_some()); + let res = maybe_res.unwrap(); + assert_eq!(res.enqueued.len(), 1); + assert_eq!(res.enqueued[0].text_document.uri, specifier); + assert_eq!(res.enqueued[0].ids.len(), 1); + let id = res.enqueued[0].ids[0].clone(); + + let res = client.read_notification::(); + assert!(res.is_ok()); + let (method, notification) = res.unwrap(); + assert_eq!(method, "deno/testRunProgress"); + assert_eq!( + notification, + Some(json!({ + "id": 1, + "message": { + "type": "started", + "test": { + "textDocument": { + "uri": specifier, + }, + "id": id, + }, + } + })) + ); + + let res = client.read_notification::(); + assert!(res.is_ok()); + let (method, notification) = res.unwrap(); + assert_eq!(method, "deno/testRunProgress"); + let notification_value = notification + .as_ref() + .unwrap() + .as_object() + .unwrap() + .get("message") + .unwrap() + .as_object() + .unwrap() + .get("value") + .unwrap() + .as_str() + .unwrap(); + // deno test's output capturing flushes with a zero-width space in order to + // synchronize the output pipes. Occassionally this zero width space + // might end up in the output so strip it from the output comparison here. + assert_eq!(notification_value.replace('\u{200B}', ""), "test a\r\n"); + assert_eq!( + notification, + Some(json!({ + "id": 1, + "message": { + "type": "output", + "value": notification_value, + "test": { + "textDocument": { + "uri": specifier, + }, + "id": id, + }, + } + })) + ); + + let res = client.read_notification::(); + assert!(res.is_ok()); + let (method, notification) = res.unwrap(); + assert_eq!(method, "deno/testRunProgress"); + let notification = notification.unwrap(); + let obj = notification.as_object().unwrap(); + assert_eq!(obj.get("id"), Some(&json!(1))); + let message = obj.get("message").unwrap().as_object().unwrap(); + match message.get("type").and_then(|v| v.as_str()) { + Some("passed") => { + assert_eq!( + message.get("test"), + Some(&json!({ + "textDocument": { + "uri": specifier + }, + "id": id, + })) + ); + assert!(message.contains_key("duration")); + + let res = client.read_notification::(); + assert!(res.is_ok()); + let (method, notification) = res.unwrap(); + assert_eq!(method, "deno/testRunProgress"); + assert_eq!( + notification, + Some(json!({ + "id": 1, + "message": { + "type": "end", + } + })) + ); + } + // sometimes on windows, the messages come out of order, but it actually is + // working, so if we do get the end before the passed, we will simply let + // the test pass + Some("end") => (), + _ => panic!("unexpected message {}", json!(notification)), + } + + shutdown(&mut client); + } +} diff --git a/cli/tests/npm_tests.rs b/cli/tests/npm_tests.rs new file mode 100644 index 0000000000..05dc83cfd2 --- /dev/null +++ b/cli/tests/npm_tests.rs @@ -0,0 +1,1533 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +mod npm { + use super::*; + use pretty_assertions::assert_eq; + use std::process::Stdio; + use test_util as util; + use util::assert_contains; + use util::env_vars_for_npm_tests; + use util::env_vars_for_npm_tests_no_sync_download; + use util::http_server; + + // NOTE: See how to make test npm packages at ./testdata/npm/README.md + + itest!(esm_module { + args: "run --allow-read --allow-env npm/esm/main.js", + output: "npm/esm/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(esm_module_eval { + args_vec: vec![ + "eval", + "import chalk from 'npm:chalk@5'; console.log(chalk.green('chalk esm loads'));", + ], + output: "npm/esm/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, +}); + + itest!(esm_module_deno_test { + args: "test --allow-read --allow-env --unstable npm/esm/test.js", + output: "npm/esm/test.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(esm_import_cjs_default { + args: "run --allow-read --allow-env --unstable --quiet --check=all npm/esm_import_cjs_default/main.ts", + output: "npm/esm_import_cjs_default/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, +}); + + itest!(cjs_with_deps { + args: "run --allow-read --allow-env npm/cjs_with_deps/main.js", + output: "npm/cjs_with_deps/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(cjs_sub_path { + args: "run --allow-read npm/cjs_sub_path/main.js", + output: "npm/cjs_sub_path/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(cjs_local_global_decls { + args: "run --allow-read npm/cjs_local_global_decls/main.ts", + output: "npm/cjs_local_global_decls/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(cjs_reexport_collision { + args: "run -A --quiet npm/cjs_reexport_collision/main.ts", + output: "npm/cjs_reexport_collision/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(cjs_this_in_exports { + args: "run --allow-read --quiet npm/cjs_this_in_exports/main.js", + output: "npm/cjs_this_in_exports/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(translate_cjs_to_esm { + args: "run -A --quiet npm/translate_cjs_to_esm/main.js", + output: "npm/translate_cjs_to_esm/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(compare_globals { + args: "run --allow-read --unstable --check=all npm/compare_globals/main.ts", + output: "npm/compare_globals/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(conditional_exports { + args: "run --allow-read npm/conditional_exports/main.js", + output: "npm/conditional_exports/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(dual_cjs_esm { + args: "run -A --quiet npm/dual_cjs_esm/main.ts", + output: "npm/dual_cjs_esm/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(child_process_fork_test { + args: "run -A --quiet npm/child_process_fork_test/main.ts", + output: "npm/child_process_fork_test/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(cjs_module_export_assignment { + args: "run -A --unstable --quiet --check=all npm/cjs_module_export_assignment/main.ts", + output: "npm/cjs_module_export_assignment/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, +}); + + itest!(cjs_module_export_assignment_number { + args: "run -A --unstable --quiet --check=all npm/cjs_module_export_assignment_number/main.ts", + output: "npm/cjs_module_export_assignment_number/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, +}); + + itest!(mixed_case_package_name_global_dir { + args: "run npm/mixed_case_package_name/global.ts", + output: "npm/mixed_case_package_name/global.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(mixed_case_package_name_local_dir { + args: + "run --node-modules-dir -A $TESTDATA/npm/mixed_case_package_name/local.ts", + output: "npm/mixed_case_package_name/local.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + temp_cwd: true, + }); + + // FIXME(bartlomieju): npm: specifiers are not handled in dynamic imports + // at the moment + // itest!(dynamic_import { + // args: "run --allow-read --allow-env npm/dynamic_import/main.ts", + // output: "npm/dynamic_import/main.out", + // envs: env_vars_for_npm_tests(), + // http_server: true, + // }); + + itest!(dynamic_import_reload_same_package { + args: "run -A --reload npm/dynamic_import_reload_same_package/main.ts", + output: "npm/dynamic_import_reload_same_package/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(env_var_re_export_dev { + args: "run --allow-read --allow-env --quiet npm/env_var_re_export/main.js", + output_str: Some("dev\n"), + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(env_var_re_export_prod { + args: "run --allow-read --allow-env --quiet npm/env_var_re_export/main.js", + output_str: Some("prod\n"), + envs: { + let mut vars = env_vars_for_npm_tests(); + vars.push(("NODE_ENV".to_string(), "production".to_string())); + vars + }, + http_server: true, + }); + + itest!(cached_only { + args: "run --cached-only npm/cached_only/main.ts", + output: "npm/cached_only/main.out", + envs: env_vars_for_npm_tests(), + exit_code: 1, + }); + + itest!(import_map { + args: "run --allow-read --allow-env --import-map npm/import_map/import_map.json npm/import_map/main.js", + output: "npm/import_map/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(lock_file { + args: "run --allow-read --allow-env --lock npm/lock_file/lock.json npm/lock_file/main.js", + output: "npm/lock_file/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 10, + }); + + itest!(sub_paths { + args: "run -A --quiet npm/sub_paths/main.jsx", + output: "npm/sub_paths/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(remote_npm_specifier { + args: "run --quiet npm/remote_npm_specifier/main.ts", + output: "npm/remote_npm_specifier/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(tarball_with_global_header { + args: "run -A --quiet npm/tarball_with_global_header/main.js", + output: "npm/tarball_with_global_header/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(nonexistent_file { + args: "run -A --quiet npm/nonexistent_file/main.js", + output: "npm/nonexistent_file/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(invalid_package_name { + args: "run -A --quiet npm/invalid_package_name/main.js", + output: "npm/invalid_package_name/main.out", + envs: env_vars_for_npm_tests(), + exit_code: 1, + }); + + itest!(require_json { + args: "run -A --quiet npm/require_json/main.js", + output: "npm/require_json/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(error_version_after_subpath { + args: "run -A --quiet npm/error_version_after_subpath/main.js", + output: "npm/error_version_after_subpath/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(deno_cache { + args: "cache --reload npm:chalk npm:mkdirp", + output: "npm/deno_cache.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(check_all { + args: "check --all npm/check_errors/main.ts", + output: "npm/check_errors/main_all.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(check_local { + args: "check npm/check_errors/main.ts", + output: "npm/check_errors/main_local.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(types { + args: "check --quiet npm/types/main.ts", + output: "npm/types/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(types_ambient_module { + args: "check --quiet npm/types_ambient_module/main.ts", + output: "npm/types_ambient_module/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(types_ambient_module_import_map { + args: "check --quiet --import-map=npm/types_ambient_module/import_map.json npm/types_ambient_module/main_import_map.ts", + output: "npm/types_ambient_module/main_import_map.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(no_types_cjs { + args: "check --quiet npm/no_types_cjs/main.ts", + output_str: Some(""), + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(no_types_in_conditional_exports { + args: "run --check --unstable npm/no_types_in_conditional_exports/main.ts", + output: "npm/no_types_in_conditional_exports/main.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(types_entry_value_not_exists { + args: "check --all npm/types_entry_value_not_exists/main.ts", + output: "npm/types_entry_value_not_exists/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(types_exports_import_types { + args: "check --all npm/types_exports_import_types/main.ts", + output: "npm/types_exports_import_types/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(types_no_types_entry { + args: "check --all npm/types_no_types_entry/main.ts", + output: "npm/types_no_types_entry/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(typescript_file_in_package { + args: "run npm/typescript_file_in_package/main.ts", + output: "npm/typescript_file_in_package/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + #[test] + fn parallel_downloading() { + let (out, _err) = util::run_and_collect_output_with_args( + true, + vec![ + "run", + "--allow-read", + "--allow-env", + "npm/cjs_with_deps/main.js", + ], + None, + // don't use the sync env var + Some(env_vars_for_npm_tests_no_sync_download()), + true, + ); + assert!(out.contains("chalk cjs loads")); + } + + #[test] + fn cached_only_after_first_run() { + let _server = http_server(); + + let deno_dir = util::new_deno_dir(); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("npm/cached_only_after_first_run/main1.ts") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_contains!(stderr, "Download"); + assert_contains!(stdout, "createChalk: chalk"); + assert!(output.status.success()); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("--cached-only") + .arg("npm/cached_only_after_first_run/main2.ts") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_contains!( + stderr, + "An npm specifier not found in cache: \"ansi-styles\", --cached-only is specified." + ); + assert!(stdout.is_empty()); + assert!(!output.status.success()); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("--cached-only") + .arg("npm/cached_only_after_first_run/main1.ts") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + + let output = deno.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(output.status.success()); + assert!(stderr.is_empty()); + assert_contains!(stdout, "createChalk: chalk"); + } + + #[test] + fn reload_flag() { + let _server = http_server(); + + let deno_dir = util::new_deno_dir(); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("npm/reload/main.ts") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_contains!(stderr, "Download"); + assert_contains!(stdout, "createChalk: chalk"); + assert!(output.status.success()); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("--reload") + .arg("npm/reload/main.ts") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_contains!(stderr, "Download"); + assert_contains!(stdout, "createChalk: chalk"); + assert!(output.status.success()); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("--reload=npm:") + .arg("npm/reload/main.ts") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_contains!(stderr, "Download"); + assert_contains!(stdout, "createChalk: chalk"); + assert!(output.status.success()); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("--reload=npm:chalk") + .arg("npm/reload/main.ts") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_contains!(stderr, "Download"); + assert_contains!(stdout, "createChalk: chalk"); + assert!(output.status.success()); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("--reload=npm:foobar") + .arg("npm/reload/main.ts") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stderr.is_empty()); + assert_contains!(stdout, "createChalk: chalk"); + assert!(output.status.success()); + } + + #[test] + fn no_npm_after_first_run() { + let _server = http_server(); + + let deno_dir = util::new_deno_dir(); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("--no-npm") + .arg("npm/no_npm_after_first_run/main1.ts") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_contains!( + stderr, + "Following npm specifiers were requested: \"chalk@5\"; but --no-npm is specified." + ); + assert!(stdout.is_empty()); + assert!(!output.status.success()); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("npm/no_npm_after_first_run/main1.ts") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_contains!(stderr, "Download"); + assert_contains!(stdout, "createChalk: chalk"); + assert!(output.status.success()); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("--no-npm") + .arg("npm/no_npm_after_first_run/main1.ts") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_contains!( + stderr, + "Following npm specifiers were requested: \"chalk@5\"; but --no-npm is specified." + ); + assert!(stdout.is_empty()); + assert!(!output.status.success()); + } + + #[test] + fn deno_run_cjs_module() { + let _server = http_server(); + + let deno_dir = util::new_deno_dir(); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(deno_dir.path()) + .arg("run") + .arg("--allow-read") + .arg("--allow-env") + .arg("--allow-write") + .arg("npm:mkdirp@1.0.4") + .arg("test_dir") + .env("NO_COLOR", "1") + .envs(env_vars_for_npm_tests()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert!(output.status.success()); + + assert!(deno_dir.path().join("test_dir").exists()); + } + + itest!(deno_run_cowsay { + args: "run -A --quiet npm:cowsay@1.5.0 Hello", + output: "npm/deno_run_cowsay.out", + envs: env_vars_for_npm_tests_no_sync_download(), + http_server: true, + }); + + itest!(deno_run_cowsay_explicit { + args: "run -A --quiet npm:cowsay@1.5.0/cowsay Hello", + output: "npm/deno_run_cowsay.out", + envs: env_vars_for_npm_tests_no_sync_download(), + http_server: true, + }); + + itest!(deno_run_cowthink { + args: "run -A --quiet npm:cowsay@1.5.0/cowthink Hello", + output: "npm/deno_run_cowthink.out", + envs: env_vars_for_npm_tests_no_sync_download(), + http_server: true, + }); + + itest!(deno_run_bin_esm { + args: "run -A --quiet npm:@denotest/bin/cli-esm this is a test", + output: "npm/deno_run_esm.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(deno_run_bin_no_ext { + args: "run -A --quiet npm:@denotest/bin/cli-no-ext this is a test", + output: "npm/deno_run_no_ext.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(deno_run_bin_cjs { + args: "run -A --quiet npm:@denotest/bin/cli-cjs this is a test", + output: "npm/deno_run_cjs.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(deno_run_non_existent { + args: "run npm:mkdirp@0.5.125", + output: "npm/deno_run_non_existent.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 1, + }); + + itest!(builtin_module_module { + args: "run --allow-read --quiet npm/builtin_module_module/main.js", + output: "npm/builtin_module_module/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(node_modules_dir_require_added_node_modules_folder { + args: + "run --node-modules-dir -A --quiet $TESTDATA/npm/require_added_nm_folder/main.js", + output: "npm/require_added_nm_folder/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + exit_code: 0, + temp_cwd: true, +}); + + itest!(node_modules_dir_with_deps { + args: "run --allow-read --allow-env --node-modules-dir $TESTDATA/npm/cjs_with_deps/main.js", + output: "npm/cjs_with_deps/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + temp_cwd: true, +}); + + itest!(node_modules_dir_yargs { + args: "run --allow-read --allow-env --node-modules-dir $TESTDATA/npm/cjs_yargs/main.js", + output: "npm/cjs_yargs/main.out", + envs: env_vars_for_npm_tests(), + http_server: true, + temp_cwd: true, +}); + + #[test] + fn node_modules_dir_cache() { + let _server = http_server(); + + let deno_dir = util::new_deno_dir(); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(deno_dir.path()) + .arg("cache") + .arg("--node-modules-dir") + .arg("--quiet") + .arg(util::testdata_path().join("npm/dual_cjs_esm/main.ts")) + .envs(env_vars_for_npm_tests()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert!(output.status.success()); + + let node_modules = deno_dir.path().join("node_modules"); + assert!(node_modules + .join( + ".deno/@denotest+dual-cjs-esm@1.0.0/node_modules/@denotest/dual-cjs-esm" + ) + .exists()); + assert!(node_modules.join("@denotest/dual-cjs-esm").exists()); + + // now try deleting the folder with the package source in the npm cache dir + let package_global_cache_dir = deno_dir + .path() + .join("npm") + .join("localhost_4545") + .join("npm") + .join("registry") + .join("@denotest") + .join("dual-cjs-esm") + .join("1.0.0"); + assert!(package_global_cache_dir.exists()); + std::fs::remove_dir_all(&package_global_cache_dir).unwrap(); + + // run the output, and it shouldn't bother recreating the directory + // because it already has everything cached locally in the node_modules folder + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(deno_dir.path()) + .arg("run") + .arg("--node-modules-dir") + .arg("--quiet") + .arg("-A") + .arg(util::testdata_path().join("npm/dual_cjs_esm/main.ts")) + .envs(env_vars_for_npm_tests()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert!(output.status.success()); + + // this won't exist, but actually the parent directory + // will because it still re-downloads the registry information + assert!(!package_global_cache_dir.exists()); + } + + #[test] + fn ensure_registry_files_local() { + // ensures the registry files all point at local tarballs + let registry_dir_path = util::testdata_path().join("npm").join("registry"); + for entry in std::fs::read_dir(®istry_dir_path).unwrap() { + let entry = entry.unwrap(); + if entry.metadata().unwrap().is_dir() { + let registry_json_path = registry_dir_path + .join(entry.file_name()) + .join("registry.json"); + if registry_json_path.exists() { + let file_text = std::fs::read_to_string(®istry_json_path).unwrap(); + if file_text.contains("https://registry.npmjs.org/") { + panic!( + "file {} contained a reference to the npm registry", + registry_json_path.display(), + ); + } + } + } + } + } + + itest!(compile_errors { + args: "compile -A --quiet npm/cached_only/main.ts", + output_str: Some("error: npm specifiers have not yet been implemented for this sub command (https://github.com/denoland/deno/issues/15960). Found: npm:chalk@5\n"), + exit_code: 1, + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(bundle_errors { + args: "bundle --quiet npm/esm/main.js", + output_str: Some("error: npm specifiers have not yet been implemented for this sub command (https://github.com/denoland/deno/issues/15960). Found: npm:chalk@5\n"), + exit_code: 1, + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(info_chalk_display { + args: "info --quiet npm/cjs_with_deps/main.js", + output: "npm/cjs_with_deps/main_info.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(info_chalk_display_node_modules_dir { + args: "info --quiet --node-modules-dir $TESTDATA/npm/cjs_with_deps/main.js", + output: "npm/cjs_with_deps/main_info.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + temp_cwd: true, + }); + + itest!(info_chalk_json { + args: "info --quiet --json npm/cjs_with_deps/main.js", + output: "npm/cjs_with_deps/main_info_json.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(info_chalk_json_node_modules_dir { + args: + "info --quiet --node-modules-dir --json $TESTDATA/npm/cjs_with_deps/main.js", + output: "npm/cjs_with_deps/main_info_json.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + temp_cwd: true, + }); + + itest!(info_cli_chalk_display { + args: "info --quiet npm:chalk@4", + output: "npm/info/chalk.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(info_cli_chalk_json { + args: "info --quiet --json npm:chalk@4", + output: "npm/info/chalk_json.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + #[test] + fn lock_file_missing_top_level_package() { + let _server = http_server(); + + let deno_dir = util::new_deno_dir(); + let temp_dir = util::TempDir::new(); + + // write empty config file + temp_dir.write("deno.json", "{}"); + + // Lock file that is automatically picked up has been intentionally broken, + // by removing "cowsay" package from it. This test ensures that npm resolver + // snapshot can be successfully hydrated in such situation + let lock_file_content = r#"{ + "version": "2", + "remote": {}, + "npm": { + "specifiers": { "cowsay": "cowsay@1.5.0" }, + "packages": { + "ansi-regex@3.0.1": { + "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", + "dependencies": {} + }, + "ansi-regex@5.0.1": { + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dependencies": {} + }, + "ansi-styles@4.3.0": { + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { "color-convert": "color-convert@2.0.1" } + }, + "camelcase@5.3.1": { + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dependencies": {} + }, + "cliui@6.0.0": { + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "dependencies": { + "string-width": "string-width@4.2.3", + "strip-ansi": "strip-ansi@6.0.1", + "wrap-ansi": "wrap-ansi@6.2.0" + } + }, + "color-convert@2.0.1": { + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { "color-name": "color-name@1.1.4" } + }, + "color-name@1.1.4": { + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dependencies": {} + }, + "decamelize@1.2.0": { + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "dependencies": {} + }, + "emoji-regex@8.0.0": { + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dependencies": {} + }, + "find-up@4.1.0": { + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dependencies": { + "locate-path": "locate-path@5.0.0", + "path-exists": "path-exists@4.0.0" + } + }, + "get-caller-file@2.0.5": { + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dependencies": {} + }, + "get-stdin@8.0.0": { + "integrity": "sha512-sY22aA6xchAzprjyqmSEQv4UbAAzRN0L2dQB0NlN5acTTK9Don6nhoc3eAbUnpZiCANAMfd/+40kVdKfFygohg==", + "dependencies": {} + }, + "is-fullwidth-code-point@2.0.0": { + "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "dependencies": {} + }, + "is-fullwidth-code-point@3.0.0": { + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dependencies": {} + }, + "locate-path@5.0.0": { + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dependencies": { "p-locate": "p-locate@4.1.0" } + }, + "p-limit@2.3.0": { + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dependencies": { "p-try": "p-try@2.2.0" } + }, + "p-locate@4.1.0": { + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dependencies": { "p-limit": "p-limit@2.3.0" } + }, + "p-try@2.2.0": { + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dependencies": {} + }, + "path-exists@4.0.0": { + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dependencies": {} + }, + "require-directory@2.1.1": { + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dependencies": {} + }, + "require-main-filename@2.0.0": { + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dependencies": {} + }, + "set-blocking@2.0.0": { + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "dependencies": {} + }, + "string-width@2.1.1": { + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "dependencies": { + "is-fullwidth-code-point": "is-fullwidth-code-point@2.0.0", + "strip-ansi": "strip-ansi@4.0.0" + } + }, + "string-width@4.2.3": { + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "emoji-regex@8.0.0", + "is-fullwidth-code-point": "is-fullwidth-code-point@3.0.0", + "strip-ansi": "strip-ansi@6.0.1" + } + }, + "strip-ansi@4.0.0": { + "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==", + "dependencies": { "ansi-regex": "ansi-regex@3.0.1" } + }, + "strip-ansi@6.0.1": { + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { "ansi-regex": "ansi-regex@5.0.1" } + }, + "strip-final-newline@2.0.0": { + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dependencies": {} + }, + "which-module@2.0.0": { + "integrity": "sha512-B+enWhmw6cjfVC7kS8Pj9pCrKSc5txArRyaYGe088shv/FGWH+0Rjx/xPgtsWfsUtS27FkP697E4DDhgrgoc0Q==", + "dependencies": {} + }, + "wrap-ansi@6.2.0": { + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dependencies": { + "ansi-styles": "ansi-styles@4.3.0", + "string-width": "string-width@4.2.3", + "strip-ansi": "strip-ansi@6.0.1" + } + }, + "y18n@4.0.3": { + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "dependencies": {} + }, + "yargs-parser@18.1.3": { + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "dependencies": { + "camelcase": "camelcase@5.3.1", + "decamelize": "decamelize@1.2.0" + } + }, + "yargs@15.4.1": { + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "dependencies": { + "cliui": "cliui@6.0.0", + "decamelize": "decamelize@1.2.0", + "find-up": "find-up@4.1.0", + "get-caller-file": "get-caller-file@2.0.5", + "require-directory": "require-directory@2.1.1", + "require-main-filename": "require-main-filename@2.0.0", + "set-blocking": "set-blocking@2.0.0", + "string-width": "string-width@4.2.3", + "which-module": "which-module@2.0.0", + "y18n": "y18n@4.0.3", + "yargs-parser": "yargs-parser@18.1.3" + } + } + } + } + } + "#; + temp_dir.write("deno.lock", lock_file_content); + let main_contents = r#" + import cowsay from "npm:cowsay"; + console.log(cowsay); + "#; + temp_dir.write("main.ts", main_contents); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(temp_dir.path()) + .arg("run") + .arg("--quiet") + .arg("--lock") + .arg("deno.lock") + .arg("-A") + .arg("main.ts") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert!(!output.status.success()); + + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!( + stderr, + "error: failed reading lockfile 'deno.lock'\n\nCaused by:\n the lockfile is corrupt. You can recreate it with --lock-write\n" + ); + } + + #[test] + fn lock_file_lock_write() { + // https://github.com/denoland/deno/issues/16666 + // Ensure that --lock-write still adds npm packages to the lockfile + let _server = http_server(); + + let deno_dir = util::new_deno_dir(); + let temp_dir = util::TempDir::new(); + + // write empty config file + temp_dir.write("deno.json", "{}"); + + // write a lock file with borked integrity + let lock_file_content = r#"{ + "version": "2", + "remote": {}, + "npm": { + "specifiers": { "cowsay@1.5.0": "cowsay@1.5.0" }, + "packages": { + "ansi-regex@3.0.1": { + "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", + "dependencies": {} + }, + "ansi-regex@5.0.1": { + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dependencies": {} + }, + "ansi-styles@4.3.0": { + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { "color-convert": "color-convert@2.0.1" } + }, + "camelcase@5.3.1": { + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dependencies": {} + }, + "cliui@6.0.0": { + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "dependencies": { + "string-width": "string-width@4.2.3", + "strip-ansi": "strip-ansi@6.0.1", + "wrap-ansi": "wrap-ansi@6.2.0" + } + }, + "color-convert@2.0.1": { + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { "color-name": "color-name@1.1.4" } + }, + "color-name@1.1.4": { + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dependencies": {} + }, + "cowsay@1.5.0": { + "integrity": "sha512-8Ipzr54Z8zROr/62C8f0PdhQcDusS05gKTS87xxdji8VbWefWly0k8BwGK7+VqamOrkv3eGsCkPtvlHzrhWsCA==", + "dependencies": { + "get-stdin": "get-stdin@8.0.0", + "string-width": "string-width@2.1.1", + "strip-final-newline": "strip-final-newline@2.0.0", + "yargs": "yargs@15.4.1" + } + }, + "decamelize@1.2.0": { + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "dependencies": {} + }, + "emoji-regex@8.0.0": { + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dependencies": {} + }, + "find-up@4.1.0": { + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dependencies": { + "locate-path": "locate-path@5.0.0", + "path-exists": "path-exists@4.0.0" + } + }, + "get-caller-file@2.0.5": { + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dependencies": {} + }, + "get-stdin@8.0.0": { + "integrity": "sha512-sY22aA6xchAzprjyqmSEQv4UbAAzRN0L2dQB0NlN5acTTK9Don6nhoc3eAbUnpZiCANAMfd/+40kVdKfFygohg==", + "dependencies": {} + }, + "is-fullwidth-code-point@2.0.0": { + "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "dependencies": {} + }, + "is-fullwidth-code-point@3.0.0": { + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dependencies": {} + }, + "locate-path@5.0.0": { + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dependencies": { "p-locate": "p-locate@4.1.0" } + }, + "p-limit@2.3.0": { + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dependencies": { "p-try": "p-try@2.2.0" } + }, + "p-locate@4.1.0": { + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dependencies": { "p-limit": "p-limit@2.3.0" } + }, + "p-try@2.2.0": { + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dependencies": {} + }, + "path-exists@4.0.0": { + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dependencies": {} + }, + "require-directory@2.1.1": { + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dependencies": {} + }, + "require-main-filename@2.0.0": { + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dependencies": {} + }, + "set-blocking@2.0.0": { + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "dependencies": {} + }, + "string-width@2.1.1": { + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "dependencies": { + "is-fullwidth-code-point": "is-fullwidth-code-point@2.0.0", + "strip-ansi": "strip-ansi@4.0.0" + } + }, + "string-width@4.2.3": { + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "emoji-regex@8.0.0", + "is-fullwidth-code-point": "is-fullwidth-code-point@3.0.0", + "strip-ansi": "strip-ansi@6.0.1" + } + }, + "strip-ansi@4.0.0": { + "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==", + "dependencies": { "ansi-regex": "ansi-regex@3.0.1" } + }, + "strip-ansi@6.0.1": { + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { "ansi-regex": "ansi-regex@5.0.1" } + }, + "strip-final-newline@2.0.0": { + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dependencies": {} + }, + "which-module@2.0.0": { + "integrity": "sha512-B+enWhmw6cjfVC7kS8Pj9pCrKSc5txArRyaYGe088shv/FGWH+0Rjx/xPgtsWfsUtS27FkP697E4DDhgrgoc0Q==", + "dependencies": {} + }, + "wrap-ansi@6.2.0": { + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dependencies": { + "ansi-styles": "ansi-styles@4.3.0", + "string-width": "string-width@4.2.3", + "strip-ansi": "strip-ansi@6.0.1" + } + }, + "y18n@4.0.3": { + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "dependencies": {} + }, + "yargs-parser@18.1.3": { + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "dependencies": { + "camelcase": "camelcase@5.3.1", + "decamelize": "decamelize@1.2.0" + } + }, + "yargs@15.4.1": { + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "dependencies": { + "cliui": "cliui@6.0.0", + "decamelize": "decamelize@1.2.0", + "find-up": "find-up@4.1.0", + "get-caller-file": "get-caller-file@2.0.5", + "require-directory": "require-directory@2.1.1", + "require-main-filename": "require-main-filename@2.0.0", + "set-blocking": "set-blocking@2.0.0", + "string-width": "string-width@4.2.3", + "which-module": "which-module@2.0.0", + "y18n": "y18n@4.0.3", + "yargs-parser": "yargs-parser@18.1.3" + } + } + } + } +} +"#; + temp_dir.write("deno.lock", lock_file_content); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(temp_dir.path()) + .arg("cache") + .arg("--lock-write") + .arg("--quiet") + .arg("npm:cowsay@1.5.0") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert!(output.status.success()); + assert_eq!(output.status.code(), Some(0)); + + let stdout = String::from_utf8(output.stdout).unwrap(); + assert!(stdout.is_empty()); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stderr.is_empty()); + assert_eq!( + lock_file_content, + std::fs::read_to_string(temp_dir.path().join("deno.lock")).unwrap() + ); + } + + #[test] + fn auto_discover_lock_file() { + let _server = http_server(); + + let deno_dir = util::new_deno_dir(); + let temp_dir = util::TempDir::new(); + + // write empty config file + temp_dir.write("deno.json", "{}"); + + // write a lock file with borked integrity + let lock_file_content = r#"{ + "version": "2", + "remote": {}, + "npm": { + "specifiers": { "@denotest/bin": "@denotest/bin@1.0.0" }, + "packages": { + "@denotest/bin@1.0.0": { + "integrity": "sha512-foobar", + "dependencies": {} + } + } + } + }"#; + temp_dir.write("deno.lock", lock_file_content); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(temp_dir.path()) + .arg("run") + .arg("--unstable") + .arg("-A") + .arg("npm:@denotest/bin/cli-esm") + .arg("test") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert!(!output.status.success()); + assert_eq!(output.status.code(), Some(10)); + + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stderr.contains( + "Integrity check failed for npm package: \"@denotest/bin@1.0.0\"" + )); + } + + #[test] + fn peer_deps_with_copied_folders_and_lockfile() { + let _server = http_server(); + + let deno_dir = util::new_deno_dir(); + let temp_dir = util::TempDir::new(); + + // write empty config file + temp_dir.write("deno.json", "{}"); + let test_folder_path = test_util::testdata_path() + .join("npm") + .join("peer_deps_with_copied_folders"); + let main_contents = + std::fs::read_to_string(test_folder_path.join("main.ts")).unwrap(); + temp_dir.write("./main.ts", main_contents); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(temp_dir.path()) + .arg("run") + .arg("-A") + .arg("main.ts") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert!(output.status.success()); + + let expected_output = + std::fs::read_to_string(test_folder_path.join("main.out")).unwrap(); + + assert_eq!(String::from_utf8(output.stderr).unwrap(), expected_output); + + assert!(temp_dir.path().join("deno.lock").exists()); + let grandchild_path = deno_dir + .path() + .join("npm") + .join("localhost_4545") + .join("npm") + .join("registry") + .join("@denotest") + .join("peer-dep-test-grandchild"); + assert!(grandchild_path.join("1.0.0").exists()); + assert!(grandchild_path.join("1.0.0_1").exists()); // copy folder, which is hardlinked + + // run again + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(temp_dir.path()) + .arg("run") + .arg("-A") + .arg("main.ts") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!(String::from_utf8(output.stderr).unwrap(), "1\n2\n"); + assert!(output.status.success()); + + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(temp_dir.path()) + .arg("run") + .arg("--reload") + .arg("-A") + .arg("main.ts") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!(String::from_utf8(output.stderr).unwrap(), expected_output); + assert!(output.status.success()); + + // now run with local node modules + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(temp_dir.path()) + .arg("run") + .arg("--node-modules-dir") + .arg("-A") + .arg("main.ts") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!(String::from_utf8(output.stderr).unwrap(), "1\n2\n"); + assert!(output.status.success()); + + let deno_folder = temp_dir.path().join("node_modules").join(".deno"); + assert!(deno_folder + .join("@denotest+peer-dep-test-grandchild@1.0.0") + .exists()); + assert!(deno_folder + .join("@denotest+peer-dep-test-grandchild@1.0.0_1") + .exists()); // copy folder + + // now again run with local node modules + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(temp_dir.path()) + .arg("run") + .arg("--node-modules-dir") + .arg("-A") + .arg("main.ts") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert!(output.status.success()); + assert_eq!(String::from_utf8(output.stderr).unwrap(), "1\n2\n"); + + // now ensure it works with reloading + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(temp_dir.path()) + .arg("run") + .arg("--node-modules-dir") + .arg("--reload") + .arg("-A") + .arg("main.ts") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert!(output.status.success()); + assert_eq!(String::from_utf8(output.stderr).unwrap(), expected_output); + + // now ensure it works with reloading and no lockfile + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(temp_dir.path()) + .arg("run") + .arg("--node-modules-dir") + .arg("--no-lock") + .arg("--reload") + .arg("-A") + .arg("main.ts") + .envs(env_vars_for_npm_tests()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!(String::from_utf8(output.stderr).unwrap(), expected_output,); + assert!(output.status.success()); + } + + itest!(info_peer_deps { + args: "info --quiet npm/peer_deps_with_copied_folders/main.ts", + output: "npm/peer_deps_with_copied_folders/main_info.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(info_peer_deps_json { + args: "info --quiet --json npm/peer_deps_with_copied_folders/main.ts", + output: "npm/peer_deps_with_copied_folders/main_info_json.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + }); + + itest!(create_require { + args: "run --reload --allow-read npm/create_require/main.ts", + output: "npm/create_require/main.out", + exit_code: 0, + envs: env_vars_for_npm_tests(), + http_server: true, + }); +} diff --git a/cli/tests/repl_tests.rs b/cli/tests/repl_tests.rs new file mode 100644 index 0000000000..4524b40972 --- /dev/null +++ b/cli/tests/repl_tests.rs @@ -0,0 +1,900 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +use test_util as util; +use test_util::assert_contains; +use test_util::assert_ends_with; +use test_util::assert_not_contains; + +mod repl { + use super::*; + + #[test] + fn pty_multiline() { + util::with_pty(&["repl"], |mut console| { + console.write_line("(\n1 + 2\n)"); + console.write_line("{\nfoo: \"foo\"\n}"); + console.write_line("`\nfoo\n`"); + console.write_line("`\n\\`\n`"); + console.write_line("'{'"); + console.write_line("'('"); + console.write_line("'['"); + console.write_line("/{/"); + console.write_line("/\\(/"); + console.write_line("/\\[/"); + console.write_line("console.log(\"{test1} abc {test2} def {{test3}}\".match(/{([^{].+?)}/));"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_contains!(output, '3'); + assert_contains!(output, "{ foo: \"foo\" }"); + assert_contains!(output, "\"\\nfoo\\n\""); + assert_contains!(output, "\"\\n`\\n\""); + assert_contains!(output, "\"{\""); + assert_contains!(output, "\"(\""); + assert_contains!(output, "\"[\""); + assert_contains!(output, "/{/"); + assert_contains!(output, "/\\(/"); + assert_contains!(output, "/\\[/"); + assert_contains!(output, "[ \"{test1}\", \"test1\" ]"); + }); + } + + #[test] + fn pty_null() { + util::with_pty(&["repl"], |mut console| { + console.write_line("null"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_contains!(output, "null"); + }); + } + + #[test] + fn pty_unpaired_braces() { + util::with_pty(&["repl"], |mut console| { + console.write_line(")"); + console.write_line("]"); + console.write_line("}"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_contains!(output, "Unexpected token `)`"); + assert_contains!(output, "Unexpected token `]`"); + assert_contains!(output, "Unexpected token `}`"); + }); + } + + #[test] + fn pty_bad_input() { + util::with_pty(&["repl"], |mut console| { + console.write_line("'\\u{1f3b5}'[0]"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_contains!(output, "Unterminated string literal"); + }); + } + + #[test] + fn pty_syntax_error_input() { + util::with_pty(&["repl"], |mut console| { + console.write_line("('\\u')"); + console.write_line("'"); + console.write_line("[{'a'}];"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_contains!( + output, + "Bad character escape sequence, expected 4 hex characters" + ); + assert_contains!(output, "Unterminated string constant"); + assert_contains!(output, "Expected a semicolon"); + }); + } + + #[test] + fn pty_complete_symbol() { + util::with_pty(&["repl"], |mut console| { + console.write_line("Symbol.it\t"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_contains!(output, "Symbol(Symbol.iterator)"); + }); + } + + #[test] + fn pty_complete_declarations() { + util::with_pty(&["repl"], |mut console| { + console.write_line("class MyClass {}"); + console.write_line("My\t"); + console.write_line("let myVar;"); + console.write_line("myV\t"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_contains!(output, "> MyClass"); + assert_contains!(output, "> myVar"); + }); + } + + #[test] + fn pty_complete_primitives() { + util::with_pty(&["repl"], |mut console| { + console.write_line("let func = function test(){}"); + console.write_line("func.appl\t"); + console.write_line("let str = ''"); + console.write_line("str.leng\t"); + console.write_line("false.valueO\t"); + console.write_line("5n.valueO\t"); + console.write_line("let num = 5"); + console.write_line("num.toStrin\t"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_contains!(output, "> func.apply"); + assert_contains!(output, "> str.length"); + assert_contains!(output, "> 5n.valueOf"); + assert_contains!(output, "> false.valueOf"); + assert_contains!(output, "> num.toString"); + }); + } + + #[test] + fn pty_complete_expression() { + util::with_pty(&["repl"], |mut console| { + console.write_text("Deno.\t\t"); + console.write_text("y"); + console.write_line(""); + console.write_line("close();"); + let output = console.read_all_output(); + assert_contains!(output, "Display all"); + assert_contains!(output, "core"); + assert_contains!(output, "args"); + assert_contains!(output, "exit"); + assert_contains!(output, "symlink"); + assert_contains!(output, "permissions"); + }); + } + + #[test] + fn pty_complete_imports() { + util::with_pty(&["repl"], |mut console| { + // single quotes + console.write_line("import './run/001_hel\t'"); + // double quotes + console.write_line("import { output } from \"./run/045_out\t\""); + console.write_line("output('testing output');"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_contains!(output, "Hello World"); + assert_contains!( + output, + // on windows, could any (it's flaky) + "\ntesting output", + "testing output\u{1b}", + "\r\n\u{1b}[?25htesting output", + ); + }); + + // ensure when the directory changes that the suggestions come from the cwd + util::with_pty(&["repl"], |mut console| { + console.write_line("Deno.chdir('./subdir');"); + console.write_line("import '../run/001_hel\t'"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_contains!(output, "Hello World"); + }); + } + + #[test] + fn pty_complete_imports_no_panic_empty_specifier() { + // does not panic when tabbing when empty + util::with_pty(&["repl"], |mut console| { + console.write_line("import '\t';"); + console.write_line("close();"); + }); + } + + #[test] + fn pty_ignore_symbols() { + util::with_pty(&["repl"], |mut console| { + console.write_line("Array.Symbol\t"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_contains!(output, "undefined"); + assert_not_contains!( + output, + "Uncaught TypeError: Array.Symbol is not a function" + ); + }); + } + + #[test] + fn pty_assign_global_this() { + util::with_pty(&["repl"], |mut console| { + console.write_line("globalThis = 42;"); + console.write_line("close();"); + + let output = console.read_all_output(); + assert_not_contains!(output, "panicked"); + }); + } + + #[test] + fn pty_emoji() { + // windows was having issues displaying this + util::with_pty(&["repl"], |mut console| { + console.write_line(r#"console.log('\u{1F995}');"#); + console.write_line("close();"); + + let output = console.read_all_output(); + // only one for the output (since input is escaped) + let emoji_count = output.chars().filter(|c| *c == '🦕').count(); + assert_eq!(emoji_count, 1); + }); + } + + #[test] + fn console_log() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["console.log('hello')", "'world'"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "hello\nundefined\n\"world\"\n"); + assert!(err.is_empty()); + } + + #[test] + fn object_literal() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["{}", "{ foo: 'bar' }"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "{}\n{ foo: \"bar\" }\n"); + assert!(err.is_empty()); + } + + #[test] + fn block_expression() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["{};", "{\"\"}"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "undefined\n\"\"\n"); + assert!(err.is_empty()); + } + + #[test] + fn await_resolve() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["await Promise.resolve('done')"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "\"done\"\n"); + assert!(err.is_empty()); + } + + #[test] + fn await_timeout() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["await new Promise((r) => setTimeout(r, 0, 'done'))"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "\"done\"\n"); + assert!(err.is_empty()); + } + + #[test] + fn let_redeclaration() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["let foo = 0;", "foo", "let foo = 1;", "foo"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "undefined\n0\nundefined\n1\n"); + assert!(err.is_empty()); + } + + #[test] + fn repl_cwd() { + let (_out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["Deno.cwd()"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert!(err.is_empty()); + } + + #[test] + fn typescript() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec![ + "function add(a: number, b: number) { return a + b }", + "const result: number = add(1, 2) as number;", + "result", + ]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "undefined\nundefined\n3\n"); + assert!(err.is_empty()); + } + + #[test] + fn typescript_declarations() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec![ + "namespace Test { export enum Values { A, B, C } }", + "Test.Values.A", + "Test.Values.C", + "interface MyInterface { prop: string; }", + "type MyTypeAlias = string;", + ]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + let expected_end_text = "undefined\n0\n2\nundefined\nundefined\n"; + assert_ends_with!(out, expected_end_text); + assert!(err.is_empty()); + } + + #[test] + fn typescript_decorators() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec![ + "function dec(target) { target.prototype.test = () => 2; }", + "@dec class Test {}", + "new Test().test()", + ]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "undefined\n[Function: Test]\n2\n"); + assert!(err.is_empty()); + } + + #[test] + fn eof() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["1 + 2"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "3\n"); + assert!(err.is_empty()); + } + + #[test] + fn strict() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec![ + "let a = {};", + "Object.preventExtensions(a);", + "a.c = 1;", + ]), + None, + false, + ); + assert_contains!( + out, + "Uncaught TypeError: Cannot add property c, object is not extensible" + ); + assert!(err.is_empty()); + } + + #[test] + fn close_command() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["close()", "'ignored'"]), + None, + false, + ); + + assert_not_contains!(out, "ignored"); + assert!(err.is_empty()); + } + + #[test] + fn function() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["Deno.writeFileSync"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "[Function: writeFileSync]\n"); + assert!(err.is_empty()); + } + + #[test] + #[ignore] + fn multiline() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["(\n1 + 2\n)"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "3\n"); + assert!(err.is_empty()); + } + + #[test] + fn import() { + let (out, _) = util::run_and_collect_output_with_args( + true, + vec![], + Some(vec!["import('./subdir/auto_print_hello.ts')"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_contains!(out, "hello!\n"); + } + + #[test] + fn import_declarations() { + let (out, _) = util::run_and_collect_output_with_args( + true, + vec!["repl", "--allow-read"], + Some(vec!["import './subdir/auto_print_hello.ts';"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_contains!(out, "hello!\n"); + } + + #[test] + fn exports_stripped() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["export default 5;", "export class Test {}"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_contains!(out, "5\n"); + assert!(err.is_empty()); + } + + #[test] + fn call_eval_unterminated() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["eval('{')"]), + None, + false, + ); + assert_contains!(out, "Unexpected end of input"); + assert!(err.is_empty()); + } + + #[test] + fn unpaired_braces() { + for right_brace in &[")", "]", "}"] { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec![right_brace]), + None, + false, + ); + assert_contains!(out, "Unexpected token"); + assert!(err.is_empty()); + } + } + + #[test] + fn reference_error() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["not_a_variable"]), + None, + false, + ); + assert_contains!(out, "not_a_variable is not defined"); + assert!(err.is_empty()); + } + + #[test] + fn syntax_error() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec![ + "syntax error", + "2", // ensure it keeps accepting input after + ]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!( + out, + "parse error: Expected ';', '}' or at 1:8\n2\n" + ); + assert!(err.is_empty()); + } + + #[test] + fn syntax_error_jsx() { + // JSX is not supported in the REPL + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["const element =
;"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_contains!(out, "Unexpected token `>`"); + assert!(err.is_empty()); + } + + #[test] + fn type_error() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["console()"]), + None, + false, + ); + assert_contains!(out, "console is not a function"); + assert!(err.is_empty()); + } + + #[test] + fn variable() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["var a = 123;", "a"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "undefined\n123\n"); + assert!(err.is_empty()); + } + + #[test] + fn lexical_scoped_variable() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["let a = 123;", "a"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "undefined\n123\n"); + assert!(err.is_empty()); + } + + #[test] + fn missing_deno_dir() { + use std::fs::{read_dir, remove_dir_all}; + const DENO_DIR: &str = "nonexistent"; + let test_deno_dir = test_util::testdata_path().join(DENO_DIR); + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["1"]), + Some(vec![ + ("DENO_DIR".to_owned(), DENO_DIR.to_owned()), + ("NO_COLOR".to_owned(), "1".to_owned()), + ]), + false, + ); + assert!(read_dir(&test_deno_dir).is_ok()); + remove_dir_all(&test_deno_dir).unwrap(); + assert_ends_with!(out, "1\n"); + assert!(err.is_empty()); + } + + #[test] + fn save_last_eval() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["1", "_"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "1\n1\n"); + assert!(err.is_empty()); + } + + #[test] + fn save_last_thrown() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["throw 1", "_error"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!(out, "Uncaught 1\n1\n"); + assert!(err.is_empty()); + } + + #[test] + fn assign_underscore() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["_ = 1", "2", "_"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert_ends_with!( + out, + "Last evaluation result is no longer saved to _.\n1\n2\n1\n" + ); + assert!(err.is_empty()); + } + + #[test] + fn assign_underscore_error() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["_error = 1", "throw 2", "_error"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + println!("{}", out); + assert_ends_with!( + out, + "Last thrown error is no longer saved to _error.\n1\nUncaught 2\n1\n" + ); + assert!(err.is_empty()); + } + + #[test] + fn custom_inspect() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec![ + r#"const o = { + [Symbol.for("Deno.customInspect")]() { + throw new Error('Oops custom inspect error'); + }, + };"#, + "o", + ]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + + assert_contains!(out, "Oops custom inspect error"); + assert!(err.is_empty()); + } + + #[test] + fn eval_flag_valid_input() { + let (out, err) = util::run_and_collect_output_with_args( + true, + vec!["repl", "--eval", "const t = 10;"], + Some(vec!["t * 500;"]), + None, + false, + ); + assert_contains!(out, "5000"); + assert!(err.is_empty()); + } + + #[test] + fn eval_flag_parse_error() { + let (out, err) = util::run_and_collect_output_with_args( + true, + vec!["repl", "--eval", "const %"], + Some(vec!["250 * 10"]), + None, + false, + ); + assert_contains!( + test_util::strip_ansi_codes(&out), + "Error in --eval flag: parse error: Unexpected token `%`." + ); + assert_contains!(out, "2500"); // should not prevent input + assert!(err.is_empty()); + } + + #[test] + fn eval_flag_runtime_error() { + let (out, err) = util::run_and_collect_output_with_args( + true, + vec!["repl", "--eval", "throw new Error('Testing')"], + Some(vec!["250 * 10"]), + None, + false, + ); + assert_contains!(out, "Error in --eval flag: Uncaught Error: Testing"); + assert_contains!(out, "2500"); // should not prevent input + assert!(err.is_empty()); + } + + #[test] + fn eval_file_flag_valid_input() { + let (out, err) = util::run_and_collect_output_with_args( + true, + vec!["repl", "--eval-file=./run/001_hello.js"], + None, + None, + false, + ); + assert_contains!(out, "Hello World"); + assert!(err.is_empty()); + } + + #[test] + fn eval_file_flag_call_defined_function() { + let (out, err) = util::run_and_collect_output_with_args( + true, + vec!["repl", "--eval-file=./tsc/d.ts"], + Some(vec!["v4()"]), + None, + false, + ); + assert_contains!(out, "hello"); + assert!(err.is_empty()); + } + + #[test] + fn eval_file_flag_http_input() { + let (out, err) = util::run_and_collect_output_with_args( + true, + vec!["repl", "--eval-file=http://127.0.0.1:4545/tsc/d.ts"], + Some(vec!["v4()"]), + None, + true, + ); + assert_contains!(out, "hello"); + assert!(err.contains("Download")); + } + + #[test] + fn eval_file_flag_multiple_files() { + let (out, err) = util::run_and_collect_output_with_args( + true, + vec!["repl", "--allow-read", "--eval-file=http://127.0.0.1:4545/repl/import_type.ts,./tsc/d.ts,http://127.0.0.1:4545/type_definitions/foo.js"], + Some(vec!["b.method1=v4", "b.method1()+foo.toUpperCase()"]), + None, + true, + ); + assert_contains!(out, "helloFOO"); + assert_contains!(err, "Download"); + } + + #[test] + fn pty_clear_function() { + util::with_pty(&["repl"], |mut console| { + console.write_line("console.log('hello');"); + console.write_line("clear();"); + console.write_line("const clear = 1234 + 2000;"); + console.write_line("clear;"); + console.write_line("close();"); + + let output = console.read_all_output(); + if cfg!(windows) { + // Windows will overwrite what's in the console buffer before + // we read from it. It contains this string repeated many times + // to clear the screen. + assert_contains!(output, "\r\n\u{1b}[K\r\n\u{1b}[K\r\n\u{1b}[K"); + } else { + assert_contains!(output, "hello"); + assert_contains!(output, "[1;1H"); + } + assert_contains!(output, "undefined"); + assert_contains!(output, "const clear = 1234 + 2000;"); + assert_contains!(output, "3234"); + }); + } + + #[test] + fn pty_tab_handler() { + // If the last character is **not** whitespace, we show the completions + util::with_pty(&["repl"], |mut console| { + console.write_line("a\t\t"); + console.write_line("close();"); + let output = console.read_all_output(); + assert_contains!(output, "addEventListener"); + assert_contains!(output, "alert"); + assert_contains!(output, "atob"); + }); + // If the last character is whitespace, we just insert a tab + util::with_pty(&["repl"], |mut console| { + console.write_line("a; \t\t"); // last character is whitespace + console.write_line("close();"); + let output = console.read_all_output(); + assert_not_contains!(output, "addEventListener"); + assert_not_contains!(output, "alert"); + assert_not_contains!(output, "atob"); + }); + } + + #[test] + fn repl_report_error() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec![ + r#"console.log(1); reportError(new Error("foo")); console.log(2);"#, + ]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + + // TODO(nayeemrmn): The REPL should report event errors and rejections. + assert_contains!(out, "1\n2\nundefined\n"); + assert!(err.is_empty()); + } + + #[test] + fn pty_aggregate_error() { + let (out, err) = util::run_and_collect_output( + true, + "repl", + Some(vec!["await Promise.any([])"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + + assert_contains!(out, "AggregateError"); + assert!(err.is_empty()); + } + + #[test] + fn repl_with_quiet_flag() { + let (out, err) = util::run_and_collect_output_with_args( + true, + vec!["repl", "--quiet"], + Some(vec!["await Promise.resolve('done')"]), + Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), + false, + ); + assert!(!out.contains("Deno")); + assert!(!out.contains("exit using ctrl+d, ctrl+c, or close()")); + assert_ends_with!(out, "\"done\"\n"); + assert!(err.is_empty()); + } +} diff --git a/cli/tests/run_tests.rs b/cli/tests/run_tests.rs new file mode 100644 index 0000000000..db6e6f685c --- /dev/null +++ b/cli/tests/run_tests.rs @@ -0,0 +1,3681 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; +use deno_core::url; +use deno_runtime::deno_fetch::reqwest; +use std::io::Read; +use std::io::Write; +use std::process::Command; +use std::process::Stdio; +use test_util as util; +use test_util::TempDir; +use tokio::task::LocalSet; +use trust_dns_client::serialize::txt::Lexer; +use trust_dns_client::serialize::txt::Parser; +use util::assert_contains; + +mod run { + use super::*; + + itest!(stdout_write_all { + args: "run --quiet run/stdout_write_all.ts", + output: "run/stdout_write_all.out", + }); + + itest!(stdin_read_all { + args: "run --quiet run/stdin_read_all.ts", + output: "run/stdin_read_all.out", + input: Some("01234567890123456789012345678901234567890123456789"), + }); + + itest!(stdout_write_sync_async { + args: "run --quiet run/stdout_write_sync_async.ts", + output: "run/stdout_write_sync_async.out", + }); + + itest!(_001_hello { + args: "run --reload run/001_hello.js", + output: "run/001_hello.js.out", + }); + + itest!(_002_hello { + args: "run --quiet --reload run/002_hello.ts", + output: "run/002_hello.ts.out", + }); + + itest!(_003_relative_import { + args: "run --quiet --reload run/003_relative_import.ts", + output: "run/003_relative_import.ts.out", + }); + + itest!(_004_set_timeout { + args: "run --quiet --reload run/004_set_timeout.ts", + output: "run/004_set_timeout.ts.out", + }); + + itest!(_005_more_imports { + args: "run --quiet --reload run/005_more_imports.ts", + output: "run/005_more_imports.ts.out", + }); + + itest!(_006_url_imports { + args: "run --quiet --reload run/006_url_imports.ts", + output: "run/006_url_imports.ts.out", + http_server: true, + }); + + itest!(_012_async { + args: "run --quiet --reload run/012_async.ts", + output: "run/012_async.ts.out", + }); + + itest!(_013_dynamic_import { + args: "run --quiet --reload --allow-read run/013_dynamic_import.ts", + output: "run/013_dynamic_import.ts.out", + }); + + itest!(_014_duplicate_import { + args: "run --quiet --reload --allow-read run/014_duplicate_import.ts ", + output: "run/014_duplicate_import.ts.out", + }); + + itest!(_015_duplicate_parallel_import { + args: + "run --quiet --reload --allow-read run/015_duplicate_parallel_import.js", + output: "run/015_duplicate_parallel_import.js.out", + }); + + itest!(_016_double_await { + args: "run --quiet --allow-read --reload run/016_double_await.ts", + output: "run/016_double_await.ts.out", + }); + + itest!(_017_import_redirect { + args: "run --quiet --reload run/017_import_redirect.ts", + output: "run/017_import_redirect.ts.out", + }); + + itest!(_017_import_redirect_nocheck { + args: "run --quiet --reload --no-check run/017_import_redirect.ts", + output: "run/017_import_redirect.ts.out", + }); + + itest!(_017_import_redirect_info { + args: "info --quiet --reload run/017_import_redirect.ts", + output: "run/017_import_redirect_info.out", + }); + + itest!(_018_async_catch { + args: "run --quiet --reload run/018_async_catch.ts", + output: "run/018_async_catch.ts.out", + }); + + itest!(_019_media_types { + args: "run --reload run/019_media_types.ts", + output: "run/019_media_types.ts.out", + http_server: true, + }); + + itest!(_020_json_modules { + args: "run --reload run/020_json_modules.ts", + output: "run/020_json_modules.ts.out", + exit_code: 1, + }); + + itest!(_021_mjs_modules { + args: "run --quiet --reload run/021_mjs_modules.ts", + output: "run/021_mjs_modules.ts.out", + }); + + itest!(_023_no_ext { + args: "run --reload --check run/023_no_ext", + output: "run/023_no_ext.out", + }); + + // TODO(lucacasonato): remove --unstable when permissions goes stable + itest!(_025_hrtime { + args: "run --quiet --allow-hrtime --unstable --reload run/025_hrtime.ts", + output: "run/025_hrtime.ts.out", + }); + + itest!(_025_reload_js_type_error { + args: "run --quiet --reload run/025_reload_js_type_error.js", + output: "run/025_reload_js_type_error.js.out", + }); + + itest!(_026_redirect_javascript { + args: "run --quiet --reload run/026_redirect_javascript.js", + output: "run/026_redirect_javascript.js.out", + http_server: true, + }); + + itest!(_027_redirect_typescript { + args: "run --quiet --reload run/027_redirect_typescript.ts", + output: "run/027_redirect_typescript.ts.out", + http_server: true, + }); + + itest!(_028_args { + args: + "run --quiet --reload run/028_args.ts --arg1 val1 --arg2=val2 -- arg3 arg4", + output: "run/028_args.ts.out", +}); + + itest!(_033_import_map { + args: + "run --quiet --reload --import-map=import_maps/import_map.json import_maps/test.ts", + output: "run/033_import_map.out", +}); + + itest!(_033_import_map_remote { + args: + "run --quiet --reload --import-map=http://127.0.0.1:4545/import_maps/import_map_remote.json --unstable import_maps/test_remote.ts", + output: "run/033_import_map_remote.out", + http_server: true, +}); + + itest!(onload { + args: "run --quiet --reload run/onload/main.ts", + output: "run/onload/main.out", + }); + + itest!(_035_cached_only_flag { + args: "run --reload --check --cached-only http://127.0.0.1:4545/run/019_media_types.ts", + output: "run/035_cached_only_flag.out", + exit_code: 1, + http_server: true, +}); + + itest!(_038_checkjs { + // checking if JS file is run through TS compiler + args: + "run --reload --config run/checkjs.tsconfig.json --check run/038_checkjs.js", + exit_code: 1, + output: "run/038_checkjs.js.out", +}); + + itest!(_042_dyn_import_evalcontext { + args: "run --quiet --allow-read --reload run/042_dyn_import_evalcontext.ts", + output: "run/042_dyn_import_evalcontext.ts.out", + }); + + itest!(_044_bad_resource { + args: "run --quiet --reload --allow-read run/044_bad_resource.ts", + output: "run/044_bad_resource.ts.out", + exit_code: 1, + }); + + // TODO(bartlomieju): remove --unstable once Deno.spawn is stabilized + itest!(_045_proxy { + args: "run -L debug --unstable --allow-net --allow-env --allow-run --allow-read --reload --quiet run/045_proxy_test.ts", + output: "run/045_proxy_test.ts.out", + http_server: true, +}); + + itest!(_046_tsx { + args: "run --quiet --reload run/046_jsx_test.tsx", + output: "run/046_jsx_test.tsx.out", + }); + + itest!(_047_jsx { + args: "run --quiet --reload run/047_jsx_test.jsx", + output: "run/047_jsx_test.jsx.out", + }); + + itest!(_048_media_types_jsx { + args: "run --reload run/048_media_types_jsx.ts", + output: "run/048_media_types_jsx.ts.out", + http_server: true, + }); + + itest!(_052_no_remote_flag { + args: + "run --reload --check --no-remote http://127.0.0.1:4545/run/019_media_types.ts", + output: "run/052_no_remote_flag.out", + exit_code: 1, + http_server: true, +}); + + itest!(_056_make_temp_file_write_perm { + args: + "run --quiet --allow-read --allow-write=./subdir/ run/056_make_temp_file_write_perm.ts", + output: "run/056_make_temp_file_write_perm.out", +}); + + itest!(_058_tasks_microtasks_close { + args: "run --quiet run/058_tasks_microtasks_close.ts", + output: "run/058_tasks_microtasks_close.ts.out", + }); + + itest!(_059_fs_relative_path_perm { + args: "run run/059_fs_relative_path_perm.ts", + output: "run/059_fs_relative_path_perm.ts.out", + exit_code: 1, + }); + + itest!(_070_location { + args: "run --location https://foo/bar?baz#bat run/070_location.ts", + output: "run/070_location.ts.out", + }); + + itest!(_071_location_unset { + args: "run run/071_location_unset.ts", + output: "run/071_location_unset.ts.out", + }); + + itest!(_072_location_relative_fetch { + args: "run --location http://127.0.0.1:4545/ --allow-net run/072_location_relative_fetch.ts", + output: "run/072_location_relative_fetch.ts.out", + http_server: true, +}); + + // tests the beforeunload event + itest!(beforeunload_event { + args: "run run/before_unload.js", + output: "run/before_unload.js.out", + }); + + // tests the serialization of webstorage (both localStorage and sessionStorage) + itest!(webstorage_serialization { + args: "run run/webstorage/serialization.ts", + output: "run/webstorage/serialization.ts.out", + }); + + // tests to ensure that when `--location` is set, all code shares the same + // localStorage cache based on the origin of the location URL. + #[test] + fn webstorage_location_shares_origin() { + let deno_dir = util::new_deno_dir(); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--location") + .arg("https://example.com/a.ts") + .arg("run/webstorage/fixture.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Storage { length: 0 }\n"); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--location") + .arg("https://example.com/b.ts") + .arg("run/webstorage/logger.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Storage { length: 1, hello: \"deno\" }\n"); + } + + // test to ensure that when a --config file is set, but no --location, that + // storage persists against unique configuration files. + #[test] + fn webstorage_config_file() { + let deno_dir = util::new_deno_dir(); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--config") + .arg("run/webstorage/config_a.jsonc") + .arg("run/webstorage/fixture.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Storage { length: 0 }\n"); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--config") + .arg("run/webstorage/config_b.jsonc") + .arg("run/webstorage/logger.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Storage { length: 0 }\n"); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--config") + .arg("run/webstorage/config_a.jsonc") + .arg("run/webstorage/logger.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Storage { length: 1, hello: \"deno\" }\n"); + } + + // tests to ensure `--config` does not effect persisted storage when a + // `--location` is provided. + #[test] + fn webstorage_location_precedes_config() { + let deno_dir = util::new_deno_dir(); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--location") + .arg("https://example.com/a.ts") + .arg("--config") + .arg("run/webstorage/config_a.jsonc") + .arg("run/webstorage/fixture.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Storage { length: 0 }\n"); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--location") + .arg("https://example.com/b.ts") + .arg("--config") + .arg("run/webstorage/config_b.jsonc") + .arg("run/webstorage/logger.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Storage { length: 1, hello: \"deno\" }\n"); + } + + // test to ensure that when there isn't a configuration or location, that the + // main module is used to determine how to persist storage data. + #[test] + fn webstorage_main_module() { + let deno_dir = util::new_deno_dir(); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("run/webstorage/fixture.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Storage { length: 0 }\n"); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("run/webstorage/logger.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Storage { length: 0 }\n"); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("run/webstorage/fixture.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"Storage { length: 1, hello: \"deno\" }\n"); + } + + itest!(_075_import_local_query_hash { + args: "run run/075_import_local_query_hash.ts", + output: "run/075_import_local_query_hash.ts.out", + }); + + itest!(_077_fetch_empty { + args: "run -A run/077_fetch_empty.ts", + output: "run/077_fetch_empty.ts.out", + exit_code: 1, + }); + + itest!(_078_unload_on_exit { + args: "run run/078_unload_on_exit.ts", + output: "run/078_unload_on_exit.ts.out", + exit_code: 1, + }); + + itest!(_079_location_authentication { + args: + "run --location https://foo:bar@baz/qux run/079_location_authentication.ts", + output: "run/079_location_authentication.ts.out", +}); + + itest!(_081_location_relative_fetch_redirect { + args: "run --location http://127.0.0.1:4546/ --allow-net run/081_location_relative_fetch_redirect.ts", + output: "run/081_location_relative_fetch_redirect.ts.out", + http_server: true, + }); + + itest!(_082_prepare_stack_trace_throw { + args: "run run/082_prepare_stack_trace_throw.js", + output: "run/082_prepare_stack_trace_throw.js.out", + exit_code: 1, + }); + + #[test] + fn _083_legacy_external_source_map() { + let _g = util::http_server(); + let deno_dir = TempDir::new(); + let module_url = url::Url::parse( + "http://localhost:4545/run/083_legacy_external_source_map.ts", + ) + .unwrap(); + // Write a faulty old external source map. + let faulty_map_path = deno_dir.path().join("gen/http/localhost_PORT4545/9576bd5febd0587c5c4d88d57cb3ac8ebf2600c529142abe3baa9a751d20c334.js.map"); + std::fs::create_dir_all(faulty_map_path.parent().unwrap()).unwrap(); + std::fs::write(faulty_map_path, "{\"version\":3,\"file\":\"\",\"sourceRoot\":\"\",\"sources\":[\"http://localhost:4545/083_legacy_external_source_map.ts\"],\"names\":[],\"mappings\":\";AAAA,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC\"}").unwrap(); + let output = Command::new(util::deno_exe_path()) + .env("DENO_DIR", deno_dir.path()) + .current_dir(util::testdata_path()) + .arg("run") + .arg(module_url.to_string()) + .output() + .unwrap(); + // Before https://github.com/denoland/deno/issues/6965 was fixed, the faulty + // old external source map would cause a panic while formatting the error + // and the exit code would be 101. The external source map should be ignored + // in favor of the inline one. + assert_eq!(output.status.code(), Some(1)); + let out = std::str::from_utf8(&output.stdout).unwrap(); + assert_eq!(out, ""); + } + + itest!(dynamic_import_async_error { + args: "run --allow-read run/dynamic_import_async_error/main.ts", + output: "run/dynamic_import_async_error/main.out", + }); + + itest!(dynamic_import_already_rejected { + args: "run --allow-read run/dynamic_import_already_rejected/main.ts", + output: "run/dynamic_import_already_rejected/main.out", + }); + + itest!(no_check_imports_not_used_as_values { + args: "run --config run/no_check_imports_not_used_as_values/preserve_imports.tsconfig.json --no-check run/no_check_imports_not_used_as_values/main.ts", + output: "run/no_check_imports_not_used_as_values/main.out", + }); + + itest!(_088_dynamic_import_already_evaluating { + args: "run --allow-read run/088_dynamic_import_already_evaluating.ts", + output: "run/088_dynamic_import_already_evaluating.ts.out", + }); + + // TODO(bartlomieju): remove --unstable once Deno.spawn is stabilized + itest!(_089_run_allow_list { + args: "run --unstable --allow-run=curl run/089_run_allow_list.ts", + output: "run/089_run_allow_list.ts.out", + }); + + #[test] + fn _090_run_permissions_request() { + let args = "run --quiet run/090_run_permissions_request.ts"; + use util::PtyData::*; + util::test_pty2(args, vec![ + Output("⚠️ ️Deno requests run access to \"ls\". Run again with --allow-run to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)]"), + Input("y\n"), + Output("⚠️ ️Deno requests run access to \"cat\". Run again with --allow-run to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)]"), + Input("n\n"), + Output("granted\r\n"), + Output("prompt\r\n"), + Output("denied\r\n"), + ]); + } + + itest!(_091_use_define_for_class_fields { + args: "run --check run/091_use_define_for_class_fields.ts", + output: "run/091_use_define_for_class_fields.ts.out", + exit_code: 1, + }); + + itest!(_092_import_map_unmapped_bare_specifier { + args: "run --import-map import_maps/import_map.json run/092_import_map_unmapped_bare_specifier.ts", + output: "run/092_import_map_unmapped_bare_specifier.ts.out", + exit_code: 1, +}); + + itest!(js_import_detect { + args: "run --quiet --reload run/js_import_detect.ts", + output: "run/js_import_detect.ts.out", + exit_code: 0, + }); + + itest!(blob_gc_finalization { + args: "run run/blob_gc_finalization.js", + output: "run/blob_gc_finalization.js.out", + exit_code: 0, + }); + + itest!(fetch_response_finalization { + args: + "run --v8-flags=--expose-gc --allow-net run/fetch_response_finalization.js", + output: "run/fetch_response_finalization.js.out", + http_server: true, + exit_code: 0, +}); + + itest!(import_type { + args: "run --reload run/import_type.ts", + output: "run/import_type.ts.out", + }); + + itest!(import_type_no_check { + args: "run --reload --no-check run/import_type.ts", + output: "run/import_type.ts.out", + }); + + itest!(private_field_presence { + args: "run --reload run/private_field_presence.ts", + output: "run/private_field_presence.ts.out", + }); + + itest!(private_field_presence_no_check { + args: "run --reload --no-check run/private_field_presence.ts", + output: "run/private_field_presence.ts.out", + }); + + // TODO(bartlomieju): remove --unstable once Deno.spawn is stabilized + itest!(lock_write_fetch { + args: + "run --quiet --allow-read --allow-write --allow-env --allow-run --unstable run/lock_write_fetch/main.ts", + output: "run/lock_write_fetch/main.out", + http_server: true, + exit_code: 0, +}); + + itest!(lock_check_ok { + args: + "run --lock=run/lock_check_ok.json http://127.0.0.1:4545/run/003_relative_import.ts", + output: "run/003_relative_import.ts.out", + http_server: true, +}); + + itest!(lock_check_ok2 { + args: "run --lock=run/lock_check_ok2.json run/019_media_types.ts", + output: "run/019_media_types.ts.out", + http_server: true, + }); + + itest!(lock_dynamic_imports { + args: "run --lock=run/lock_dynamic_imports.json --allow-read --allow-net http://127.0.0.1:4545/run/013_dynamic_import.ts", + output: "run/lock_dynamic_imports.out", + exit_code: 10, + http_server: true, +}); + + itest!(lock_check_err { + args: "run --lock=run/lock_check_err.json http://127.0.0.1:4545/run/003_relative_import.ts", + output: "run/lock_check_err.out", + exit_code: 10, + http_server: true, +}); + + itest!(lock_check_err2 { + args: "run --lock=run/lock_check_err2.json run/019_media_types.ts", + output: "run/lock_check_err2.out", + exit_code: 10, + http_server: true, + }); + + itest!(lock_v2_check_ok { + args: + "run --lock=run/lock_v2_check_ok.json http://127.0.0.1:4545/run/003_relative_import.ts", + output: "run/003_relative_import.ts.out", + http_server: true, +}); + + itest!(lock_v2_check_ok2 { + args: "run --lock=run/lock_v2_check_ok2.json run/019_media_types.ts", + output: "run/019_media_types.ts.out", + http_server: true, + }); + + itest!(lock_v2_dynamic_imports { + args: "run --lock=run/lock_v2_dynamic_imports.json --allow-read --allow-net http://127.0.0.1:4545/run/013_dynamic_import.ts", + output: "run/lock_v2_dynamic_imports.out", + exit_code: 10, + http_server: true, +}); + + itest!(lock_v2_check_err { + args: "run --lock=run/lock_v2_check_err.json http://127.0.0.1:4545/run/003_relative_import.ts", + output: "run/lock_v2_check_err.out", + exit_code: 10, + http_server: true, +}); + + itest!(lock_v2_check_err2 { + args: "run --lock=run/lock_v2_check_err2.json run/019_media_types.ts", + output: "run/lock_v2_check_err2.out", + exit_code: 10, + http_server: true, + }); + + itest!(lock_only_http_and_https { + args: "run --lock=run/lock_only_http_and_https/deno.lock run/lock_only_http_and_https/main.ts", + output: "run/lock_only_http_and_https/main.out", + http_server: true, +}); + + itest!(mts_dmts_mjs { + args: "run subdir/import.mts", + output: "run/mts_dmts_mjs.out", + }); + + itest!(mts_dmts_mjs_no_check { + args: "run --no-check subdir/import.mts", + output: "run/mts_dmts_mjs.out", + }); + + itest!(async_error { + exit_code: 1, + args: "run --reload run/async_error.ts", + output: "run/async_error.ts.out", + }); + + itest!(config { + args: + "run --reload --config run/config/tsconfig.json --check run/config/main.ts", + output: "run/config/main.out", +}); + + itest!(config_types { + args: + "run --reload --quiet --config run/config_types/tsconfig.json run/config_types/main.ts", + output: "run/config_types/main.out", +}); + + itest!(config_types_remote { + http_server: true, + args: "run --reload --quiet --config run/config_types/remote.tsconfig.json run/config_types/main.ts", + output: "run/config_types/main.out", + }); + + itest!(empty_typescript { + args: "run --reload --check run/empty.ts", + output_str: Some("Check file:[WILDCARD]/run/empty.ts\n"), + }); + + itest!(error_001 { + args: "run --reload run/error_001.ts", + exit_code: 1, + output: "run/error_001.ts.out", + }); + + itest!(error_002 { + args: "run --reload run/error_002.ts", + exit_code: 1, + output: "run/error_002.ts.out", + }); + + itest!(error_003_typescript { + args: "run --reload --check run/error_003_typescript.ts", + exit_code: 1, + output: "run/error_003_typescript.ts.out", + }); + + // Supposing that we've already attempted to run error_003_typescript.ts + // we want to make sure that JS wasn't emitted. Running again without reload flag + // should result in the same output. + // https://github.com/denoland/deno/issues/2436 + itest!(error_003_typescript2 { + args: "run --check run/error_003_typescript.ts", + exit_code: 1, + output: "run/error_003_typescript.ts.out", + }); + + itest!(error_004_missing_module { + args: "run --reload run/error_004_missing_module.ts", + exit_code: 1, + output: "run/error_004_missing_module.ts.out", + }); + + itest!(error_005_missing_dynamic_import { + args: + "run --reload --allow-read --quiet run/error_005_missing_dynamic_import.ts", + exit_code: 1, + output: "run/error_005_missing_dynamic_import.ts.out", +}); + + itest!(error_006_import_ext_failure { + args: "run --reload run/error_006_import_ext_failure.ts", + exit_code: 1, + output: "run/error_006_import_ext_failure.ts.out", + }); + + itest!(error_007_any { + args: "run --reload run/error_007_any.ts", + exit_code: 1, + output: "run/error_007_any.ts.out", + }); + + itest!(error_008_checkjs { + args: "run --reload run/error_008_checkjs.js", + exit_code: 1, + output: "run/error_008_checkjs.js.out", + }); + + itest!(error_009_extensions_error { + args: "run run/error_009_extensions_error.js", + output: "run/error_009_extensions_error.js.out", + exit_code: 1, + }); + + itest!(error_011_bad_module_specifier { + args: "run --reload run/error_011_bad_module_specifier.ts", + exit_code: 1, + output: "run/error_011_bad_module_specifier.ts.out", + }); + + itest!(error_012_bad_dynamic_import_specifier { + args: "run --reload --check run/error_012_bad_dynamic_import_specifier.ts", + exit_code: 1, + output: "run/error_012_bad_dynamic_import_specifier.ts.out", + }); + + itest!(error_013_missing_script { + args: "run --reload missing_file_name", + exit_code: 1, + output: "run/error_013_missing_script.out", + }); + + itest!(error_014_catch_dynamic_import_error { + args: + "run --reload --allow-read run/error_014_catch_dynamic_import_error.js", + output: "run/error_014_catch_dynamic_import_error.js.out", + }); + + itest!(error_015_dynamic_import_permissions { + args: "run --reload --quiet run/error_015_dynamic_import_permissions.js", + output: "run/error_015_dynamic_import_permissions.out", + exit_code: 1, + http_server: true, + }); + + // We have an allow-net flag but not allow-read, it should still result in error. + itest!(error_016_dynamic_import_permissions2 { + args: + "run --reload --allow-net run/error_016_dynamic_import_permissions2.js", + output: "run/error_016_dynamic_import_permissions2.out", + exit_code: 1, + http_server: true, + }); + + itest!(error_017_hide_long_source_ts { + args: "run --reload --check run/error_017_hide_long_source_ts.ts", + output: "run/error_017_hide_long_source_ts.ts.out", + exit_code: 1, + }); + + itest!(error_018_hide_long_source_js { + args: "run run/error_018_hide_long_source_js.js", + output: "run/error_018_hide_long_source_js.js.out", + exit_code: 1, + }); + + itest!(error_019_stack_function { + args: "run run/error_019_stack_function.ts", + output: "run/error_019_stack_function.ts.out", + exit_code: 1, + }); + + itest!(error_020_stack_constructor { + args: "run run/error_020_stack_constructor.ts", + output: "run/error_020_stack_constructor.ts.out", + exit_code: 1, + }); + + itest!(error_021_stack_method { + args: "run run/error_021_stack_method.ts", + output: "run/error_021_stack_method.ts.out", + exit_code: 1, + }); + + itest!(error_022_stack_custom_error { + args: "run run/error_022_stack_custom_error.ts", + output: "run/error_022_stack_custom_error.ts.out", + exit_code: 1, + }); + + itest!(error_023_stack_async { + args: "run run/error_023_stack_async.ts", + output: "run/error_023_stack_async.ts.out", + exit_code: 1, + }); + + itest!(error_024_stack_promise_all { + args: "run run/error_024_stack_promise_all.ts", + output: "run/error_024_stack_promise_all.ts.out", + exit_code: 1, + }); + + itest!(error_025_tab_indent { + args: "run run/error_025_tab_indent", + output: "run/error_025_tab_indent.out", + exit_code: 1, + }); + + itest!(error_026_remote_import_error { + args: "run run/error_026_remote_import_error.ts", + output: "run/error_026_remote_import_error.ts.out", + exit_code: 1, + http_server: true, + }); + + itest!(error_for_await { + args: "run --reload --check run/error_for_await.ts", + output: "run/error_for_await.ts.out", + exit_code: 1, + }); + + itest!(error_missing_module_named_import { + args: "run --reload run/error_missing_module_named_import.ts", + output: "run/error_missing_module_named_import.ts.out", + exit_code: 1, + }); + + itest!(error_no_check { + args: "run --reload --no-check run/error_no_check.ts", + output: "run/error_no_check.ts.out", + exit_code: 1, + }); + + itest!(error_syntax { + args: "run --reload run/error_syntax.js", + exit_code: 1, + output: "run/error_syntax.js.out", + }); + + itest!(error_syntax_empty_trailing_line { + args: "run --reload run/error_syntax_empty_trailing_line.mjs", + exit_code: 1, + output: "run/error_syntax_empty_trailing_line.mjs.out", + }); + + itest!(error_type_definitions { + args: "run --reload --check run/error_type_definitions.ts", + exit_code: 1, + output: "run/error_type_definitions.ts.out", + }); + + itest!(error_local_static_import_from_remote_ts { + args: "run --reload http://localhost:4545/run/error_local_static_import_from_remote.ts", + exit_code: 1, + http_server: true, + output: "run/error_local_static_import_from_remote.ts.out", + }); + + itest!(error_local_static_import_from_remote_js { + args: "run --reload http://localhost:4545/run/error_local_static_import_from_remote.js", + exit_code: 1, + http_server: true, + output: "run/error_local_static_import_from_remote.js.out", + }); + + itest!(exit_error42 { + exit_code: 42, + args: "run --quiet --reload run/exit_error42.ts", + output: "run/exit_error42.ts.out", + }); + + itest!(set_exit_code_0 { + args: "run --no-check --unstable run/set_exit_code_0.ts", + output_str: Some(""), + exit_code: 0, + }); + + itest!(set_exit_code_1 { + args: "run --no-check --unstable run/set_exit_code_1.ts", + output_str: Some(""), + exit_code: 42, + }); + + itest!(set_exit_code_2 { + args: "run --no-check --unstable run/set_exit_code_2.ts", + output_str: Some(""), + exit_code: 42, + }); + + itest!(op_exit_op_set_exit_code_in_worker { + args: "run --no-check --unstable --allow-read run/op_exit_op_set_exit_code_in_worker.ts", + exit_code: 21, + output_str: Some(""), +}); + + itest!(deno_exit_tampering { + args: "run --no-check --unstable run/deno_exit_tampering.ts", + output_str: Some(""), + exit_code: 42, + }); + + itest!(heapstats { + args: "run --quiet --unstable --v8-flags=--expose-gc run/heapstats.js", + output: "run/heapstats.js.out", + }); + + itest!(finalization_registry { + args: + "run --quiet --unstable --v8-flags=--expose-gc run/finalization_registry.js", + output: "run/finalization_registry.js.out", +}); + + itest!(https_import { + args: "run --quiet --reload --cert tls/RootCA.pem run/https_import.ts", + output: "run/https_import.ts.out", + http_server: true, + }); + + itest!(if_main { + args: "run --quiet --reload run/if_main.ts", + output: "run/if_main.ts.out", + }); + + itest!(import_meta { + args: "run --quiet --reload --import-map=run/import_meta/importmap.json run/import_meta/main.ts", + output: "run/import_meta/main.out", +}); + + itest!(main_module { + args: "run --quiet --allow-read --reload run/main_module/main.ts", + output: "run/main_module/main.out", + }); + + itest!(no_check { + args: "run --quiet --reload --no-check run/006_url_imports.ts", + output: "run/006_url_imports.ts.out", + http_server: true, + }); + + itest!(no_check_decorators { + args: "run --quiet --reload --no-check run/no_check_decorators.ts", + output: "run/no_check_decorators.ts.out", + }); + + itest!(check_remote { + args: "run --quiet --reload --check=all run/no_check_remote.ts", + output: "run/no_check_remote.ts.disabled.out", + exit_code: 1, + http_server: true, + }); + + itest!(no_check_remote { + args: "run --quiet --reload --no-check=remote run/no_check_remote.ts", + output: "run/no_check_remote.ts.enabled.out", + http_server: true, + }); + + itest!(runtime_decorators { + args: "run --quiet --reload --no-check run/runtime_decorators.ts", + output: "run/runtime_decorators.ts.out", + }); + + itest!(seed_random { + args: "run --seed=100 run/seed_random.js", + output: "run/seed_random.js.out", + }); + + itest!(type_definitions { + args: "run --reload run/type_definitions.ts", + output: "run/type_definitions.ts.out", + }); + + itest!(type_definitions_for_export { + args: "run --reload --check run/type_definitions_for_export.ts", + output: "run/type_definitions_for_export.ts.out", + exit_code: 1, + }); + + itest!(type_directives_01 { + args: "run --reload --check=all -L debug run/type_directives_01.ts", + output: "run/type_directives_01.ts.out", + http_server: true, + }); + + itest!(type_directives_02 { + args: "run --reload --check=all -L debug run/type_directives_02.ts", + output: "run/type_directives_02.ts.out", + }); + + itest!(type_directives_js_main { + args: "run --reload -L debug run/type_directives_js_main.js", + output: "run/type_directives_js_main.js.out", + exit_code: 0, + }); + + itest!(type_directives_redirect { + args: "run --reload --check run/type_directives_redirect.ts", + output: "run/type_directives_redirect.ts.out", + http_server: true, + }); + + itest!(type_headers_deno_types { + args: "run --reload --check run/type_headers_deno_types.ts", + output: "run/type_headers_deno_types.ts.out", + http_server: true, + }); + + itest!(ts_type_imports { + args: "run --reload --check run/ts_type_imports.ts", + output: "run/ts_type_imports.ts.out", + exit_code: 1, + }); + + itest!(ts_decorators { + args: "run --reload --check run/ts_decorators.ts", + output: "run/ts_decorators.ts.out", + }); + + itest!(ts_type_only_import { + args: "run --reload --check run/ts_type_only_import.ts", + output: "run/ts_type_only_import.ts.out", + }); + + itest!(swc_syntax_error { + args: "run --reload --check run/swc_syntax_error.ts", + output: "run/swc_syntax_error.ts.out", + exit_code: 1, + }); + + itest!(unbuffered_stderr { + args: "run --reload run/unbuffered_stderr.ts", + output: "run/unbuffered_stderr.ts.out", + }); + + itest!(unbuffered_stdout { + args: "run --quiet --reload run/unbuffered_stdout.ts", + output: "run/unbuffered_stdout.ts.out", + }); + + itest!(v8_flags_run { + args: "run --v8-flags=--expose-gc run/v8_flags.js", + output: "run/v8_flags.js.out", + }); + + itest!(v8_flags_unrecognized { + args: "repl --v8-flags=--foo,bar,--trace-gc,-baz", + output: "run/v8_flags_unrecognized.out", + exit_code: 1, + }); + + itest!(v8_help { + args: "repl --v8-flags=--help", + output: "run/v8_help.out", + }); + + itest!(unsupported_dynamic_import_scheme { + args: "eval import('xxx:')", + output: "run/unsupported_dynamic_import_scheme.out", + exit_code: 1, + }); + + itest!(wasm { + args: "run --quiet run/wasm.ts", + output: "run/wasm.ts.out", + }); + + itest!(wasm_shared { + args: "run --quiet run/wasm_shared.ts", + output: "run/wasm_shared.out", + }); + + itest!(wasm_async { + args: "run run/wasm_async.js", + output: "run/wasm_async.out", + }); + + itest!(wasm_unreachable { + args: "run --allow-read run/wasm_unreachable.js", + output: "run/wasm_unreachable.out", + exit_code: 1, + }); + + itest!(wasm_url { + args: "run --quiet --allow-net=localhost:4545 run/wasm_url.js", + output: "run/wasm_url.out", + exit_code: 1, + http_server: true, + }); + + itest!(weakref { + args: "run --quiet --reload run/weakref.ts", + output: "run/weakref.ts.out", + }); + + itest!(top_level_await_order { + args: "run --allow-read run/top_level_await/order.js", + output: "run/top_level_await/order.out", + }); + + itest!(top_level_await_loop { + args: "run --allow-read run/top_level_await/loop.js", + output: "run/top_level_await/loop.out", + }); + + itest!(top_level_await_circular { + args: "run --allow-read run/top_level_await/circular.js", + output: "run/top_level_await/circular.out", + exit_code: 1, + }); + + // Regression test for https://github.com/denoland/deno/issues/11238. + itest!(top_level_await_nested { + args: "run --allow-read run/top_level_await/nested/main.js", + output: "run/top_level_await/nested.out", + }); + + itest!(top_level_await_unresolved { + args: "run run/top_level_await/unresolved.js", + output: "run/top_level_await/unresolved.out", + exit_code: 1, + }); + + itest!(top_level_await { + args: "run --allow-read run/top_level_await/top_level_await.js", + output: "run/top_level_await/top_level_await.out", + }); + + itest!(top_level_await_ts { + args: "run --quiet --allow-read run/top_level_await/top_level_await.ts", + output: "run/top_level_await/top_level_await.out", + }); + + itest!(top_level_for_await { + args: "run --quiet run/top_level_await/top_level_for_await.js", + output: "run/top_level_await/top_level_for_await.out", + }); + + itest!(top_level_for_await_ts { + args: "run --quiet run/top_level_await/top_level_for_await.ts", + output: "run/top_level_await/top_level_for_await.out", + }); + + itest!(unstable_disabled { + args: "run --reload --check run/unstable.ts", + exit_code: 1, + output: "run/unstable_disabled.out", + }); + + itest!(unstable_enabled { + args: "run --quiet --reload --unstable run/unstable.ts", + output: "run/unstable_enabled.out", + }); + + itest!(unstable_disabled_js { + args: "run --reload run/unstable.js", + output: "run/unstable_disabled_js.out", + }); + + itest!(unstable_enabled_js { + args: "run --quiet --reload --unstable run/unstable.ts", + output: "run/unstable_enabled_js.out", + }); + + itest!(unstable_worker { + args: "run --reload --unstable --quiet --allow-read run/unstable_worker.ts", + output: "run/unstable_worker.ts.out", + }); + + itest!(import_compression { + args: "run --quiet --reload --allow-net run/import_compression/main.ts", + output: "run/import_compression/main.out", + http_server: true, + }); + + itest!(disallow_http_from_https_js { + args: "run --quiet --reload --cert tls/RootCA.pem https://localhost:5545/run/disallow_http_from_https.js", + output: "run/disallow_http_from_https_js.out", + http_server: true, + exit_code: 1, +}); + + itest!(disallow_http_from_https_ts { + args: "run --quiet --reload --cert tls/RootCA.pem https://localhost:5545/run/disallow_http_from_https.ts", + output: "run/disallow_http_from_https_ts.out", + http_server: true, + exit_code: 1, +}); + + itest!(dynamic_import_conditional { + args: "run --quiet --reload run/dynamic_import_conditional.js", + output: "run/dynamic_import_conditional.js.out", + }); + + itest!(tsx_imports { + args: "run --reload --check run/tsx_imports/tsx_imports.ts", + output: "run/tsx_imports/tsx_imports.ts.out", + }); + + itest!(fix_dynamic_import_errors { + args: "run --reload run/fix_dynamic_import_errors.js", + output: "run/fix_dynamic_import_errors.js.out", + }); + + itest!(fix_emittable_skipped { + args: "run --reload run/fix_emittable_skipped.js", + output: "run/fix_emittable_skipped.ts.out", + }); + + itest!(fix_js_import_js { + args: "run --quiet --reload run/fix_js_import_js.ts", + output: "run/fix_js_import_js.ts.out", + }); + + itest!(fix_js_imports { + args: "run --quiet --reload run/fix_js_imports.ts", + output: "run/fix_js_imports.ts.out", + }); + + itest!(fix_tsc_file_exists { + args: "run --quiet --reload tsc/test.js", + output: "run/fix_tsc_file_exists.out", + }); + + itest!(fix_worker_dispatchevent { + args: "run --quiet --reload run/fix_worker_dispatchevent.ts", + output: "run/fix_worker_dispatchevent.ts.out", + }); + + itest!(es_private_fields { + args: "run --quiet --reload run/es_private_fields.js", + output: "run/es_private_fields.js.out", + }); + + itest!(cjs_imports { + args: "run --quiet --reload run/cjs_imports/main.ts", + output: "run/cjs_imports/main.out", + }); + + itest!(ts_import_from_js { + args: "run --quiet --reload run/ts_import_from_js/main.js", + output: "run/ts_import_from_js/main.out", + http_server: true, + }); + + itest!(jsx_import_from_ts { + args: "run --quiet --reload run/jsx_import_from_ts.ts", + output: "run/jsx_import_from_ts.ts.out", + }); + + itest!(jsx_import_source_pragma { + args: "run --reload run/jsx_import_source_pragma.tsx", + output: "run/jsx_import_source.out", + http_server: true, + }); + + itest!(jsx_import_source_pragma_with_config { + args: + "run --reload --config jsx/deno-jsx.jsonc --no-lock run/jsx_import_source_pragma.tsx", + output: "run/jsx_import_source.out", + http_server: true, +}); + + itest!(jsx_import_source_pragma_with_dev_config { + args: + "run --reload --config jsx/deno-jsxdev.jsonc --no-lock run/jsx_import_source_pragma.tsx", + output: "run/jsx_import_source_dev.out", + http_server: true, +}); + + itest!(jsx_import_source_no_pragma { + args: + "run --reload --config jsx/deno-jsx.jsonc --no-lock run/jsx_import_source_no_pragma.tsx", + output: "run/jsx_import_source.out", + http_server: true, +}); + + itest!(jsx_import_source_no_pragma_dev { + args: "run --reload --config jsx/deno-jsxdev.jsonc --no-lock run/jsx_import_source_no_pragma.tsx", + output: "run/jsx_import_source_dev.out", + http_server: true, +}); + + itest!(jsx_import_source_pragma_import_map { + args: "run --reload --import-map jsx/import-map.json run/jsx_import_source_pragma_import_map.tsx", + output: "run/jsx_import_source_import_map.out", + http_server: true, +}); + + itest!(jsx_import_source_pragma_import_map_dev { + args: "run --reload --import-map jsx/import-map.json --config jsx/deno-jsxdev-import-map.jsonc run/jsx_import_source_pragma_import_map.tsx", + output: "run/jsx_import_source_import_map_dev.out", + http_server: true, +}); + + itest!(jsx_import_source_import_map { + args: "run --reload --import-map jsx/import-map.json --no-lock --config jsx/deno-jsx-import-map.jsonc run/jsx_import_source_no_pragma.tsx", + output: "run/jsx_import_source_import_map.out", + http_server: true, +}); + + itest!(jsx_import_source_import_map_dev { + args: "run --reload --import-map jsx/import-map.json --no-lock --config jsx/deno-jsxdev-import-map.jsonc run/jsx_import_source_no_pragma.tsx", + output: "run/jsx_import_source_import_map_dev.out", + http_server: true, +}); + + itest!(jsx_import_source_import_map_scoped { + args: "run --reload --import-map jsx/import-map-scoped.json --no-lock --config jsx/deno-jsx-import-map.jsonc subdir/jsx_import_source_no_pragma.tsx", + output: "run/jsx_import_source_import_map.out", + http_server: true, +}); + + itest!(jsx_import_source_import_map_scoped_dev { + args: "run --reload --import-map jsx/import-map-scoped.json --no-lock --config jsx/deno-jsxdev-import-map.jsonc subdir/jsx_import_source_no_pragma.tsx", + output: "run/jsx_import_source_import_map_dev.out", + http_server: true, +}); + + itest!(jsx_import_source_pragma_no_check { + args: "run --reload --no-check run/jsx_import_source_pragma.tsx", + output: "run/jsx_import_source.out", + http_server: true, + }); + + itest!(jsx_import_source_pragma_with_config_no_check { + args: "run --reload --config jsx/deno-jsx.jsonc --no-lock --no-check run/jsx_import_source_pragma.tsx", + output: "run/jsx_import_source.out", + http_server: true, +}); + + itest!(jsx_import_source_no_pragma_no_check { + args: + "run --reload --config jsx/deno-jsx.jsonc --no-lock --no-check run/jsx_import_source_no_pragma.tsx", + output: "run/jsx_import_source.out", + http_server: true, +}); + + itest!(jsx_import_source_pragma_import_map_no_check { + args: "run --reload --import-map jsx/import-map.json --no-check run/jsx_import_source_pragma_import_map.tsx", + output: "run/jsx_import_source_import_map.out", + http_server: true, +}); + + itest!(jsx_import_source_import_map_no_check { + args: "run --reload --import-map jsx/import-map.json --no-lock --config jsx/deno-jsx-import-map.jsonc --no-check run/jsx_import_source_no_pragma.tsx", + output: "run/jsx_import_source_import_map.out", + http_server: true, +}); + + itest!(jsx_import_source_error { + args: "run --config jsx/deno-jsx-error.jsonc --check run/jsx_import_source_no_pragma.tsx", + output: "run/jsx_import_source_error.out", + exit_code: 1, +}); + + // TODO(#11128): Flaky. Re-enable later. + // itest!(single_compile_with_reload { + // args: "run --relcert/oad --allow-read run/single_compile_with_reload.ts", + // output: "run/single_compile_with_reload.ts.out", + // }); + + itest!(proto_exploit { + args: "run run/proto_exploit.js", + output: "run/proto_exploit.js.out", + }); + + itest!(reference_types { + args: "run --reload --quiet run/reference_types.ts", + output: "run/reference_types.ts.out", + }); + + itest!(references_types_remote { + http_server: true, + args: "run --reload --quiet run/reference_types_remote.ts", + output: "run/reference_types_remote.ts.out", + }); + + itest!(reference_types_error { + args: + "run --config run/checkjs.tsconfig.json --check run/reference_types_error.js", + output: "run/reference_types_error.js.out", + exit_code: 1, +}); + + itest!(reference_types_error_no_check { + args: "run --no-check run/reference_types_error.js", + output_str: Some(""), + }); + + itest!(import_data_url_error_stack { + args: "run --quiet --reload run/import_data_url_error_stack.ts", + output: "run/import_data_url_error_stack.ts.out", + exit_code: 1, + }); + + itest!(import_data_url_import_relative { + args: "run --quiet --reload run/import_data_url_import_relative.ts", + output: "run/import_data_url_import_relative.ts.out", + exit_code: 1, + }); + + itest!(import_data_url_import_map { + args: "run --quiet --reload --import-map import_maps/import_map.json run/import_data_url.ts", + output: "run/import_data_url.ts.out", + }); + + itest!(import_data_url_imports { + args: "run --quiet --reload run/import_data_url_imports.ts", + output: "run/import_data_url_imports.ts.out", + http_server: true, + }); + + itest!(import_data_url_jsx { + args: "run --quiet --reload run/import_data_url_jsx.ts", + output: "run/import_data_url_jsx.ts.out", + }); + + itest!(import_data_url { + args: "run --quiet --reload run/import_data_url.ts", + output: "run/import_data_url.ts.out", + }); + + itest!(import_dynamic_data_url { + args: "run --quiet --reload run/import_dynamic_data_url.ts", + output: "run/import_dynamic_data_url.ts.out", + }); + + itest!(import_blob_url_error_stack { + args: "run --quiet --reload run/import_blob_url_error_stack.ts", + output: "run/import_blob_url_error_stack.ts.out", + exit_code: 1, + }); + + itest!(import_blob_url_import_relative { + args: "run --quiet --reload run/import_blob_url_import_relative.ts", + output: "run/import_blob_url_import_relative.ts.out", + exit_code: 1, + }); + + itest!(import_blob_url_imports { + args: + "run --quiet --reload --allow-net=localhost:4545 run/import_blob_url_imports.ts", + output: "run/import_blob_url_imports.ts.out", + http_server: true, +}); + + itest!(import_blob_url_jsx { + args: "run --quiet --reload run/import_blob_url_jsx.ts", + output: "run/import_blob_url_jsx.ts.out", + }); + + itest!(import_blob_url { + args: "run --quiet --reload run/import_blob_url.ts", + output: "run/import_blob_url.ts.out", + }); + + itest!(import_file_with_colon { + args: "run --quiet --reload run/import_file_with_colon.ts", + output: "run/import_file_with_colon.ts.out", + http_server: true, + }); + + itest!(import_extensionless { + args: "run --quiet --reload run/import_extensionless.ts", + output: "run/import_extensionless.ts.out", + http_server: true, + }); + + itest!(classic_workers_event_loop { + args: + "run --enable-testing-features-do-not-use run/classic_workers_event_loop.js", + output: "run/classic_workers_event_loop.js.out", +}); + + // FIXME(bartlomieju): disabled, because this test is very flaky on CI + // itest!(local_sources_not_cached_in_memory { + // args: "run --allow-read --allow-write run/no_mem_cache.js", + // output: "run/no_mem_cache.js.out", + // }); + + // This test checks that inline source map data is used. It uses a hand crafted + // source map that maps to a file that exists, but is not loaded into the module + // graph (inline_js_source_map_2.ts) (because there are no direct dependencies). + // Source line is not remapped because no inline source contents are included in + // the sourcemap and the file is not present in the dependency graph. + itest!(inline_js_source_map_2 { + args: "run --quiet run/inline_js_source_map_2.js", + output: "run/inline_js_source_map_2.js.out", + exit_code: 1, + }); + + // This test checks that inline source map data is used. It uses a hand crafted + // source map that maps to a file that exists, but is not loaded into the module + // graph (inline_js_source_map_2.ts) (because there are no direct dependencies). + // Source line remapped using th inline source contents that are included in the + // inline source map. + itest!(inline_js_source_map_2_with_inline_contents { + args: "run --quiet run/inline_js_source_map_2_with_inline_contents.js", + output: "run/inline_js_source_map_2_with_inline_contents.js.out", + exit_code: 1, + }); + + // This test checks that inline source map data is used. It uses a hand crafted + // source map that maps to a file that exists, and is loaded into the module + // graph because of a direct import statement (inline_js_source_map.ts). The + // source map was generated from an earlier version of this file, where the throw + // was not commented out. The source line is remapped using source contents that + // from the module graph. + itest!(inline_js_source_map_with_contents_from_graph { + args: "run --quiet run/inline_js_source_map_with_contents_from_graph.js", + output: "run/inline_js_source_map_with_contents_from_graph.js.out", + exit_code: 1, + http_server: true, + }); + + // This test ensures that a descriptive error is shown when we're unable to load + // the import map. Even though this tests only the `run` subcommand, we can be sure + // that the error message is similar for other subcommands as they all use + // `program_state.maybe_import_map` to access the import map underneath. + itest!(error_import_map_unable_to_load { + args: + "run --import-map=import_maps/does_not_exist.json import_maps/test.ts", + output: "run/error_import_map_unable_to_load.out", + exit_code: 1, + }); + + // Test that setting `self` in the main thread to some other value doesn't break + // the world. + itest!(replace_self { + args: "run run/replace_self.js", + output: "run/replace_self.js.out", + }); + + itest!(worker_event_handler_test { + args: "run --quiet --reload --allow-read run/worker_event_handler_test.js", + output: "run/worker_event_handler_test.js.out", + }); + + itest!(worker_close_race { + args: "run --quiet --reload --allow-read run/worker_close_race.js", + output: "run/worker_close_race.js.out", + }); + + itest!(worker_drop_handle_race { + args: "run --quiet --reload --allow-read run/worker_drop_handle_race.js", + output: "run/worker_drop_handle_race.js.out", + exit_code: 1, + }); + + itest!(worker_drop_handle_race_terminate { + args: "run --unstable run/worker_drop_handle_race_terminate.js", + output: "run/worker_drop_handle_race_terminate.js.out", + }); + + itest!(worker_close_nested { + args: "run --quiet --reload --allow-read run/worker_close_nested.js", + output: "run/worker_close_nested.js.out", + }); + + itest!(worker_message_before_close { + args: + "run --quiet --reload --allow-read run/worker_message_before_close.js", + output: "run/worker_message_before_close.js.out", + }); + + itest!(worker_close_in_wasm_reactions { + args: + "run --quiet --reload --allow-read run/worker_close_in_wasm_reactions.js", + output: "run/worker_close_in_wasm_reactions.js.out", + }); + + itest!(shebang_tsc { + args: "run --quiet --check run/shebang.ts", + output: "run/shebang.ts.out", + }); + + itest!(shebang_swc { + args: "run --quiet run/shebang.ts", + output: "run/shebang.ts.out", + }); + + itest!(shebang_with_json_imports_tsc { + args: "run --quiet import_assertions/json_with_shebang.ts", + output: "import_assertions/json_with_shebang.ts.out", + exit_code: 1, + }); + + itest!(shebang_with_json_imports_swc { + args: "run --quiet --no-check import_assertions/json_with_shebang.ts", + output: "import_assertions/json_with_shebang.ts.out", + exit_code: 1, + }); + + #[test] + fn no_validate_asm() { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("run/no_validate_asm.js") + .stderr(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert!(output.stderr.is_empty()); + assert!(output.stdout.is_empty()); + } + + #[test] + fn exec_path() { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--allow-read") + .arg("run/exec_path.ts") + .stdout(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); + let actual = + std::fs::canonicalize(std::path::Path::new(stdout_str)).unwrap(); + let expected = std::fs::canonicalize(util::deno_exe_path()).unwrap(); + assert_eq!(expected, actual); + } + + #[cfg(windows)] + // Clippy suggests to remove the `NoStd` prefix from all variants. I disagree. + #[allow(clippy::enum_variant_names)] + enum WinProcConstraints { + NoStdIn, + NoStdOut, + NoStdErr, + } + + #[cfg(windows)] + fn run_deno_script_constrained( + script_path: std::path::PathBuf, + constraints: WinProcConstraints, + ) -> Result<(), i64> { + let file_path = "assets/DenoWinRunner.ps1"; + let constraints = match constraints { + WinProcConstraints::NoStdIn => "1", + WinProcConstraints::NoStdOut => "2", + WinProcConstraints::NoStdErr => "4", + }; + let deno_exe_path = util::deno_exe_path() + .into_os_string() + .into_string() + .unwrap(); + + let deno_script_path = script_path.into_os_string().into_string().unwrap(); + + let args = vec![&deno_exe_path[..], &deno_script_path[..], constraints]; + util::run_powershell_script_file(file_path, args) + } + + #[cfg(windows)] + #[test] + fn should_not_panic_on_no_stdin() { + let output = run_deno_script_constrained( + util::testdata_path().join("echo.ts"), + WinProcConstraints::NoStdIn, + ); + output.unwrap(); + } + + #[cfg(windows)] + #[test] + fn should_not_panic_on_no_stdout() { + let output = run_deno_script_constrained( + util::testdata_path().join("echo.ts"), + WinProcConstraints::NoStdOut, + ); + output.unwrap(); + } + + #[cfg(windows)] + #[test] + fn should_not_panic_on_no_stderr() { + let output = run_deno_script_constrained( + util::testdata_path().join("echo.ts"), + WinProcConstraints::NoStdErr, + ); + output.unwrap(); + } + + #[cfg(not(windows))] + #[test] + fn should_not_panic_on_undefined_home_environment_variable() { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("echo.ts") + .env_remove("HOME") + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + } + + #[test] + fn should_not_panic_on_undefined_deno_dir_environment_variable() { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("echo.ts") + .env_remove("DENO_DIR") + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + } + + #[cfg(not(windows))] + #[test] + fn should_not_panic_on_undefined_deno_dir_and_home_environment_variables() { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("echo.ts") + .env_remove("DENO_DIR") + .env_remove("HOME") + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + } + + #[test] + fn rust_log() { + // Without RUST_LOG the stderr is empty. + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("run/001_hello.js") + .stderr(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert!(output.stderr.is_empty()); + + // With RUST_LOG the stderr is not empty. + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("run/001_hello.js") + .env("RUST_LOG", "debug") + .stderr(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + assert!(!output.stderr.is_empty()); + } + + #[test] + fn dont_cache_on_check_fail() { + let deno_dir = util::new_deno_dir(); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--check=all") + .arg("--reload") + .arg("run/error_003_typescript.ts") + .stderr(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + assert!(!output.stderr.is_empty()); + + let mut deno_cmd = util::deno_cmd_with_deno_dir(&deno_dir); + let output = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--check=all") + .arg("run/error_003_typescript.ts") + .stderr(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + assert!(!output.stderr.is_empty()); + } + + mod permissions { + use super::itest; + use test_util as util; + + // TODO(bartlomieju): remove --unstable once Deno.spawn is stabilized + #[test] + fn with_allow() { + for permission in &util::PERMISSION_VARIANTS { + let status = util::deno_cmd() + .current_dir(&util::testdata_path()) + .arg("run") + .arg("--unstable") + .arg(format!("--allow-{0}", permission)) + .arg("run/permission_test.ts") + .arg(format!("{0}Required", permission)) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + } + + // TODO(bartlomieju): remove --unstable once Deno.spawn is stabilized + #[test] + fn without_allow() { + for permission in &util::PERMISSION_VARIANTS { + let (_, err) = util::run_and_collect_output( + false, + &format!( + "run --unstable run/permission_test.ts {0}Required", + permission + ), + None, + None, + false, + ); + assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); + } + } + + #[test] + fn rw_inside_project_dir() { + const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; + for permission in &PERMISSION_VARIANTS { + let status = util::deno_cmd() + .current_dir(&util::testdata_path()) + .arg("run") + .arg(format!( + "--allow-{0}={1}", + permission, + util::testdata_path() + .into_os_string() + .into_string() + .unwrap() + )) + .arg("run/complex_permissions_test.ts") + .arg(permission) + .arg("run/complex_permissions_test.ts") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + } + + #[test] + fn rw_outside_test_dir() { + const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; + for permission in &PERMISSION_VARIANTS { + let (_, err) = util::run_and_collect_output( + false, + &format!( + "run --allow-{0}={1} run/complex_permissions_test.ts {0} {2}", + permission, + util::testdata_path() + .into_os_string() + .into_string() + .unwrap(), + util::root_path() + .join("Cargo.toml") + .into_os_string() + .into_string() + .unwrap(), + ), + None, + None, + false, + ); + assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); + } + } + + #[test] + fn rw_inside_test_dir() { + const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; + for permission in &PERMISSION_VARIANTS { + let status = util::deno_cmd() + .current_dir(&util::testdata_path()) + .arg("run") + .arg(format!( + "--allow-{0}={1}", + permission, + util::testdata_path() + .into_os_string() + .into_string() + .unwrap() + )) + .arg("run/complex_permissions_test.ts") + .arg(permission) + .arg("run/complex_permissions_test.ts") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + } + + #[test] + fn rw_outside_test_and_js_dir() { + const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; + let test_dir = util::testdata_path() + .into_os_string() + .into_string() + .unwrap(); + let js_dir = util::root_path() + .join("js") + .into_os_string() + .into_string() + .unwrap(); + for permission in &PERMISSION_VARIANTS { + let (_, err) = util::run_and_collect_output( + false, + &format!( + "run --allow-{0}={1},{2} run/complex_permissions_test.ts {0} {3}", + permission, + test_dir, + js_dir, + util::root_path() + .join("Cargo.toml") + .into_os_string() + .into_string() + .unwrap(), + ), + None, + None, + false, + ); + assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); + } + } + + #[test] + fn rw_inside_test_and_js_dir() { + const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; + let test_dir = util::testdata_path() + .into_os_string() + .into_string() + .unwrap(); + let js_dir = util::root_path() + .join("js") + .into_os_string() + .into_string() + .unwrap(); + for permission in &PERMISSION_VARIANTS { + let status = util::deno_cmd() + .current_dir(&util::testdata_path()) + .arg("run") + .arg(format!("--allow-{0}={1},{2}", permission, test_dir, js_dir)) + .arg("run/complex_permissions_test.ts") + .arg(permission) + .arg("run/complex_permissions_test.ts") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + } + + #[test] + fn rw_relative() { + const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; + for permission in &PERMISSION_VARIANTS { + let status = util::deno_cmd() + .current_dir(&util::testdata_path()) + .arg("run") + .arg(format!("--allow-{0}=.", permission)) + .arg("run/complex_permissions_test.ts") + .arg(permission) + .arg("run/complex_permissions_test.ts") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + } + + #[test] + fn rw_no_prefix() { + const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; + for permission in &PERMISSION_VARIANTS { + let status = util::deno_cmd() + .current_dir(&util::testdata_path()) + .arg("run") + .arg(format!("--allow-{0}=tls/../", permission)) + .arg("run/complex_permissions_test.ts") + .arg(permission) + .arg("run/complex_permissions_test.ts") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + } + + #[test] + fn net_fetch_allow_localhost_4545() { + let (_, err) = util::run_and_collect_output( + true, + "run --allow-net=localhost:4545 run/complex_permissions_test.ts netFetch http://localhost:4545/", + None, + None, + true, + ); + assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn net_fetch_allow_deno_land() { + let (_, err) = util::run_and_collect_output( + false, + "run --allow-net=deno.land run/complex_permissions_test.ts netFetch http://localhost:4545/", + None, + None, + true, + ); + assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn net_fetch_localhost_4545_fail() { + let (_, err) = util::run_and_collect_output( + false, + "run --allow-net=localhost:4545 run/complex_permissions_test.ts netFetch http://localhost:4546/", + None, + None, + true, + ); + assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn net_fetch_localhost() { + let (_, err) = util::run_and_collect_output( + true, + "run --allow-net=localhost run/complex_permissions_test.ts netFetch http://localhost:4545/ http://localhost:4546/ http://localhost:4547/", + None, + None, + true, + ); + assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn net_connect_allow_localhost_ip_4555() { + let (_, err) = util::run_and_collect_output( + true, + "run --allow-net=127.0.0.1:4545 run/complex_permissions_test.ts netConnect 127.0.0.1:4545", + None, + None, + true, + ); + assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn net_connect_allow_deno_land() { + let (_, err) = util::run_and_collect_output( + false, + "run --allow-net=deno.land run/complex_permissions_test.ts netConnect 127.0.0.1:4546", + None, + None, + true, + ); + assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn net_connect_allow_localhost_ip_4545_fail() { + let (_, err) = util::run_and_collect_output( + false, + "run --allow-net=127.0.0.1:4545 run/complex_permissions_test.ts netConnect 127.0.0.1:4546", + None, + None, + true, + ); + assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn net_connect_allow_localhost_ip() { + let (_, err) = util::run_and_collect_output( + true, + "run --allow-net=127.0.0.1 run/complex_permissions_test.ts netConnect 127.0.0.1:4545 127.0.0.1:4546 127.0.0.1:4547", + None, + None, + true, + ); + assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn net_listen_allow_localhost_4555() { + let (_, err) = util::run_and_collect_output( + true, + "run --allow-net=localhost:4558 run/complex_permissions_test.ts netListen localhost:4558", + None, + None, + false, + ); + assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn net_listen_allow_deno_land() { + let (_, err) = util::run_and_collect_output( + false, + "run --allow-net=deno.land run/complex_permissions_test.ts netListen localhost:4545", + None, + None, + false, + ); + assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn net_listen_allow_localhost_4555_fail() { + let (_, err) = util::run_and_collect_output( + false, + "run --allow-net=localhost:4555 run/complex_permissions_test.ts netListen localhost:4556", + None, + None, + false, + ); + assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn net_listen_allow_localhost() { + // Port 4600 is chosen to not colide with those used by + // target/debug/test_server + let (_, err) = util::run_and_collect_output( + true, + "run --allow-net=localhost run/complex_permissions_test.ts netListen localhost:4600", + None, + None, + false, + ); + assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); + } + + #[test] + fn _061_permissions_request() { + let args = "run --quiet run/061_permissions_request.ts"; + use util::PtyData::*; + util::test_pty2(args, vec![ + Output("⚠️ ️Deno requests read access to \"foo\". Run again with --allow-read to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)] "), + Input("y\n"), + Output("⚠️ ️Deno requests read access to \"bar\". Run again with --allow-read to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)]"), + Input("n\n"), + Output("granted\r\n"), + Output("prompt\r\n"), + Output("denied\r\n"), + ]); + } + + #[test] + fn _062_permissions_request_global() { + let args = "run --quiet run/062_permissions_request_global.ts"; + use util::PtyData::*; + util::test_pty2(args, vec![ + Output("⚠️ ️Deno requests read access. Run again with --allow-read to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)] "), + Input("y\n"), + Output("PermissionStatus { state: \"granted\", onchange: null }\r\n"), + Output("PermissionStatus { state: \"granted\", onchange: null }\r\n"), + Output("PermissionStatus { state: \"granted\", onchange: null }\r\n"), + ]); + } + + itest!(_063_permissions_revoke { + args: "run --allow-read=foo,bar run/063_permissions_revoke.ts", + output: "run/063_permissions_revoke.ts.out", + }); + + itest!(_064_permissions_revoke_global { + args: "run --allow-read=foo,bar run/064_permissions_revoke_global.ts", + output: "run/064_permissions_revoke_global.ts.out", + }); + + #[test] + fn _066_prompt() { + let args = "run --quiet --unstable run/066_prompt.ts"; + use util::PtyData::*; + util::test_pty2( + args, + vec![ + Output("What is your name? [Jane Doe] "), + Input("John Doe\n"), + Output("Your name is John Doe.\r\n"), + Output("What is your name? [Jane Doe] "), + Input("\n"), + Output("Your name is Jane Doe.\r\n"), + Output("Prompt "), + Input("foo\n"), + Output("Your input is foo.\r\n"), + Output("Question 0 [y/N] "), + Input("Y\n"), + Output("Your answer is true\r\n"), + Output("Question 1 [y/N] "), + Input("N\n"), + Output("Your answer is false\r\n"), + Output("Question 2 [y/N] "), + Input("yes\n"), + Output("Your answer is false\r\n"), + Output("Confirm [y/N] "), + Input("\n"), + Output("Your answer is false\r\n"), + Output("What is Windows EOL? "), + Input("windows\n"), + Output("Your answer is \"windows\"\r\n"), + Output("Hi [Enter] "), + Input("\n"), + Output("Alert [Enter] "), + Input("\n"), + Output("The end of test\r\n"), + Output("What is EOF? "), + Input("\n"), + Output("Your answer is null\r\n"), + ], + ); + } + + itest!(dynamic_import_permissions_remote_remote { + args: "run --quiet --reload --allow-net=localhost:4545 dynamic_import/permissions_remote_remote.ts", + output: "dynamic_import/permissions_remote_remote.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(dynamic_import_permissions_data_remote { + args: "run --quiet --reload --allow-net=localhost:4545 dynamic_import/permissions_data_remote.ts", + output: "dynamic_import/permissions_data_remote.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(dynamic_import_permissions_blob_remote { + args: "run --quiet --reload --allow-net=localhost:4545 dynamic_import/permissions_blob_remote.ts", + output: "dynamic_import/permissions_blob_remote.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(dynamic_import_permissions_data_local { + args: "run --quiet --reload --allow-net=localhost:4545 dynamic_import/permissions_data_local.ts", + output: "dynamic_import/permissions_data_local.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(dynamic_import_permissions_blob_local { + args: "run --quiet --reload --allow-net=localhost:4545 dynamic_import/permissions_blob_local.ts", + output: "dynamic_import/permissions_blob_local.ts.out", + http_server: true, + exit_code: 1, + }); + } + + itest!(tls_starttls { + args: "run --quiet --reload --allow-net --allow-read --unstable --cert tls/RootCA.pem run/tls_starttls.js", + output: "run/tls.out", +}); + + itest!(tls_connecttls { + args: "run --quiet --reload --allow-net --allow-read --cert tls/RootCA.pem run/tls_connecttls.js", + output: "run/tls.out", +}); + + itest!(byte_order_mark { + args: "run --no-check run/byte_order_mark.ts", + output: "run/byte_order_mark.out", + }); + + #[test] + fn issue9750() { + use util::PtyData::*; + util::test_pty2( + "run --prompt run/issue9750.js", + vec![ + Output("Enter 'yy':\r\n"), + Input("yy\n"), + Output("⚠️ ️Deno requests env access. Run again with --allow-env to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)]"), + Input("n\n"), + Output("⚠️ ️Deno requests env access to \"SECRET\". Run again with --allow-env to bypass this prompt.\r\n Allow? [y/n (y = yes allow, n = no deny)]"), + Input("n\n"), + Output("error: Uncaught (in promise) PermissionDenied: Requires env access to \"SECRET\", run again with the --allow-env flag\r\n"), + ], + ); + } + + // Regression test for https://github.com/denoland/deno/issues/11451. + itest!(dom_exception_formatting { + args: "run run/dom_exception_formatting.ts", + output: "run/dom_exception_formatting.ts.out", + exit_code: 1, + }); + + itest!(long_data_url_formatting { + args: "run run/long_data_url_formatting.ts", + output: "run/long_data_url_formatting.ts.out", + exit_code: 1, + }); + + itest!(eval_context_throw_dom_exception { + args: "run run/eval_context_throw_dom_exception.js", + output: "run/eval_context_throw_dom_exception.js.out", + }); + + #[test] + #[cfg(unix)] + fn navigator_language_unix() { + let (res, _) = util::run_and_collect_output( + true, + "run navigator_language.ts", + None, + Some(vec![("LC_ALL".to_owned(), "pl_PL".to_owned())]), + false, + ); + assert_eq!(res, "pl-PL\n") + } + + #[test] + fn navigator_language() { + let (res, _) = util::run_and_collect_output( + true, + "run navigator_language.ts", + None, + None, + false, + ); + assert!(!res.is_empty()) + } + + #[test] + #[cfg(unix)] + fn navigator_languages_unix() { + let (res, _) = util::run_and_collect_output( + true, + "run navigator_languages.ts", + None, + Some(vec![ + ("LC_ALL".to_owned(), "pl_PL".to_owned()), + ("NO_COLOR".to_owned(), "1".to_owned()), + ]), + false, + ); + assert_eq!(res, "[ \"pl-PL\" ]\n") + } + + #[test] + fn navigator_languages() { + let (res, _) = util::run_and_collect_output( + true, + "run navigator_languages.ts", + None, + None, + false, + ); + assert!(!res.is_empty()) + } + + /// Regression test for https://github.com/denoland/deno/issues/12740. + #[test] + fn issue12740() { + let mod_dir = TempDir::new(); + let mod1_path = mod_dir.path().join("mod1.ts"); + let mod2_path = mod_dir.path().join("mod2.ts"); + let mut deno_cmd = util::deno_cmd(); + std::fs::write(&mod1_path, "").unwrap(); + let status = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg(&mod1_path) + .stderr(Stdio::null()) + .stdout(Stdio::null()) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + std::fs::write(&mod1_path, "export { foo } from \"./mod2.ts\";").unwrap(); + std::fs::write(&mod2_path, "(").unwrap(); + let status = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg(&mod1_path) + .stderr(Stdio::null()) + .stdout(Stdio::null()) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(!status.success()); + } + + /// Regression test for https://github.com/denoland/deno/issues/12807. + #[test] + fn issue12807() { + let mod_dir = TempDir::new(); + let mod1_path = mod_dir.path().join("mod1.ts"); + let mod2_path = mod_dir.path().join("mod2.ts"); + let mut deno_cmd = util::deno_cmd(); + // With a fresh `DENO_DIR`, run a module with a dependency and a type error. + std::fs::write(&mod1_path, "import './mod2.ts'; Deno.exit('0');").unwrap(); + std::fs::write(&mod2_path, "console.log('Hello, world!');").unwrap(); + let status = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--check") + .arg(&mod1_path) + .stderr(Stdio::null()) + .stdout(Stdio::null()) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(!status.success()); + // Fix the type error and run again. + std::fs::write(&mod1_path, "import './mod2.ts'; Deno.exit(0);").unwrap(); + let status = deno_cmd + .current_dir(util::testdata_path()) + .arg("run") + .arg("--check") + .arg(&mod1_path) + .stderr(Stdio::null()) + .stdout(Stdio::null()) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + + itest!(issue_13562 { + args: "run run/issue13562.ts", + output: "run/issue13562.ts.out", + }); + + itest!(import_assertions_static_import { + args: "run --allow-read import_assertions/static_import.ts", + output: "import_assertions/static_import.out", + }); + + itest!(import_assertions_static_export { + args: "run --allow-read import_assertions/static_export.ts", + output: "import_assertions/static_export.out", + }); + + itest!(import_assertions_static_error { + args: "run --allow-read import_assertions/static_error.ts", + output: "import_assertions/static_error.out", + exit_code: 1, + }); + + itest!(import_assertions_dynamic_import { + args: "run --allow-read import_assertions/dynamic_import.ts", + output: "import_assertions/dynamic_import.out", + }); + + itest!(import_assertions_dynamic_error { + args: "run --allow-read import_assertions/dynamic_error.ts", + output: "import_assertions/dynamic_error.out", + exit_code: 1, + }); + + itest!(import_assertions_type_check { + args: "run --allow-read --check import_assertions/type_check.ts", + output: "import_assertions/type_check.out", + exit_code: 1, + }); + + itest!(delete_window { + args: "run run/delete_window.js", + output_str: Some("true\n"), + }); + + itest!(colors_without_global_this { + args: "run run/colors_without_globalThis.js", + output_str: Some("true\n"), + }); + + itest!(config_auto_discovered_for_local_script { + args: "run --quiet run/with_config/frontend_work.ts", + output_str: Some("ok\n"), + }); + + itest!(no_config_auto_discovery_for_local_script { + args: "run --quiet --no-config --check run/with_config/frontend_work.ts", + output: "run/with_config/no_auto_discovery.out", + exit_code: 1, + }); + + itest!(config_not_auto_discovered_for_remote_script { + args: + "run --quiet http://127.0.0.1:4545/run/with_config/server_side_work.ts", + output_str: Some("ok\n"), + http_server: true, + }); + + itest!(wasm_streaming_panic_test { + args: "run run/wasm_streaming_panic_test.js", + output: "run/wasm_streaming_panic_test.js.out", + exit_code: 1, + }); + + // Regression test for https://github.com/denoland/deno/issues/13897. + itest!(fetch_async_error_stack { + args: "run --quiet -A run/fetch_async_error_stack.ts", + output: "run/fetch_async_error_stack.ts.out", + exit_code: 1, + }); + + itest!(unstable_ffi_1 { + args: "run run/ffi/unstable_ffi_1.js", + output: "run/ffi/unstable_ffi_1.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_2 { + args: "run run/ffi/unstable_ffi_2.js", + output: "run/ffi/unstable_ffi_2.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_3 { + args: "run run/ffi/unstable_ffi_3.js", + output: "run/ffi/unstable_ffi_3.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_4 { + args: "run run/ffi/unstable_ffi_4.js", + output: "run/ffi/unstable_ffi_4.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_5 { + args: "run run/ffi/unstable_ffi_5.js", + output: "run/ffi/unstable_ffi_5.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_6 { + args: "run run/ffi/unstable_ffi_6.js", + output: "run/ffi/unstable_ffi_6.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_7 { + args: "run run/ffi/unstable_ffi_7.js", + output: "run/ffi/unstable_ffi_7.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_8 { + args: "run run/ffi/unstable_ffi_8.js", + output: "run/ffi/unstable_ffi_8.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_9 { + args: "run run/ffi/unstable_ffi_9.js", + output: "run/ffi/unstable_ffi_9.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_10 { + args: "run run/ffi/unstable_ffi_10.js", + output: "run/ffi/unstable_ffi_10.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_11 { + args: "run run/ffi/unstable_ffi_11.js", + output: "run/ffi/unstable_ffi_11.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_12 { + args: "run run/ffi/unstable_ffi_12.js", + output: "run/ffi/unstable_ffi_12.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_13 { + args: "run run/ffi/unstable_ffi_13.js", + output: "run/ffi/unstable_ffi_13.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_14 { + args: "run run/ffi/unstable_ffi_14.js", + output: "run/ffi/unstable_ffi_14.js.out", + exit_code: 70, + }); + + itest!(unstable_ffi_15 { + args: "run run/ffi/unstable_ffi_15.js", + output: "run/ffi/unstable_ffi_15.js.out", + exit_code: 70, + }); + + itest!(future_check2 { + args: "run --check run/future_check.ts", + output: "run/future_check2.out", + }); + + itest!(event_listener_error { + args: "run --quiet run/event_listener_error.ts", + output: "run/event_listener_error.ts.out", + exit_code: 1, + }); + + itest!(event_listener_error_handled { + args: "run --quiet run/event_listener_error_handled.ts", + output: "run/event_listener_error_handled.ts.out", + }); + + // https://github.com/denoland/deno/pull/14159#issuecomment-1092285446 + itest!(event_listener_error_immediate_exit { + args: "run --quiet run/event_listener_error_immediate_exit.ts", + output: "run/event_listener_error_immediate_exit.ts.out", + exit_code: 1, + }); + + // https://github.com/denoland/deno/pull/14159#issuecomment-1092285446 + itest!(event_listener_error_immediate_exit_worker { + args: + "run --quiet --unstable -A run/event_listener_error_immediate_exit_worker.ts", + output: "run/event_listener_error_immediate_exit_worker.ts.out", + exit_code: 1, +}); + + itest!(set_timeout_error { + args: "run --quiet run/set_timeout_error.ts", + output: "run/set_timeout_error.ts.out", + exit_code: 1, + }); + + itest!(set_timeout_error_handled { + args: "run --quiet run/set_timeout_error_handled.ts", + output: "run/set_timeout_error_handled.ts.out", + }); + + itest!(aggregate_error { + args: "run --quiet run/aggregate_error.ts", + output: "run/aggregate_error.out", + exit_code: 1, + }); + + itest!(complex_error { + args: "run --quiet run/complex_error.ts", + output: "run/complex_error.ts.out", + exit_code: 1, + }); + + // Regression test for https://github.com/denoland/deno/issues/12143. + itest!(js_root_with_ts_check { + args: "run --quiet --check run/js_root_with_ts_check.js", + output: "run/js_root_with_ts_check.js.out", + exit_code: 1, + }); + + #[test] + fn check_local_then_remote() { + let _http_guard = util::http_server(); + let deno_dir = util::new_deno_dir(); + let output = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--check") + .arg("run/remote_type_error/main.ts") + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + let output = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--check=all") + .arg("run/remote_type_error/main.ts") + .env("NO_COLOR", "1") + .stderr(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + let stderr = std::str::from_utf8(&output.stderr).unwrap(); + assert_contains!( + stderr, + "Type 'string' is not assignable to type 'number'." + ); + } + + // Regression test for https://github.com/denoland/deno/issues/15163 + itest!(check_js_points_to_ts { + args: "run --quiet --check --config run/checkjs.tsconfig.json run/check_js_points_to_ts/test.js", + output: "run/check_js_points_to_ts/test.js.out", + exit_code: 1, +}); + + itest!(no_prompt_flag { + args: "run --quiet --unstable --no-prompt run/no_prompt.ts", + output_str: Some(""), + }); + + #[test] + fn deno_no_prompt_environment_variable() { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--unstable") + .arg("run/no_prompt.ts") + .env("DENO_NO_PROMPT", "1") + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + } + + itest!(report_error { + args: "run --quiet run/report_error.ts", + output: "run/report_error.ts.out", + exit_code: 1, + }); + + itest!(report_error_handled { + args: "run --quiet run/report_error_handled.ts", + output: "run/report_error_handled.ts.out", + }); + + // Regression test for https://github.com/denoland/deno/issues/15513. + itest!(report_error_end_of_program { + args: "run --quiet run/report_error_end_of_program.ts", + output: "run/report_error_end_of_program.ts.out", + exit_code: 1, + }); + + itest!(queue_microtask_error { + args: "run --quiet run/queue_microtask_error.ts", + output: "run/queue_microtask_error.ts.out", + exit_code: 1, + }); + + itest!(queue_microtask_error_handled { + args: "run --quiet run/queue_microtask_error_handled.ts", + output: "run/queue_microtask_error_handled.ts.out", + }); + + itest!(spawn_stdout_inherit { + args: "run --quiet --unstable -A run/spawn_stdout_inherit.ts", + output: "run/spawn_stdout_inherit.ts.out", + }); + + itest!(error_name_non_string { + args: "run --quiet run/error_name_non_string.js", + output: "run/error_name_non_string.js.out", + exit_code: 1, + }); + + itest!(custom_inspect_url { + args: "run run/custom_inspect_url.js", + output: "run/custom_inspect_url.js.out", + }); + + itest!(config_json_import { + args: "run --quiet -c jsx/deno-jsx.json run/config_json_import.ts", + output: "run/config_json_import.ts.out", + http_server: true, + }); + + #[test] + fn running_declaration_files() { + let temp_dir = TempDir::new(); + let files = vec!["file.d.ts", "file.d.cts", "file.d.mts"]; + + for file in files { + temp_dir.write(file, ""); + let mut deno_cmd = util::deno_cmd_with_deno_dir(&temp_dir); + let output = deno_cmd + .current_dir(temp_dir.path()) + .args(["run", file]) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(output.status.success()); + } + } + + itest!(test_and_bench_are_noops_in_run { + args: "run run/test_and_bench_in_run.js", + output_str: Some(""), + }); + + itest!(followup_dyn_import_resolved { + args: + "run --unstable --allow-read run/followup_dyn_import_resolves/main.ts", + output: "run/followup_dyn_import_resolves/main.ts.out", + }); + + itest!(unhandled_rejection { + args: "run --check run/unhandled_rejection.ts", + output: "run/unhandled_rejection.ts.out", + }); + + itest!(unhandled_rejection_sync_error { + args: "run --check run/unhandled_rejection_sync_error.ts", + output: "run/unhandled_rejection_sync_error.ts.out", + }); + + itest!(nested_error { + args: "run run/nested_error.ts", + output: "run/nested_error.ts.out", + exit_code: 1, + }); + + itest!(node_env_var_allowlist { + args: "run --unstable --no-prompt run/node_env_var_allowlist.ts", + output: "run/node_env_var_allowlist.ts.out", + exit_code: 1, + }); + + #[test] + fn cache_test() { + let _g = util::http_server(); + let deno_dir = TempDir::new(); + let module_url = + url::Url::parse("http://localhost:4545/run/006_url_imports.ts").unwrap(); + let output = Command::new(util::deno_exe_path()) + .env("DENO_DIR", deno_dir.path()) + .current_dir(util::testdata_path()) + .arg("cache") + .arg("--check=all") + .arg("-L") + .arg("debug") + .arg(module_url.to_string()) + .output() + .expect("Failed to spawn script"); + assert!(output.status.success()); + + let prg = util::deno_exe_path(); + let output = Command::new(&prg) + .env("DENO_DIR", deno_dir.path()) + .env("HTTP_PROXY", "http://nil") + .env("NO_COLOR", "1") + .current_dir(util::testdata_path()) + .arg("run") + .arg(module_url.to_string()) + .output() + .expect("Failed to spawn script"); + + let str_output = std::str::from_utf8(&output.stdout).unwrap(); + + let module_output_path = + util::testdata_path().join("run/006_url_imports.ts.out"); + let mut module_output = String::new(); + let mut module_output_file = + std::fs::File::open(module_output_path).unwrap(); + module_output_file + .read_to_string(&mut module_output) + .unwrap(); + + assert_eq!(module_output, str_output); + } + + #[test] + fn cache_invalidation_test() { + let deno_dir = TempDir::new(); + let fixture_path = deno_dir.path().join("fixture.ts"); + { + let mut file = std::fs::File::create(fixture_path.clone()) + .expect("could not create fixture"); + file + .write_all(b"console.log(\"42\");") + .expect("could not write fixture"); + } + let output = Command::new(util::deno_exe_path()) + .env("DENO_DIR", deno_dir.path()) + .current_dir(util::testdata_path()) + .arg("run") + .arg(fixture_path.to_str().unwrap()) + .output() + .expect("Failed to spawn script"); + assert!(output.status.success()); + let actual = std::str::from_utf8(&output.stdout).unwrap(); + assert_eq!(actual, "42\n"); + { + let mut file = std::fs::File::create(fixture_path.clone()) + .expect("could not create fixture"); + file + .write_all(b"console.log(\"43\");") + .expect("could not write fixture"); + } + let output = Command::new(util::deno_exe_path()) + .env("DENO_DIR", deno_dir.path()) + .current_dir(util::testdata_path()) + .arg("run") + .arg(fixture_path.to_str().unwrap()) + .output() + .expect("Failed to spawn script"); + assert!(output.status.success()); + let actual = std::str::from_utf8(&output.stdout).unwrap(); + assert_eq!(actual, "43\n"); + } + + #[test] + fn cache_invalidation_test_no_check() { + let deno_dir = TempDir::new(); + let fixture_path = deno_dir.path().join("fixture.ts"); + { + let mut file = std::fs::File::create(fixture_path.clone()) + .expect("could not create fixture"); + file + .write_all(b"console.log(\"42\");") + .expect("could not write fixture"); + } + let output = Command::new(util::deno_exe_path()) + .env("DENO_DIR", deno_dir.path()) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--no-check") + .arg(fixture_path.to_str().unwrap()) + .output() + .expect("Failed to spawn script"); + assert!(output.status.success()); + let actual = std::str::from_utf8(&output.stdout).unwrap(); + assert_eq!(actual, "42\n"); + { + let mut file = std::fs::File::create(fixture_path.clone()) + .expect("could not create fixture"); + file + .write_all(b"console.log(\"43\");") + .expect("could not write fixture"); + } + let output = Command::new(util::deno_exe_path()) + .env("DENO_DIR", deno_dir.path()) + .current_dir(util::testdata_path()) + .arg("run") + .arg("--no-check") + .arg(fixture_path.to_str().unwrap()) + .output() + .expect("Failed to spawn script"); + assert!(output.status.success()); + let actual = std::str::from_utf8(&output.stdout).unwrap(); + assert_eq!(actual, "43\n"); + } + + #[test] + fn ts_dependency_recompilation() { + let t = TempDir::new(); + let ats = t.path().join("a.ts"); + + std::fs::write( + &ats, + " + import { foo } from \"./b.ts\"; + + function print(str: string): void { + console.log(str); + } + + print(foo);", + ) + .unwrap(); + + let bts = t.path().join("b.ts"); + std::fs::write( + &bts, + " + export const foo = \"foo\";", + ) + .unwrap(); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .env("NO_COLOR", "1") + .arg("run") + .arg("--check") + .arg(&ats) + .output() + .expect("failed to spawn script"); + + let stdout_output = std::str::from_utf8(&output.stdout).unwrap().trim(); + let stderr_output = std::str::from_utf8(&output.stderr).unwrap().trim(); + + assert!(stdout_output.ends_with("foo")); + assert!(stderr_output.starts_with("Check")); + + // Overwrite contents of b.ts and run again + std::fs::write( + &bts, + " + export const foo = 5;", + ) + .expect("error writing file"); + + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .env("NO_COLOR", "1") + .arg("run") + .arg("--check") + .arg(&ats) + .output() + .expect("failed to spawn script"); + + let stdout_output = std::str::from_utf8(&output.stdout).unwrap().trim(); + let stderr_output = std::str::from_utf8(&output.stderr).unwrap().trim(); + + // error: TS2345 [ERROR]: Argument of type '5' is not assignable to parameter of type 'string'. + assert!(stderr_output.contains("TS2345")); + assert!(!output.status.success()); + assert!(stdout_output.is_empty()); + } + + #[test] + fn basic_auth_tokens() { + let _g = util::http_server(); + + let output = util::deno_cmd() + .current_dir(util::root_path()) + .arg("run") + .arg("http://127.0.0.1:4554/run/001_hello.js") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + + assert!(!output.status.success()); + + let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); + assert!(stdout_str.is_empty()); + + let stderr_str = std::str::from_utf8(&output.stderr).unwrap().trim(); + eprintln!("{}", stderr_str); + + assert!(stderr_str.contains( + "Module not found \"http://127.0.0.1:4554/run/001_hello.js\"." + )); + + let output = util::deno_cmd() + .current_dir(util::root_path()) + .arg("run") + .arg("http://127.0.0.1:4554/run/001_hello.js") + .env("DENO_AUTH_TOKENS", "testuser123:testpassabc@127.0.0.1:4554") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + + let stderr_str = std::str::from_utf8(&output.stderr).unwrap().trim(); + eprintln!("{}", stderr_str); + + assert!(output.status.success()); + + let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); + assert_eq!(util::strip_ansi_codes(stdout_str), "Hello World"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_resolve_dns() { + use std::net::SocketAddr; + use std::str::FromStr; + use std::sync::Arc; + use std::time::Duration; + use tokio::net::TcpListener; + use tokio::net::UdpSocket; + use tokio::sync::oneshot; + use trust_dns_server::authority::Catalog; + use trust_dns_server::authority::ZoneType; + use trust_dns_server::proto::rr::Name; + use trust_dns_server::store::in_memory::InMemoryAuthority; + use trust_dns_server::ServerFuture; + + const DNS_PORT: u16 = 4553; + + // Setup DNS server for testing + async fn run_dns_server(tx: oneshot::Sender<()>) { + let zone_file = std::fs::read_to_string( + util::testdata_path().join("run/resolve_dns.zone.in"), + ) + .unwrap(); + let lexer = Lexer::new(&zone_file); + let records = Parser::new().parse( + lexer, + Some(Name::from_str("example.com").unwrap()), + None, + ); + if records.is_err() { + panic!("failed to parse: {:?}", records.err()) + } + let (origin, records) = records.unwrap(); + let authority = Box::new(Arc::new( + InMemoryAuthority::new(origin, records, ZoneType::Primary, false) + .unwrap(), + )); + let mut catalog: Catalog = Catalog::new(); + catalog.upsert(Name::root().into(), authority); + + let mut server_fut = ServerFuture::new(catalog); + let socket_addr = SocketAddr::from(([127, 0, 0, 1], DNS_PORT)); + let tcp_listener = TcpListener::bind(socket_addr).await.unwrap(); + let udp_socket = UdpSocket::bind(socket_addr).await.unwrap(); + server_fut.register_socket(udp_socket); + server_fut.register_listener(tcp_listener, Duration::from_secs(2)); + + // Notifies that the DNS server is ready + tx.send(()).unwrap(); + + server_fut.block_until_done().await.unwrap(); + } + + let (ready_tx, ready_rx) = oneshot::channel(); + let dns_server_fut = run_dns_server(ready_tx); + let handle = tokio::spawn(dns_server_fut); + + // Waits for the DNS server to be ready + ready_rx.await.unwrap(); + + // Pass: `--allow-net` + { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .env("NO_COLOR", "1") + .arg("run") + .arg("--check") + .arg("--allow-net") + .arg("run/resolve_dns.ts") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + let err = String::from_utf8_lossy(&output.stderr); + let out = String::from_utf8_lossy(&output.stdout); + println!("{}", err); + assert!(output.status.success()); + assert!(err.starts_with("Check file")); + + let expected = std::fs::read_to_string( + util::testdata_path().join("run/resolve_dns.ts.out"), + ) + .unwrap(); + assert_eq!(expected, out); + } + + // Pass: `--allow-net=127.0.0.1:4553` + { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .env("NO_COLOR", "1") + .arg("run") + .arg("--check") + .arg("--allow-net=127.0.0.1:4553") + .arg("run/resolve_dns.ts") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + let err = String::from_utf8_lossy(&output.stderr); + let out = String::from_utf8_lossy(&output.stdout); + assert!(output.status.success()); + assert!(err.starts_with("Check file")); + + let expected = std::fs::read_to_string( + util::testdata_path().join("run/resolve_dns.ts.out"), + ) + .unwrap(); + assert_eq!(expected, out); + } + + // Permission error: `--allow-net=deno.land` + { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .env("NO_COLOR", "1") + .arg("run") + .arg("--check") + .arg("--allow-net=deno.land") + .arg("run/resolve_dns.ts") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + let err = String::from_utf8_lossy(&output.stderr); + let out = String::from_utf8_lossy(&output.stdout); + assert!(!output.status.success()); + assert!(err.starts_with("Check file")); + assert!(err.contains(r#"error: Uncaught PermissionDenied: Requires net access to "127.0.0.1:4553""#)); + assert!(out.is_empty()); + } + + // Permission error: no permission specified + { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .env("NO_COLOR", "1") + .arg("run") + .arg("--check") + .arg("run/resolve_dns.ts") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + let err = String::from_utf8_lossy(&output.stderr); + let out = String::from_utf8_lossy(&output.stdout); + assert!(!output.status.success()); + assert!(err.starts_with("Check file")); + assert!(err.contains(r#"error: Uncaught PermissionDenied: Requires net access to "127.0.0.1:4553""#)); + assert!(out.is_empty()); + } + + handle.abort(); + } + + #[tokio::test] + async fn http2_request_url() { + // TLS streams require the presence of an ambient local task set to gracefully + // close dropped connections in the background. + LocalSet::new() + .run_until(async { + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--unstable") + .arg("--quiet") + .arg("--allow-net") + .arg("--allow-read") + .arg("./run/http2_request_url.ts") + .arg("4506") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let stdout = child.stdout.as_mut().unwrap(); + let mut buffer = [0; 5]; + let read = stdout.read(&mut buffer).unwrap(); + assert_eq!(read, 5); + let msg = std::str::from_utf8(&buffer).unwrap(); + assert_eq!(msg, "READY"); + + let cert = reqwest::Certificate::from_pem(include_bytes!( + "./testdata/tls/RootCA.crt" + )) + .unwrap(); + + let client = reqwest::Client::builder() + .add_root_certificate(cert) + .http2_prior_knowledge() + .build() + .unwrap(); + + let res = client.get("http://127.0.0.1:4506").send().await.unwrap(); + assert_eq!(200, res.status()); + + let body = res.text().await.unwrap(); + assert_eq!(body, "http://127.0.0.1:4506/"); + + child.kill().unwrap(); + child.wait().unwrap(); + }) + .await; + } + + #[cfg(not(windows))] + #[test] + fn set_raw_should_not_panic_on_no_tty() { + let output = util::deno_cmd() + .arg("eval") + .arg("Deno.stdin.setRaw(true)") + // stdin set to piped so it certainly does not refer to TTY + .stdin(std::process::Stdio::piped()) + // stderr is piped so we can capture output. + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + let stderr = std::str::from_utf8(&output.stderr).unwrap().trim(); + assert!(stderr.contains("BadResource")); + } + + #[test] + fn timeout_clear() { + // https://github.com/denoland/deno/issues/7599 + + use std::time::Duration; + use std::time::Instant; + + let source_code = r#" +const handle = setTimeout(() => { + console.log("timeout finish"); +}, 10000); +clearTimeout(handle); +console.log("finish"); +"#; + + let mut p = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("-") + .stdin(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let stdin = p.stdin.as_mut().unwrap(); + stdin.write_all(source_code.as_bytes()).unwrap(); + let start = Instant::now(); + let status = p.wait().unwrap(); + let end = Instant::now(); + assert!(status.success()); + // check that program did not run for 10 seconds + // for timeout to clear + assert!(end - start < Duration::new(10, 0)); + } + + #[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::testdata_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!(error_cause { + args: "run run/error_cause.ts", + output: "run/error_cause.ts.out", + exit_code: 1, + }); + + itest!(error_cause_recursive_aggregate { + args: "run error_cause_recursive_aggregate.ts", + output: "error_cause_recursive_aggregate.ts.out", + exit_code: 1, + }); + + itest!(error_cause_recursive_tail { + args: "run error_cause_recursive_tail.ts", + output: "error_cause_recursive_tail.ts.out", + exit_code: 1, + }); + + itest!(error_cause_recursive { + args: "run run/error_cause_recursive.ts", + output: "run/error_cause_recursive.ts.out", + exit_code: 1, + }); + + #[test] + fn websocket() { + let _g = util::http_server(); + + let script = util::testdata_path().join("run/websocket_test.ts"); + let root_ca = util::testdata_path().join("tls/RootCA.pem"); + let status = util::deno_cmd() + .arg("test") + .arg("--unstable") + .arg("--allow-net") + .arg("--cert") + .arg(root_ca) + .arg(script) + .spawn() + .unwrap() + .wait() + .unwrap(); + + assert!(status.success()); + } + + #[ignore] + #[test] + fn websocketstream() { + let _g = util::http_server(); + + let script = util::testdata_path().join("run/websocketstream_test.ts"); + let root_ca = util::testdata_path().join("tls/RootCA.pem"); + let status = util::deno_cmd() + .arg("test") + .arg("--unstable") + .arg("--allow-net") + .arg("--cert") + .arg(root_ca) + .arg(script) + .spawn() + .unwrap() + .wait() + .unwrap(); + + assert!(status.success()); + } + + #[test] + fn websocketstream_ping() { + use deno_runtime::deno_websocket::tokio_tungstenite::tungstenite; + let _g = util::http_server(); + + let script = util::testdata_path().join("run/websocketstream_ping_test.ts"); + let root_ca = util::testdata_path().join("tls/RootCA.pem"); + let mut child = util::deno_cmd() + .arg("test") + .arg("--unstable") + .arg("--allow-net") + .arg("--cert") + .arg(root_ca) + .arg(script) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let server = std::net::TcpListener::bind("127.0.0.1:4513").unwrap(); + let (stream, _) = server.accept().unwrap(); + let mut socket = tungstenite::accept(stream).unwrap(); + socket + .write_message(tungstenite::Message::Text(String::from("A"))) + .unwrap(); + socket + .write_message(tungstenite::Message::Ping(vec![])) + .unwrap(); + socket + .write_message(tungstenite::Message::Text(String::from("B"))) + .unwrap(); + let message = socket.read_message().unwrap(); + assert_eq!(message, tungstenite::Message::Pong(vec![])); + socket + .write_message(tungstenite::Message::Text(String::from("C"))) + .unwrap(); + socket.close(None).unwrap(); + + assert!(child.wait().unwrap().success()); + } + + #[test] + fn websocket_server_multi_field_connection_header() { + let script = util::testdata_path() + .join("run/websocket_server_multi_field_connection_header_test.ts"); + let root_ca = util::testdata_path().join("tls/RootCA.pem"); + let mut child = util::deno_cmd() + .arg("run") + .arg("--unstable") + .arg("--allow-net") + .arg("--cert") + .arg(root_ca) + .arg(script) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let stdout = child.stdout.as_mut().unwrap(); + let mut buffer = [0; 5]; + let read = stdout.read(&mut buffer).unwrap(); + assert_eq!(read, 5); + let msg = std::str::from_utf8(&buffer).unwrap(); + assert_eq!(msg, "READY"); + + let req = http::request::Builder::new() + .header(http::header::CONNECTION, "keep-alive, Upgrade") + .uri("ws://localhost:4319") + .body(()) + .unwrap(); + let (mut socket, _) = + deno_runtime::deno_websocket::tokio_tungstenite::tungstenite::connect( + req, + ) + .unwrap(); + let message = socket.read_message().unwrap(); + assert_eq!(message, deno_runtime::deno_websocket::tokio_tungstenite::tungstenite::Message::Close(None)); + socket.close(None).unwrap(); + assert!(child.wait().unwrap().success()); + } + + // TODO(bartlomieju): this should use `deno run`, not `deno test`; but the + // test hangs then. https://github.com/denoland/deno/issues/14283 + #[test] + #[ignore] + fn websocket_server_idletimeout() { + let script = + util::testdata_path().join("run/websocket_server_idletimeout.ts"); + let root_ca = util::testdata_path().join("tls/RootCA.pem"); + let mut child = util::deno_cmd() + .arg("test") + .arg("--unstable") + .arg("--allow-net") + .arg("--cert") + .arg(root_ca) + .arg(script) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let stdout = child.stdout.as_mut().unwrap(); + let mut buffer = [0; 5]; + let read = stdout.read(&mut buffer).unwrap(); + assert_eq!(read, 5); + let msg = std::str::from_utf8(&buffer).unwrap(); + assert_eq!(msg, "READY"); + + let req = http::request::Builder::new() + .uri("ws://localhost:4509") + .body(()) + .unwrap(); + let (_ws, _request) = + deno_runtime::deno_websocket::tokio_tungstenite::tungstenite::connect( + req, + ) + .unwrap(); + + assert!(child.wait().unwrap().success()); + } + + itest!(auto_discover_lockfile { + args: "run run/auto_discover_lockfile/main.ts", + output: "run/auto_discover_lockfile/main.out", + http_server: true, + exit_code: 10, + }); + + itest!(no_lock_flag { + args: "run --no-lock run/no_lock_flag/main.ts", + output: "run/no_lock_flag/main.out", + http_server: true, + exit_code: 0, + }); + + // Check https://github.com/denoland/deno_std/issues/2882 + itest!(flash_shutdown { + args: "run --unstable --allow-net run/flash_shutdown/main.ts", + exit_code: 0, + }); + + itest!(permission_args { + args: "run run/001_hello.js --allow-net", + output: "run/permission_args.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + }); + + itest!(permission_args_quiet { + args: "run --quiet run/001_hello.js --allow-net", + output: "run/001_hello.js.out", + }); +} diff --git a/cli/tests/task_tests.rs b/cli/tests/task_tests.rs new file mode 100644 index 0000000000..0280391da4 --- /dev/null +++ b/cli/tests/task_tests.rs @@ -0,0 +1,136 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +// Most of the tests for this are in deno_task_shell. +// These tests are intended to only test integration. + +mod task { + use super::*; + + itest!(task_no_args { + args: "task -q --config task/deno.json", + output: "task/task_no_args.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + exit_code: 1, + }); + + itest!(task_cwd { + args: "task -q --config task/deno.json --cwd .. echo_cwd", + output: "task/task_cwd.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + exit_code: 0, + }); + + itest!(task_init_cwd { + args: "task -q --config task/deno.json --cwd .. echo_init_cwd", + output: "task/task_init_cwd.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + exit_code: 0, + }); + + itest!(task_init_cwd_already_set { + args: "task -q --config task/deno.json echo_init_cwd", + output: "task/task_init_cwd_already_set.out", + envs: vec![ + ("NO_COLOR".to_string(), "1".to_string()), + ("INIT_CWD".to_string(), "HELLO".to_string()) + ], + exit_code: 0, + }); + + itest!(task_cwd_resolves_config_from_specified_dir { + args: "task -q --cwd task", + output: "task/task_no_args.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + exit_code: 1, + }); + + itest!(task_non_existent { + args: "task --config task/deno.json non_existent", + output: "task/task_non_existent.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + exit_code: 1, + }); + + #[test] + fn task_emoji() { + // this bug only appears when using a pty/tty + let args = "task --config task/deno.json echo_emoji"; + use test_util::PtyData::*; + test_util::test_pty2(args, vec![Output("Task echo_emoji echo 🔥\r\n🔥")]); + } + + itest!(task_boolean_logic { + args: "task -q --config task/deno.json boolean_logic", + output: "task/task_boolean_logic.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + }); + + itest!(task_exit_code_5 { + args: "task --config task/deno.json exit_code_5", + output: "task/task_exit_code_5.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + exit_code: 5, + }); + + itest!(task_additional_args { + args: "task -q --config task/deno.json echo 2", + output: "task/task_additional_args.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + }); + + itest!(task_additional_args_no_shell_expansion { + args_vec: vec![ + "task", + "-q", + "--config", + "task/deno.json", + "echo", + "$(echo 5)" + ], + output: "task/task_additional_args_no_shell_expansion.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + }); + + itest!(task_additional_args_nested_strings { + args_vec: vec![ + "task", + "-q", + "--config", + "task/deno.json", + "echo", + "string \"quoted string\"" + ], + output: "task/task_additional_args_nested_strings.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + }); + + itest!(task_additional_args_no_logic { + args_vec: vec![ + "task", + "-q", + "--config", + "task/deno.json", + "echo", + "||", + "echo", + "5" + ], + output: "task/task_additional_args_no_logic.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + }); + + itest!(task_deno_exe_no_env { + args_vec: vec!["task", "-q", "--config", "task/deno.json", "deno_echo"], + output: "task/task_deno_exe_no_env.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + env_clear: true, + }); + + itest!(task_piped_stdin { + args_vec: vec!["task", "-q", "--config", "task/deno.json", "piped"], + output: "task/task_piped_stdin.out", + envs: vec![("NO_COLOR".to_string(), "1".to_string())], + }); +} diff --git a/cli/tests/test_tests.rs b/cli/tests/test_tests.rs new file mode 100644 index 0000000000..c8fa5b8e51 --- /dev/null +++ b/cli/tests/test_tests.rs @@ -0,0 +1,459 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; +use deno_core::url::Url; +use test_util as util; + +mod test { + use super::*; + + #[test] + fn no_color() { + let (out, _) = util::run_and_collect_output( + false, + "test test/no_color.ts", + None, + Some(vec![("NO_COLOR".to_owned(), "true".to_owned())]), + false, + ); + // ANSI escape codes should be stripped. + assert!(out.contains("success ... ok")); + assert!(out.contains("fail ... FAILED")); + assert!(out.contains("ignored ... ignored")); + assert!(out.contains("FAILED | 1 passed | 1 failed | 1 ignored")); + } + + itest!(overloads { + args: "test test/overloads.ts", + exit_code: 0, + output: "test/overloads.out", + }); + + itest!(meta { + args: "test test/meta.ts", + exit_code: 0, + output: "test/meta.out", + }); + + itest!(pass { + args: "test test/pass.ts", + exit_code: 0, + output: "test/pass.out", + }); + + itest!(ignore { + args: "test test/ignore.ts", + exit_code: 0, + output: "test/ignore.out", + }); + + itest!(ignore_permissions { + args: "test --unstable test/ignore_permissions.ts", + exit_code: 0, + output: "test/ignore_permissions.out", + }); + + itest!(fail { + args: "test test/fail.ts", + exit_code: 1, + output: "test/fail.out", + }); + + itest!(collect { + args: "test --ignore=test/collect/ignore test/collect", + exit_code: 0, + output: "test/collect.out", + }); + + itest!(test_with_config { + args: "test --config test/collect/deno.jsonc test/collect", + exit_code: 0, + output: "test/collect.out", + }); + + itest!(test_with_config2 { + args: "test --config test/collect/deno2.jsonc test/collect", + exit_code: 0, + output: "test/collect2.out", + }); + + itest!(test_with_malformed_config { + args: "test --config test/collect/deno.malformed.jsonc", + exit_code: 1, + output: "test/collect_with_malformed_config.out", + }); + + itest!(parallel_flag { + args: "test test/short-pass.ts --parallel", + exit_code: 0, + output: "test/short-pass.out", + }); + + itest!(parallel_flag_with_env_variable { + args: "test test/short-pass.ts --parallel", + envs: vec![("DENO_JOBS".to_owned(), "2".to_owned())], + exit_code: 0, + output: "test/short-pass.out", + }); + + itest!(jobs_flag { + args: "test test/short-pass.ts --jobs", + exit_code: 0, + output: "test/short-pass-jobs-flag-warning.out", + }); + + itest!(jobs_flag_with_numeric_value { + args: "test test/short-pass.ts --jobs=2", + exit_code: 0, + output: "test/short-pass-jobs-flag-warning.out", + }); + + itest!(load_unload { + args: "test test/load_unload.ts", + exit_code: 0, + output: "test/load_unload.out", + }); + + itest!(interval { + args: "test test/interval.ts", + exit_code: 0, + output: "test/interval.out", + }); + + itest!(doc { + args: "test --doc --allow-all test/doc.ts", + exit_code: 1, + output: "test/doc.out", + }); + + itest!(doc_only { + args: "test --doc --allow-all test/doc_only", + exit_code: 0, + output: "test/doc_only.out", + }); + + itest!(markdown { + args: "test --doc --allow-all test/markdown.md", + exit_code: 1, + output: "test/markdown.out", + }); + + itest!(markdown_windows { + args: "test --doc --allow-all test/markdown_windows.md", + exit_code: 1, + output: "test/markdown_windows.out", + }); + + itest!(markdown_full_block_names { + args: "test --doc --allow-all test/markdown_full_block_names.md", + exit_code: 1, + output: "test/markdown_full_block_names.out", + }); + + itest!(markdown_ignore_html_comment { + args: "test --doc --allow-all test/markdown_with_comment.md", + exit_code: 1, + output: "test/markdown_with_comment.out", + }); + + itest!(text { + args: "test --doc --allow-all test/text.md", + exit_code: 0, + output: "test/text.out", + }); + + itest!(quiet { + args: "test --quiet test/quiet.ts", + exit_code: 0, + output: "test/quiet.out", + }); + + itest!(fail_fast { + args: "test --fail-fast test/fail_fast.ts", + exit_code: 1, + output: "test/fail_fast.out", + }); + + itest!(only { + args: "test test/only.ts", + exit_code: 1, + output: "test/only.out", + }); + + itest!(no_check { + args: "test --no-check test/no_check.ts", + exit_code: 1, + output: "test/no_check.out", + }); + + itest!(no_run { + args: "test --unstable --no-run test/no_run.ts", + output: "test/no_run.out", + exit_code: 1, + }); + + itest!(allow_all { + args: "test --unstable --allow-all test/allow_all.ts", + exit_code: 0, + output: "test/allow_all.out", + }); + + itest!(allow_none { + args: "test --unstable test/allow_none.ts", + exit_code: 1, + output: "test/allow_none.out", + }); + + itest!(ops_sanitizer_unstable { + args: "test --unstable --trace-ops test/ops_sanitizer_unstable.ts", + exit_code: 1, + output: "test/ops_sanitizer_unstable.out", + }); + + itest!(ops_sanitizer_timeout_failure { + args: "test test/ops_sanitizer_timeout_failure.ts", + output: "test/ops_sanitizer_timeout_failure.out", + }); + + itest!(ops_sanitizer_multiple_timeout_tests { + args: "test --trace-ops test/ops_sanitizer_multiple_timeout_tests.ts", + exit_code: 1, + output: "test/ops_sanitizer_multiple_timeout_tests.out", + }); + + itest!(ops_sanitizer_multiple_timeout_tests_no_trace { + args: "test test/ops_sanitizer_multiple_timeout_tests.ts", + exit_code: 1, + output: "test/ops_sanitizer_multiple_timeout_tests_no_trace.out", + }); + + itest!(trace_ops_catch_error { + args: "test -A --trace-ops test/trace_ops_caught_error/main.ts", + exit_code: 0, + output: "test/trace_ops_caught_error/main.out", + }); + + // TODO(@littledivy): re-enable this test, recent optimizations made output non deterministic. + // https://github.com/denoland/deno/issues/14268 + // + // itest!(ops_sanitizer_missing_details { + // args: "test --allow-write --allow-read test/ops_sanitizer_missing_details.ts", + // exit_code: 1, + // output: "test/ops_sanitizer_missing_details.out", + // }); + + itest!(ops_sanitizer_nexttick { + args: "test test/ops_sanitizer_nexttick.ts", + output: "test/ops_sanitizer_nexttick.out", + }); + + itest!(resource_sanitizer { + args: "test --allow-read test/resource_sanitizer.ts", + exit_code: 1, + output: "test/resource_sanitizer.out", + }); + + itest!(exit_sanitizer { + args: "test test/exit_sanitizer.ts", + output: "test/exit_sanitizer.out", + exit_code: 1, + }); + + itest!(clear_timeout { + args: "test test/clear_timeout.ts", + exit_code: 0, + output: "test/clear_timeout.out", + }); + + itest!(finally_timeout { + args: "test test/finally_timeout.ts", + exit_code: 1, + output: "test/finally_timeout.out", + }); + + itest!(unresolved_promise { + args: "test test/unresolved_promise.ts", + exit_code: 1, + output: "test/unresolved_promise.out", + }); + + itest!(unhandled_rejection { + args: "test test/unhandled_rejection.ts", + exit_code: 1, + output: "test/unhandled_rejection.out", + }); + + itest!(filter { + args: "test --filter=foo test/filter", + exit_code: 0, + output: "test/filter.out", + }); + + itest!(shuffle { + args: "test --shuffle test/shuffle", + exit_code: 0, + output_str: Some("[WILDCARD]"), + }); + + itest!(shuffle_with_seed { + args: "test --shuffle=42 test/shuffle", + exit_code: 0, + output: "test/shuffle.out", + }); + + itest!(aggregate_error { + args: "test --quiet test/aggregate_error.ts", + exit_code: 1, + output: "test/aggregate_error.out", + }); + + itest!(steps_passing_steps { + args: "test test/steps/passing_steps.ts", + exit_code: 0, + output: "test/steps/passing_steps.out", + }); + + itest!(steps_failing_steps { + args: "test test/steps/failing_steps.ts", + exit_code: 1, + output: "test/steps/failing_steps.out", + }); + + itest!(steps_ignored_steps { + args: "test test/steps/ignored_steps.ts", + exit_code: 0, + output: "test/steps/ignored_steps.out", + }); + + itest!(steps_invalid_usage { + args: "test test/steps/invalid_usage.ts", + exit_code: 1, + output: "test/steps/invalid_usage.out", + }); + + itest!(steps_output_within { + args: "test test/steps/output_within.ts", + exit_code: 0, + output: "test/steps/output_within.out", + }); + + itest!(no_prompt_by_default { + args: "test --quiet test/no_prompt_by_default.ts", + exit_code: 1, + output: "test/no_prompt_by_default.out", + }); + + itest!(no_prompt_with_denied_perms { + args: "test --quiet --allow-read test/no_prompt_with_denied_perms.ts", + exit_code: 1, + output: "test/no_prompt_with_denied_perms.out", + }); + + itest!(test_with_custom_jsx { + args: "test --quiet --allow-read test/hello_world.ts --config=test/deno_custom_jsx.json", + exit_code: 0, + output: "test/hello_world.out", +}); + + #[test] + fn captured_output() { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("test") + .arg("--allow-run") + .arg("--allow-read") + .arg("--unstable") + .arg("test/captured_output.ts") + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + + let output_start = "------- output -------"; + let output_end = "----- output end -----"; + assert!(output.status.success()); + let output_text = String::from_utf8(output.stdout).unwrap(); + let start = output_text.find(output_start).unwrap() + output_start.len(); + let end = output_text.find(output_end).unwrap(); + // replace zero width space that may appear in test output due + // to test runner output flusher + let output_text = output_text[start..end] + .replace('\u{200B}', "") + .trim() + .to_string(); + let mut lines = output_text.lines().collect::>(); + // the output is racy on either stdout or stderr being flushed + // from the runtime into the rust code, so sort it... the main + // thing here to ensure is that we're capturing the output in + // this block on stdout + lines.sort_unstable(); + assert_eq!(lines.join(" "), "0 1 2 3 4 5 6 7 8 9"); + } + + #[test] + fn recursive_permissions_pledge() { + let output = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("test") + .arg("test/recursive_permissions_pledge.js") + .stderr(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + assert!(String::from_utf8(output.stderr).unwrap().contains( + "pledge test permissions called before restoring previous pledge" + )); + } + + #[test] + fn file_protocol() { + let file_url = + Url::from_file_path(util::testdata_path().join("test/file_protocol.ts")) + .unwrap() + .to_string(); + + (util::CheckOutputIntegrationTest { + args_vec: vec!["test", &file_url], + exit_code: 0, + output: "test/file_protocol.out", + ..Default::default() + }) + .run(); + } + + itest!(uncaught_errors { + args: "test --quiet test/uncaught_errors_1.ts test/uncaught_errors_2.ts test/uncaught_errors_3.ts", + output: "test/uncaught_errors.out", + exit_code: 1, +}); + + itest!(check_local_by_default { + args: "test --quiet test/check_local_by_default.ts", + output: "test/check_local_by_default.out", + http_server: true, + }); + + itest!(check_local_by_default2 { + args: "test --quiet test/check_local_by_default2.ts", + output: "test/check_local_by_default2.out", + http_server: true, + exit_code: 1, + }); + + itest!(non_error_thrown { + args: "test --quiet test/non_error_thrown.ts", + output: "test/non_error_thrown.out", + exit_code: 1, + }); + + itest!(parallel_output { + args: "test --parallel --reload test/parallel_output.ts", + output: "test/parallel_output.out", + exit_code: 1, + }); +} diff --git a/cli/tests/testdata/bench/unresolved_promise.out b/cli/tests/testdata/bench/unresolved_promise.out index d544d77e77..b601e9b70f 100644 --- a/cli/tests/testdata/bench/unresolved_promise.out +++ b/cli/tests/testdata/bench/unresolved_promise.out @@ -1,2 +1,5 @@ Check [WILDCARD]/bench/unresolved_promise.ts -error: Module evaluation is still pending but there are no pending ops or dynamic imports. This situation is often caused by unresolved promises. +error: Top-level await promise never resolved +await new Promise((_resolve, _reject) => {}); +^ + at ([WILDCARD]bench/unresolved_promise.ts:1:1) diff --git a/cli/tests/testdata/coverage/invalid_cache/mod.test.ts b/cli/tests/testdata/coverage/invalid_cache/mod.test.ts new file mode 100644 index 0000000000..5815d07a34 --- /dev/null +++ b/cli/tests/testdata/coverage/invalid_cache/mod.test.ts @@ -0,0 +1,2 @@ +import { test } from "./mod.ts"; +Deno.test("test", () => void test()); diff --git a/cli/tests/testdata/coverage/invalid_cache/mod_after.ts b/cli/tests/testdata/coverage/invalid_cache/mod_after.ts new file mode 100644 index 0000000000..294dc0843a --- /dev/null +++ b/cli/tests/testdata/coverage/invalid_cache/mod_after.ts @@ -0,0 +1,6 @@ +export function test() { + return 42; +} +if (import.meta.main) { + test(); +} diff --git a/cli/tests/testdata/coverage/invalid_cache/mod_before.ts b/cli/tests/testdata/coverage/invalid_cache/mod_before.ts new file mode 100644 index 0000000000..ea52ccbcee --- /dev/null +++ b/cli/tests/testdata/coverage/invalid_cache/mod_before.ts @@ -0,0 +1,15 @@ +export function test() { + console.log("1"); + console.log("2"); + console.log("3"); + console.log("4"); + console.log("5"); + console.log("6"); + console.log("7"); + console.log("8"); + console.log("9"); + return 42; +} +if (import.meta.main) { + test(); +} diff --git a/cli/tests/testdata/inspector/error_with_npm_import.js b/cli/tests/testdata/inspector/error_with_npm_import.js new file mode 100644 index 0000000000..9244f2cf2f --- /dev/null +++ b/cli/tests/testdata/inspector/error_with_npm_import.js @@ -0,0 +1,7 @@ +// deno-lint-ignore-file + +import chalk from "npm:chalk"; + +console.log("hello"); + +throw new Error("boom!"); diff --git a/cli/tests/testdata/lsp/selection_range_response.json b/cli/tests/testdata/lsp/selection_range_response.json index b5eef5ddce..c5a8b288e2 100644 --- a/cli/tests/testdata/lsp/selection_range_response.json +++ b/cli/tests/testdata/lsp/selection_range_response.json @@ -47,7 +47,7 @@ "range": { "start": { "line": 1, - "character": 2 + "character": 12 }, "end": { "line": 6, @@ -57,23 +57,35 @@ "parent": { "range": { "start": { - "line": 0, - "character": 11 + "line": 1, + "character": 2 }, "end": { - "line": 7, - "character": 0 + "line": 6, + "character": 3 } }, "parent": { "range": { "start": { "line": 0, - "character": 0 + "character": 11 }, "end": { "line": 7, - "character": 1 + "character": 0 + } + }, + "parent": { + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 7, + "character": 1 + } } } } diff --git a/cli/tests/testdata/npm/create_require/main.out b/cli/tests/testdata/npm/create_require/main.out index ebd96c120a..70b0415b3a 100644 --- a/cli/tests/testdata/npm/create_require/main.out +++ b/cli/tests/testdata/npm/create_require/main.out @@ -1,6 +1,12 @@ [WILDCARD] function function +function +function +function +function The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received https://example.com/ The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received https://example.com/ The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 1 +The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received foo +The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received ./foo diff --git a/cli/tests/testdata/npm/dynamic_import_reload_same_package/main.out b/cli/tests/testdata/npm/dynamic_import_reload_same_package/main.out new file mode 100644 index 0000000000..918e7f5e8f --- /dev/null +++ b/cli/tests/testdata/npm/dynamic_import_reload_same_package/main.out @@ -0,0 +1,5 @@ +Download http://localhost:4545/npm/registry/chalk +Download http://localhost:4545/npm/registry/chalk/chalk-5.0.1.tgz +Starting... +Ran other. +Finished... diff --git a/cli/tests/testdata/npm/dynamic_import_reload_same_package/main.ts b/cli/tests/testdata/npm/dynamic_import_reload_same_package/main.ts new file mode 100644 index 0000000000..7c7ee7d557 --- /dev/null +++ b/cli/tests/testdata/npm/dynamic_import_reload_same_package/main.ts @@ -0,0 +1,7 @@ +import chalk from "npm:chalk@5"; + +console.log(chalk.green("Starting...")); +// non-analyzable +const importName = "./other.ts"; +await import(importName); +console.log(chalk.green("Finished...")); diff --git a/cli/tests/testdata/npm/dynamic_import_reload_same_package/other.ts b/cli/tests/testdata/npm/dynamic_import_reload_same_package/other.ts new file mode 100644 index 0000000000..28e3da14ff --- /dev/null +++ b/cli/tests/testdata/npm/dynamic_import_reload_same_package/other.ts @@ -0,0 +1,3 @@ +import chalk from "npm:chalk@5"; + +console.log(chalk.green("Ran other.")); diff --git a/cli/tests/testdata/npm/no_types_cjs/main.ts b/cli/tests/testdata/npm/no_types_cjs/main.ts new file mode 100644 index 0000000000..32458e8393 --- /dev/null +++ b/cli/tests/testdata/npm/no_types_cjs/main.ts @@ -0,0 +1,7 @@ +import mod from "npm:@denotest/no-types-cjs"; + +// it actually returns a `number` and has that in its +// jsdocs, but the jsdocs should not have been resolved so +// this should type check just fine +const value: string = mod(); +console.log(value); diff --git a/cli/tests/testdata/npm/registry/@denotest/create-require/1.0.0/index.js b/cli/tests/testdata/npm/registry/@denotest/create-require/1.0.0/index.js index eaa3e5afdf..2ab5643660 100644 --- a/cli/tests/testdata/npm/registry/@denotest/create-require/1.0.0/index.js +++ b/cli/tests/testdata/npm/registry/@denotest/create-require/1.0.0/index.js @@ -2,6 +2,10 @@ import { createRequire } from "module"; console.log(typeof createRequire(import.meta.url)); console.log(typeof createRequire(new URL(import.meta.url))); +console.log(typeof createRequire("/")); +console.log(typeof createRequire("/foo")); +console.log(typeof createRequire("/foo/")); +console.log(typeof createRequire("c:\\foo")); try { createRequire("https://example.com/"); } catch (e) { @@ -17,3 +21,13 @@ try { } catch (e) { console.log(e.message); } +try { + createRequire("foo"); +} catch (e) { + console.log(e.message); +} +try { + createRequire("./foo"); +} catch (e) { + console.log(e.message); +} diff --git a/cli/tests/testdata/npm/registry/@denotest/no-types-cjs/1.0.0/main.js b/cli/tests/testdata/npm/registry/@denotest/no-types-cjs/1.0.0/main.js new file mode 100644 index 0000000000..bb6cbdb029 --- /dev/null +++ b/cli/tests/testdata/npm/registry/@denotest/no-types-cjs/1.0.0/main.js @@ -0,0 +1,6 @@ +/** + * @return {number} + */ + module.exports = function () { + return 5; +}; diff --git a/cli/tests/testdata/npm/registry/@denotest/no-types-cjs/1.0.0/package.json b/cli/tests/testdata/npm/registry/@denotest/no-types-cjs/1.0.0/package.json new file mode 100644 index 0000000000..60b8a0285e --- /dev/null +++ b/cli/tests/testdata/npm/registry/@denotest/no-types-cjs/1.0.0/package.json @@ -0,0 +1,5 @@ +{ + "name": "@denotest/no-types-cjs", + "version": "1.0.0", + "main": "./main.js" +} diff --git a/cli/tests/testdata/npm/registry/@denotest/types-exports-import-types/1.0.0/dist/main.d.ts b/cli/tests/testdata/npm/registry/@denotest/types-exports-import-types/1.0.0/dist/main.d.ts new file mode 100644 index 0000000000..2341a14f08 --- /dev/null +++ b/cli/tests/testdata/npm/registry/@denotest/types-exports-import-types/1.0.0/dist/main.d.ts @@ -0,0 +1 @@ +export function getValue(): 5; diff --git a/cli/tests/testdata/npm/registry/@denotest/types-exports-import-types/1.0.0/dist/main.mjs b/cli/tests/testdata/npm/registry/@denotest/types-exports-import-types/1.0.0/dist/main.mjs new file mode 100644 index 0000000000..358b4b09e5 --- /dev/null +++ b/cli/tests/testdata/npm/registry/@denotest/types-exports-import-types/1.0.0/dist/main.mjs @@ -0,0 +1,3 @@ +export function getValue() { + return 5; +} diff --git a/cli/tests/testdata/npm/registry/@denotest/types-exports-import-types/1.0.0/package.json b/cli/tests/testdata/npm/registry/@denotest/types-exports-import-types/1.0.0/package.json new file mode 100644 index 0000000000..202a2c784b --- /dev/null +++ b/cli/tests/testdata/npm/registry/@denotest/types-exports-import-types/1.0.0/package.json @@ -0,0 +1,10 @@ +{ + "name": "@denotest/types-exports-import-types", + "version": "1.0.0", + "exports": { + "node": { + "types": "./dist/main.d.ts", + "import": "./dist/main.mjs" + } + } +} diff --git a/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/dist/main.d.ts b/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/dist/main.d.ts index 2341a14f08..8942f08dda 100644 --- a/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/dist/main.d.ts +++ b/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/dist/main.d.ts @@ -1 +1 @@ -export function getValue(): 5; +export { getValue } from "@denotest/types-entry-value-not-exists"; diff --git a/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/dist/main.js b/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/dist/main.js index d0c5dbc70c..63c7ef0cee 100644 --- a/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/dist/main.js +++ b/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/dist/main.js @@ -1 +1 @@ -module.exports.getValue = () => 5; +module.exports.getValue = require("@denotest/types-entry-value-not-exists").getValue; diff --git a/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/package.json b/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/package.json index 377af2bae6..6abccec985 100644 --- a/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/package.json +++ b/cli/tests/testdata/npm/registry/@denotest/types-no-types-entry/1.0.0/package.json @@ -1,5 +1,8 @@ { "name": "@denotest/types-no-types-entry", "version": "1.0.0", - "main": "./dist/main.js" + "main": "./dist/main.js", + "dependencies": { + "@denotest/types-entry-value-not-exists": "^1.0" + } } diff --git a/cli/tests/testdata/npm/types_entry_value_not_exists/main.out b/cli/tests/testdata/npm/types_entry_value_not_exists/main.out index 0368578277..0bb31a195b 100644 --- a/cli/tests/testdata/npm/types_entry_value_not_exists/main.out +++ b/cli/tests/testdata/npm/types_entry_value_not_exists/main.out @@ -1,4 +1,7 @@ Download http://localhost:4545/npm/registry/@denotest/types-entry-value-not-exists Download http://localhost:4545/npm/registry/@denotest/types-entry-value-not-exists/1.0.0.tgz Check file://[WILDCARD]/types_entry_value_not_exists/main.ts -5 +error: TS2322 [ERROR]: Type 'number' is not assignable to type 'string'. +const result: string = getValue(); + ~~~~~~ + at file:///[WILDCARD]/main.ts:4:7 diff --git a/cli/tests/testdata/npm/types_entry_value_not_exists/main.ts b/cli/tests/testdata/npm/types_entry_value_not_exists/main.ts index d8fca712c9..04374ef878 100644 --- a/cli/tests/testdata/npm/types_entry_value_not_exists/main.ts +++ b/cli/tests/testdata/npm/types_entry_value_not_exists/main.ts @@ -1,4 +1,5 @@ import { getValue } from "npm:@denotest/types-entry-value-not-exists"; -const result: 5 = getValue(); +// should error here +const result: string = getValue(); console.log(result); diff --git a/cli/tests/testdata/npm/types_exports_import_types/main.out b/cli/tests/testdata/npm/types_exports_import_types/main.out new file mode 100644 index 0000000000..a3db009ca1 --- /dev/null +++ b/cli/tests/testdata/npm/types_exports_import_types/main.out @@ -0,0 +1,7 @@ +Download http://localhost:4545/npm/registry/@denotest/types-exports-import-types +Download http://localhost:4545/npm/registry/@denotest/types-exports-import-types/1.0.0.tgz +Check file://[WILDCARD]/types_exports_import_types/main.ts +error: TS2322 [ERROR]: Type 'number' is not assignable to type 'string'. +const result: string = getValue(); + ~~~~~~ + at file:///[WILDCARD]/main.ts:4:7 diff --git a/cli/tests/testdata/npm/types_exports_import_types/main.ts b/cli/tests/testdata/npm/types_exports_import_types/main.ts new file mode 100644 index 0000000000..3ae3e92a3c --- /dev/null +++ b/cli/tests/testdata/npm/types_exports_import_types/main.ts @@ -0,0 +1,5 @@ +import { getValue } from "npm:@denotest/types-exports-import-types"; + +// should error here +const result: string = getValue(); +console.log(result); diff --git a/cli/tests/testdata/npm/types_no_types_entry/main.out b/cli/tests/testdata/npm/types_no_types_entry/main.out index 6c5d45222d..429940fffa 100644 --- a/cli/tests/testdata/npm/types_no_types_entry/main.out +++ b/cli/tests/testdata/npm/types_no_types_entry/main.out @@ -1,4 +1,9 @@ Download http://localhost:4545/npm/registry/@denotest/types-no-types-entry +Download http://localhost:4545/npm/registry/@denotest/types-entry-value-not-exists +Download http://localhost:4545/npm/registry/@denotest/types-entry-value-not-exists/1.0.0.tgz Download http://localhost:4545/npm/registry/@denotest/types-no-types-entry/1.0.0.tgz Check file://[WILDCARD]/types_no_types_entry/main.ts -5 +error: TS2322 [ERROR]: Type 'number' is not assignable to type 'string'. +const result: string = getValue(); + ~~~~~~ + at file:///[WILDCARD]/main.ts:4:7 diff --git a/cli/tests/testdata/npm/types_no_types_entry/main.ts b/cli/tests/testdata/npm/types_no_types_entry/main.ts index 15e0604020..eef53b681b 100644 --- a/cli/tests/testdata/npm/types_no_types_entry/main.ts +++ b/cli/tests/testdata/npm/types_no_types_entry/main.ts @@ -1,4 +1,5 @@ import { getValue } from "npm:@denotest/types-no-types-entry"; -const result: 5 = getValue(); +// should error here +const result: string = getValue(); console.log(result); diff --git a/cli/tests/testdata/run/045_proxy_test.ts b/cli/tests/testdata/run/045_proxy_test.ts index 0ff7184b1e..f90c376490 100644 --- a/cli/tests/testdata/run/045_proxy_test.ts +++ b/cli/tests/testdata/run/045_proxy_test.ts @@ -31,7 +31,7 @@ async function handler(req: Request): Promise { } async function testFetch() { - const { code } = await Deno.spawn(Deno.execPath(), { + const { code } = await new Deno.Command(Deno.execPath(), { args: [ "run", "--quiet", @@ -42,13 +42,13 @@ async function testFetch() { env: { HTTP_PROXY: `http://${addr}`, }, - }); + }).output(); assertEquals(code, 0); } async function testModuleDownload() { - const { code } = await Deno.spawn(Deno.execPath(), { + const { code } = await new Deno.Command(Deno.execPath(), { args: [ "cache", "--reload", @@ -58,13 +58,13 @@ async function testModuleDownload() { env: { HTTP_PROXY: `http://${addr}`, }, - }); + }).output(); assertEquals(code, 0); } async function testFetchNoProxy() { - const { code } = await Deno.spawn(Deno.execPath(), { + const { code } = await new Deno.Command(Deno.execPath(), { args: [ "run", "--quiet", @@ -76,13 +76,13 @@ async function testFetchNoProxy() { HTTP_PROXY: "http://not.exising.proxy.server", NO_PROXY: "localhost", }, - }); + }).output(); assertEquals(code, 0); } async function testModuleDownloadNoProxy() { - const { code } = await Deno.spawn(Deno.execPath(), { + const { code } = await new Deno.Command(Deno.execPath(), { args: [ "cache", "--reload", @@ -93,13 +93,13 @@ async function testModuleDownloadNoProxy() { HTTP_PROXY: "http://not.exising.proxy.server", NO_PROXY: "localhost", }, - }); + }).output(); assertEquals(code, 0); } async function testFetchProgrammaticProxy() { - const { code } = await Deno.spawn(Deno.execPath(), { + const { code } = await new Deno.Command(Deno.execPath(), { args: [ "run", "--quiet", @@ -108,7 +108,7 @@ async function testFetchProgrammaticProxy() { "--unstable", "run/045_programmatic_proxy_client.ts", ], - }); + }).output(); assertEquals(code, 0); } diff --git a/cli/tests/testdata/run/089_run_allow_list.ts b/cli/tests/testdata/run/089_run_allow_list.ts index d7bc8e195f..d9cabba847 100644 --- a/cli/tests/testdata/run/089_run_allow_list.ts +++ b/cli/tests/testdata/run/089_run_allow_list.ts @@ -1,12 +1,12 @@ try { - await Deno.spawn("ls"); + await new Deno.Command("ls").output(); } catch (e) { console.log(e); } -const { success } = await Deno.spawn("curl", { +const { success } = await new Deno.Command("curl", { args: ["--help"], stdout: "null", stderr: "inherit", -}); +}).output(); console.log(success); diff --git a/cli/tests/testdata/run/lock_write_fetch/main.ts b/cli/tests/testdata/run/lock_write_fetch/main.ts index 3e6892cf02..57bc54d029 100644 --- a/cli/tests/testdata/run/lock_write_fetch/main.ts +++ b/cli/tests/testdata/run/lock_write_fetch/main.ts @@ -4,7 +4,7 @@ try { // pass } -const fetchProc = await Deno.spawn(Deno.execPath(), { +const fetchProc = await new Deno.Command(Deno.execPath(), { stdout: "null", stderr: "null", args: [ @@ -15,11 +15,11 @@ const fetchProc = await Deno.spawn(Deno.execPath(), { "--cert=tls/RootCA.pem", "run/https_import.ts", ], -}); +}).output(); console.log(`fetch code: ${fetchProc.code}`); -const fetchCheckProc = await Deno.spawn(Deno.execPath(), { +const fetchCheckProc = await new Deno.Command(Deno.execPath(), { stdout: "null", stderr: "null", args: [ @@ -28,13 +28,13 @@ const fetchCheckProc = await Deno.spawn(Deno.execPath(), { "--cert=tls/RootCA.pem", "run/https_import.ts", ], -}); +}).output(); console.log(`fetch check code: ${fetchCheckProc.code}`); Deno.removeSync("./lock_write_fetch.json"); -const runProc = await Deno.spawn(Deno.execPath(), { +const runProc = await new Deno.Command(Deno.execPath(), { stdout: "null", stderr: "null", args: [ @@ -45,7 +45,7 @@ const runProc = await Deno.spawn(Deno.execPath(), { "run/lock_write_fetch/file_exists.ts", "lock_write_fetch.json", ], -}); +}).output(); console.log(`run code: ${runProc.code}`); diff --git a/cli/tests/testdata/run/no_prompt.ts b/cli/tests/testdata/run/no_prompt.ts index 7f97509954..17d54b92c1 100644 --- a/cli/tests/testdata/run/no_prompt.ts +++ b/cli/tests/testdata/run/no_prompt.ts @@ -1,10 +1,10 @@ new Worker("data:,setTimeout(() => Deno.exit(2), 200)", { type: "module" }); try { - await Deno.spawn("ps", { + await new Deno.Command("ps", { stdout: "inherit", stderr: "inherit", - }); + }).output(); } catch { Deno.exit(0); } diff --git a/cli/tests/testdata/run/permission_test.ts b/cli/tests/testdata/run/permission_test.ts index 9b5409b4f2..a2312e3acf 100644 --- a/cli/tests/testdata/run/permission_test.ts +++ b/cli/tests/testdata/run/permission_test.ts @@ -16,9 +16,9 @@ const test: { [key: string]: (...args: any[]) => void | Promise } = { Deno.listen({ transport: "tcp", port: 4541 }); }, async runRequired() { - await Deno.spawn(Deno.build.os === "windows" ? "cmd.exe" : "printf", { + await new Deno.Command(Deno.build.os === "windows" ? "cmd.exe" : "printf", { args: Deno.build.os === "windows" ? ["/c", "echo hello"] : ["hello"], - }); + }).output(); }, }; diff --git a/cli/tests/testdata/run/spawn_stdout_inherit.ts b/cli/tests/testdata/run/spawn_stdout_inherit.ts index be5f9b7ef4..04f635ceae 100644 --- a/cli/tests/testdata/run/spawn_stdout_inherit.ts +++ b/cli/tests/testdata/run/spawn_stdout_inherit.ts @@ -1,8 +1,8 @@ -await Deno.spawn(Deno.execPath(), { +await new Deno.Command(Deno.execPath(), { args: ["eval", "--quiet", "console.log('Hello, world! 1')"], stdout: "inherit", -}); -Deno.spawnSync(Deno.execPath(), { +}).output(); +new Deno.Command(Deno.execPath(), { args: ["eval", "--quiet", "console.log('Hello, world! 2')"], stdout: "inherit", -}); +}).outputSync(); diff --git a/cli/tests/testdata/run/top_level_await/circular.out b/cli/tests/testdata/run/top_level_await/circular.out index 72072071ed..c889789613 100644 --- a/cli/tests/testdata/run/top_level_await/circular.out +++ b/cli/tests/testdata/run/top_level_await/circular.out @@ -4,6 +4,7 @@ timeout loop 2 timeout loop 3 timeout loop 4 timeout loop 5 -error: Dynamically imported module evaluation is still pending but there are no pending ops. This situation is often caused by unresolved promises. -Pending dynamic modules: -- [WILDCARD]/tla3/b.js +error: Top-level await promise never resolved +const mod = await import("./tla3/b.js"); + ^ + at ([WILDCARD]/top_level_await/circular.js:5:13) diff --git a/cli/tests/testdata/run/top_level_await/unresolved.out b/cli/tests/testdata/run/top_level_await/unresolved.out index d5291f833d..1f4ea5d382 100644 --- a/cli/tests/testdata/run/top_level_await/unresolved.out +++ b/cli/tests/testdata/run/top_level_await/unresolved.out @@ -1 +1,4 @@ -error: Module evaluation is still pending but there are no pending ops or dynamic imports. This situation is often caused by unresolved promises. +error: Top-level await promise never resolved +await new Promise(() => {}); +^ + at ([WILDCARD]top_level_await/unresolved.js:1:1) diff --git a/cli/tests/testdata/test/captured_output.ts b/cli/tests/testdata/test/captured_output.ts index 2e6aec948b..43295f027b 100644 --- a/cli/tests/testdata/test/captured_output.ts +++ b/cli/tests/testdata/test/captured_output.ts @@ -4,21 +4,21 @@ Deno.test("output", async () => { }); await p.status(); await p.close(); - Deno.spawnSync(Deno.execPath(), { + new Deno.Command(Deno.execPath(), { args: ["eval", "console.log(2); console.error(3);"], stdout: "inherit", stderr: "inherit", - }); - await Deno.spawn(Deno.execPath(), { + }).outputSync(); + await new Deno.Command(Deno.execPath(), { args: ["eval", "console.log(4); console.error(5);"], stdout: "inherit", stderr: "inherit", - }); - const c = await Deno.spawnChild(Deno.execPath(), { + }).output(); + const c = new Deno.Command(Deno.execPath(), { args: ["eval", "console.log(6); console.error(7);"], stdout: "inherit", stderr: "inherit", - }); + }).spawn(); await c.status; const worker = new Worker( import.meta.resolve("./captured_output.worker.js"), diff --git a/cli/tests/testdata/test/doc.out b/cli/tests/testdata/test/doc.out index 91ecbd4d48..1766912e57 100644 --- a/cli/tests/testdata/test/doc.out +++ b/cli/tests/testdata/test/doc.out @@ -4,7 +4,7 @@ Check [WILDCARD]/doc.ts$10-13.jsx Check [WILDCARD]/doc.ts$14-17.ts Check [WILDCARD]/doc.ts$18-21.tsx Check [WILDCARD]/doc.ts$30-35.ts -error: TS2367 [ERROR]: This condition will always return 'false' since the types 'string' and 'number' have no overlap. +error: TS2367 [ERROR]: This comparison appears to be unintentional because the types 'string' and 'number' have no overlap. console.assert(check() == 42); ~~~~~~~~~~~~~ at [WILDCARD]/doc.ts$30-35.ts:3:16 diff --git a/cli/tests/testdata/test/trace_ops_caught_error/main.out b/cli/tests/testdata/test/trace_ops_caught_error/main.out new file mode 100644 index 0000000000..192ed3a6d4 --- /dev/null +++ b/cli/tests/testdata/test/trace_ops_caught_error/main.out @@ -0,0 +1,6 @@ +Check file:///[WILDCARD]/trace_ops_caught_error/main.ts +running 1 test from ./test/trace_ops_caught_error/main.ts +handle thrown error in async function ... ok ([WILDCARD]) + +ok | 1 passed | 0 failed ([WILDCARD]) + diff --git a/cli/tests/testdata/test/trace_ops_caught_error/main.ts b/cli/tests/testdata/test/trace_ops_caught_error/main.ts new file mode 100644 index 0000000000..8194a8b2a1 --- /dev/null +++ b/cli/tests/testdata/test/trace_ops_caught_error/main.ts @@ -0,0 +1,12 @@ +Deno.test("handle thrown error in async function", async () => { + const dirPath = Deno.makeTempDirSync(); + const filePath = `${dirPath}/file.txt`; + try { + await Deno.stat(filePath); + } catch { + await Deno.writeTextFile(filePath, ""); + } finally { + await Deno.remove(filePath); + await Deno.remove(dirPath); + } +}); diff --git a/cli/tests/testdata/test/unresolved_promise.out b/cli/tests/testdata/test/unresolved_promise.out index 92eb16bed1..88535e1714 100644 --- a/cli/tests/testdata/test/unresolved_promise.out +++ b/cli/tests/testdata/test/unresolved_promise.out @@ -1,5 +1,10 @@ -Check [WILDCARD]/test/unresolved_promise.ts - -ok | 0 passed | 0 failed ([WILDCARD]) - -error: Module evaluation is still pending but there are no pending ops or dynamic imports. This situation is often caused by unresolved promises. +[WILDCARD] +./test/unresolved_promise.ts (uncaught error) +error: Top-level await promise never resolved +await new Promise((_resolve, _reject) => {}); +^ + at ([WILDCARD]/test/unresolved_promise.ts:1:1) +This error was not caught from a test and caused the test runner to fail on the referenced module. +It most likely originated from a dangling promise, event/timeout handler or top-level code. +[WILDCARD] +error: Test failed diff --git a/cli/tests/unit/README.md b/cli/tests/unit/README.md index 0d9e175541..af31c08fcc 100644 --- a/cli/tests/unit/README.md +++ b/cli/tests/unit/README.md @@ -30,10 +30,10 @@ There are two ways to run `unit_test_runner.ts`: ```sh # Run all tests. -target/debug/deno test --allow-all --unstable --location=http://js-unit-tests/foo/bar cli/tests/unit/ +cargo run --bin deno -- test --allow-all --unstable --location=http://js-unit-tests/foo/bar cli/tests/unit/ # Run a specific test module -target/debug/deno test --allow-all --unstable --location=http://js-unit-tests/foo/bar cli/tests/unit/files_test.ts +cargo run --bin deno -- test --allow-all --unstable --location=http://js-unit-tests/foo/bar cli/tests/unit/files_test.ts ``` ### Http server diff --git a/cli/tests/unit/chown_test.ts b/cli/tests/unit/chown_test.ts index 2fa203e187..dd23627ae5 100644 --- a/cli/tests/unit/chown_test.ts +++ b/cli/tests/unit/chown_test.ts @@ -5,12 +5,12 @@ import { assertEquals, assertRejects, assertThrows } from "./test_util.ts"; async function getUidAndGid(): Promise<{ uid: number; gid: number }> { // get the user ID and group ID of the current process - const uidProc = await Deno.spawn("id", { + const uidProc = await new Deno.Command("id", { args: ["-u"], - }); - const gidProc = await Deno.spawn("id", { + }).output(); + const gidProc = await new Deno.Command("id", { args: ["-g"], - }); + }).output(); assertEquals(uidProc.code, 0); assertEquals(gidProc.code, 0); diff --git a/cli/tests/unit/command_test.ts b/cli/tests/unit/command_test.ts index 0b8aa934b1..d58053c84c 100644 --- a/cli/tests/unit/command_test.ts +++ b/cli/tests/unit/command_test.ts @@ -31,13 +31,13 @@ tryExit(); Deno.writeFileSync(`${cwd}/${programFile}`, enc.encode(program)); - const child = new Deno.Command(Deno.execPath(), { + const command = new Deno.Command(Deno.execPath(), { cwd, args: ["run", "--allow-read", programFile], stdout: "inherit", stderr: "inherit", }); - child.spawn(); + const child = command.spawn(); // Write the expected exit code *after* starting deno. // This is how we verify that `Child` is actually asynchronous. @@ -55,7 +55,7 @@ tryExit(); Deno.test( { permissions: { run: true, read: true } }, async function commandStdinPiped() { - const child = new Deno.Command(Deno.execPath(), { + const command = new Deno.Command(Deno.execPath(), { args: [ "eval", "if (new TextDecoder().decode(await Deno.readAll(Deno.stdin)) !== 'hello') throw new Error('Expected \\'hello\\'')", @@ -64,7 +64,7 @@ Deno.test( stdout: "null", stderr: "null", }); - child.spawn(); + const child = command.spawn(); assertThrows(() => child.stdout, TypeError, "stdout is not piped"); assertThrows(() => child.stderr, TypeError, "stderr is not piped"); @@ -85,14 +85,14 @@ Deno.test( Deno.test( { permissions: { run: true, read: true } }, async function commandStdoutPiped() { - const child = new Deno.Command(Deno.execPath(), { + const command = new Deno.Command(Deno.execPath(), { args: [ "eval", "await Deno.stdout.write(new TextEncoder().encode('hello'))", ], stderr: "null", }); - child.spawn(); + const child = command.spawn(); assertThrows(() => child.stdin, TypeError, "stdin is not piped"); assertThrows(() => child.stderr, TypeError, "stderr is not piped"); @@ -118,14 +118,14 @@ Deno.test( Deno.test( { permissions: { run: true, read: true } }, async function commandStderrPiped() { - const child = new Deno.Command(Deno.execPath(), { + const command = new Deno.Command(Deno.execPath(), { args: [ "eval", "await Deno.stderr.write(new TextEncoder().encode('hello'))", ], stdout: "null", }); - child.spawn(); + const child = command.spawn(); assertThrows(() => child.stdin, TypeError, "stdin is not piped"); assertThrows(() => child.stdout, TypeError, "stdout is not piped"); @@ -158,13 +158,13 @@ Deno.test( write: true, }); - const child = new Deno.Command(Deno.execPath(), { + const command = new Deno.Command(Deno.execPath(), { args: [ "eval", "Deno.stderr.write(new TextEncoder().encode('error\\n')); Deno.stdout.write(new TextEncoder().encode('output\\n'));", ], }); - child.spawn(); + const child = command.spawn(); await child.stdout.pipeTo(file.writable, { preventClose: true, }); @@ -189,7 +189,7 @@ Deno.test( await Deno.writeFile(fileName, encoder.encode("hello")); const file = await Deno.open(fileName); - const child = new Deno.Command(Deno.execPath(), { + const command = new Deno.Command(Deno.execPath(), { args: [ "eval", "if (new TextDecoder().decode(await Deno.readAll(Deno.stdin)) !== 'hello') throw new Error('Expected \\'hello\\'')", @@ -198,7 +198,7 @@ Deno.test( stdout: "null", stderr: "null", }); - child.spawn(); + const child = command.spawn(); await file.readable.pipeTo(child.stdin, { preventClose: true, }); @@ -212,12 +212,12 @@ Deno.test( Deno.test( { permissions: { run: true, read: true } }, async function commandKillSuccess() { - const child = new Deno.Command(Deno.execPath(), { + const command = new Deno.Command(Deno.execPath(), { args: ["eval", "setTimeout(() => {}, 10000)"], stdout: "null", stderr: "null", }); - child.spawn(); + const child = command.spawn(); child.kill("SIGKILL"); const status = await child.status; @@ -236,12 +236,12 @@ Deno.test( Deno.test( { permissions: { run: true, read: true } }, async function commandKillFailed() { - const child = new Deno.Command(Deno.execPath(), { + const command = new Deno.Command(Deno.execPath(), { args: ["eval", "setTimeout(() => {}, 5000)"], stdout: "null", stderr: "null", }); - child.spawn(); + const child = command.spawn(); assertThrows(() => { // @ts-expect-error testing runtime error of bad signal @@ -255,12 +255,12 @@ Deno.test( Deno.test( { permissions: { run: true, read: true } }, async function commandKillOptional() { - const child = new Deno.Command(Deno.execPath(), { + const command = new Deno.Command(Deno.execPath(), { args: ["eval", "setTimeout(() => {}, 10000)"], stdout: "null", stderr: "null", }); - child.spawn(); + const child = command.spawn(); child.kill(); const status = await child.status; @@ -280,7 +280,7 @@ Deno.test( { permissions: { run: true, read: true } }, async function commandAbort() { const ac = new AbortController(); - const child = new Deno.Command(Deno.execPath(), { + const command = new Deno.Command(Deno.execPath(), { args: [ "eval", "setTimeout(console.log, 1e8)", @@ -289,7 +289,7 @@ Deno.test( stdout: "null", stderr: "null", }); - child.spawn(); + const child = command.spawn(); queueMicrotask(() => ac.abort()); const status = await child.status; assertEquals(status.success, false); @@ -735,11 +735,12 @@ Deno.test( const programFile = "unref.ts"; const program = ` -const child = await new Deno.Command(Deno.execPath(), { +const command = await new Deno.Command(Deno.execPath(), { cwd: Deno.args[0], stdout: "piped", args: ["run", "-A", "--unstable", Deno.args[1]], -});child.spawn(); +}); +const child = command.spawn(); const readable = child.stdout.pipeThrough(new TextDecoderStream()); const reader = readable.getReader(); // set up an interval that will end after reading a few messages from stdout, diff --git a/cli/tests/unit/fetch_test.ts b/cli/tests/unit/fetch_test.ts index a668bb4802..fde119bf15 100644 --- a/cli/tests/unit/fetch_test.ts +++ b/cli/tests/unit/fetch_test.ts @@ -1776,9 +1776,7 @@ Deno.test( Deno.test( { permissions: { net: true } }, - async function fetchBlobUrl(): Promise< - void - > { + async function fetchBlobUrl(): Promise { const blob = new Blob(["ok"], { type: "text/plain" }); const url = URL.createObjectURL(blob); const res = await fetch(url); @@ -1805,3 +1803,28 @@ Deno.test( await promise; }, ); + +Deno.test( + { permissions: { net: true } }, + async function fetchConstructorClones() { + const req = new Request("https://example.com", { + method: "POST", + body: "foo", + }); + assertEquals(await req.text(), "foo"); + await assertRejects(() => req.text()); + + const req2 = new Request(req, { method: "PUT", body: "bar" }); // should not have any impact on req + await assertRejects(() => req.text()); + assertEquals(await req2.text(), "bar"); + + assertEquals(req.method, "POST"); + assertEquals(req2.method, "PUT"); + + assertEquals(req.headers.get("x-foo"), null); + assertEquals(req2.headers.get("x-foo"), null); + req2.headers.set("x-foo", "bar"); // should not have any impact on req + assertEquals(req.headers.get("x-foo"), null); + assertEquals(req2.headers.get("x-foo"), "bar"); + }, +); diff --git a/cli/tests/unit/flash_test.ts b/cli/tests/unit/flash_test.ts index 761b9137aa..836c9b6031 100644 --- a/cli/tests/unit/flash_test.ts +++ b/cli/tests/unit/flash_test.ts @@ -57,42 +57,32 @@ Deno.test(async function httpServerCanResolveHostnames() { await server; }); -// TODO(magurotuna): ignore this case for now because it's flaky on GitHub Actions, -// although it acts as expected when running locally. -// See https://github.com/denoland/deno/pull/16616 -Deno.test({ ignore: true }, async function httpServerRejectsOnAddrInUse() { - const ac1 = new AbortController(); +Deno.test(async function httpServerRejectsOnAddrInUse() { + const ac = new AbortController(); const listeningPromise = deferred(); - let port: number; const server = Deno.serve({ handler: (_req) => new Response("ok"), hostname: "localhost", - port: 0, - signal: ac1.signal, - onListen: (addr) => { - port = addr.port; - listeningPromise.resolve(); - }, - onError: createOnErrorCb(ac1), + port: 4501, + signal: ac.signal, + onListen: onListen(listeningPromise), + onError: createOnErrorCb(ac), }); - await listeningPromise; - - const ac2 = new AbortController(); assertRejects( () => Deno.serve({ handler: (_req) => new Response("ok"), hostname: "localhost", - port, - signal: ac2.signal, + port: 4501, + signal: ac.signal, + onListen: onListen(listeningPromise), + onError: createOnErrorCb(ac), }), Deno.errors.AddrInUse, ); - - ac1.abort(); - ac2.abort(); + ac.abort(); await server; }); @@ -1043,11 +1033,11 @@ Deno.test( await listeningPromise; const url = `http://${hostname}:${port}/`; const args = ["-X", "DELETE", url]; - const { success } = await Deno.spawn("curl", { + const { success } = await new Deno.Command("curl", { args, stdout: "null", stderr: "null", - }); + }).output(); assert(success); await promise; ac.abort(); diff --git a/cli/tests/unit/flock_test.ts b/cli/tests/unit/flock_test.ts index 7ece1695ca..be463bf12b 100644 --- a/cli/tests/unit/flock_test.ts +++ b/cli/tests/unit/flock_test.ts @@ -148,10 +148,10 @@ function runFlockTestProcess(opts: { exclusive: boolean; sync: boolean }) { console.log(JSON.stringify({ enterTime, exitTime })); `; - const process = Deno.spawnChild(Deno.execPath(), { + const process = new Deno.Command(Deno.execPath(), { args: ["eval", "--unstable", scriptText], stdin: "piped", - }); + }).spawn(); const waitSignal = async () => { const reader = process.stdout.getReader({ mode: "byob" }); diff --git a/cli/tests/unit/http_test.ts b/cli/tests/unit/http_test.ts index 1d2addb2dc..0c17c7277c 100644 --- a/cli/tests/unit/http_test.ts +++ b/cli/tests/unit/http_test.ts @@ -1249,11 +1249,11 @@ Deno.test( async function client() { const url = `http://${hostname}:${port}/`; const args = ["-X", "DELETE", url]; - const { success } = await Deno.spawn("curl", { + const { success } = await new Deno.Command("curl", { args, stdout: "null", stderr: "null", - }); + }).output(); assert(success); } @@ -1380,10 +1380,10 @@ Deno.test({ "--header", "Accept-Encoding: gzip, deflate, br", ]; - const { success, stdout } = await Deno.spawn("curl", { + const { success, stdout } = await new Deno.Command("curl", { args, stderr: "null", - }); + }).output(); assert(success); const output = decoder.decode(stdout); assert(output.includes("vary: Accept-Encoding\r\n")); @@ -1430,7 +1430,7 @@ Deno.test({ "--header", "Accept-Encoding: gzip, deflate, br", ]; - const proc = Deno.spawnChild("curl", { args, stderr: "null" }); + const proc = new Deno.Command("curl", { args, stderr: "null" }).spawn(); const status = await proc.status; assert(status.success); const stdout = proc.stdout @@ -1485,10 +1485,10 @@ Deno.test({ "--header", "Accept-Encoding: gzip, deflate, br", ]; - const { success, stdout } = await Deno.spawn("curl", { + const { success, stdout } = await new Deno.Command("curl", { args, stderr: "null", - }); + }).output(); assert(success); const output = decoder.decode(stdout).toLocaleLowerCase(); assert(output.includes("vary: accept-encoding\r\n")); @@ -1540,10 +1540,10 @@ Deno.test({ "--header", "Accept-Encoding: gzip;q=0.8, br;q=1.0, *;q=0.1", ]; - const { success, stdout } = await Deno.spawn("curl", { + const { success, stdout } = await new Deno.Command("curl", { args, stderr: "null", - }); + }).output(); assert(success); const output = decoder.decode(stdout); assert(output.includes("vary: Accept-Encoding\r\n")); @@ -1592,10 +1592,10 @@ Deno.test({ "--header", "Accept-Encoding: gzip, deflate, br", ]; - const { success, stdout } = await Deno.spawn("curl", { + const { success, stdout } = await new Deno.Command("curl", { args, stderr: "null", - }); + }).output(); assert(success); const output = decoder.decode(stdout); assert(output.includes("vary: Accept-Encoding, Accept\r\n")); @@ -1648,10 +1648,10 @@ Deno.test({ "--header", "Accept-Encoding: gzip, deflate, br", ]; - const { success, stdout } = await Deno.spawn("curl", { + const { success, stdout } = await new Deno.Command("curl", { args, stderr: "null", - }); + }).output(); assert(success); const output = decoder.decode(stdout); assert(output.includes("vary: Accept-Encoding\r\n")); @@ -1706,10 +1706,10 @@ Deno.test({ "--header", "Accept-Encoding: gzip, deflate, br", ]; - const { success, stdout } = await Deno.spawn("curl", { + const { success, stdout } = await new Deno.Command("curl", { args, stderr: "null", - }); + }).output(); assert(success); const output = decoder.decode(stdout); assert(output.includes("vary: Accept-Encoding\r\n")); @@ -1764,10 +1764,10 @@ Deno.test({ "--header", "Accept-Encoding: gzip, deflate, br", ]; - const { success, stdout } = await Deno.spawn("curl", { + const { success, stdout } = await new Deno.Command("curl", { args, stderr: "null", - }); + }).output(); assert(success); const output = decoder.decode(stdout); assert(output.includes("vary: Accept-Encoding\r\n")); @@ -1819,10 +1819,10 @@ Deno.test({ "--header", "Accept-Encoding: gzip, deflate, br", ]; - const { success, stdout } = await Deno.spawn("curl", { + const { success, stdout } = await new Deno.Command("curl", { args, stderr: "null", - }); + }).output(); assert(success); const output = decoder.decode(stdout); assert(output.includes("vary: Accept-Encoding\r\n")); @@ -1880,10 +1880,10 @@ Deno.test({ "--header", "Accept-Encoding: gzip, deflate, br", ]; - const { success, stdout } = await Deno.spawn("curl", { + const { success, stdout } = await new Deno.Command("curl", { args, stderr: "null", - }); + }).output(); assert(success); const output = decoder.decode(stdout); assert(output.includes("vary: Accept-Encoding\r\n")); @@ -1939,7 +1939,7 @@ Deno.test({ "--header", "Accept-Encoding: gzip, deflate, br", ]; - const proc = Deno.spawnChild("curl", { args, stderr: "null" }); + const proc = new Deno.Command("curl", { args, stderr: "null" }).spawn(); const status = await proc.status; assert(status.success); const stdout = proc.stdout @@ -2004,10 +2004,10 @@ Deno.test({ "--header", "Accept-Encoding: gzip, deflate, br", ]; - const { success, stdout } = await Deno.spawn("curl", { + const { success, stdout } = await new Deno.Command("curl", { args, stderr: "null", - }); + }).output(); assert(success); const output = decoder.decode(stdout); assert(output.includes("vary: Accept-Encoding\r\n")); @@ -2569,7 +2569,7 @@ Deno.test({ "Accept-Encoding: gzip, deflate, br", "--no-buffer", ]; - const proc = Deno.spawnChild("curl", { args, stderr: "null" }); + const proc = new Deno.Command("curl", { args, stderr: "null" }).spawn(); const stdout = proc.stdout .pipeThrough(new DecompressionStream("gzip")) .pipeThrough(new TextDecoderStream()); diff --git a/cli/tests/unit/net_test.ts b/cli/tests/unit/net_test.ts index 8d004f4248..b4a21578e2 100644 --- a/cli/tests/unit/net_test.ts +++ b/cli/tests/unit/net_test.ts @@ -8,6 +8,7 @@ import { deferred, delay, execCode, + execCode2, } from "./test_util.ts"; import { join } from "../../../test_util/std/path/mod.ts"; @@ -853,25 +854,23 @@ Deno.test( Deno.test( { permissions: { read: true, run: true, net: true } }, async function netListenUnrefAndRef() { - const p = execCode(` + const p = execCode2(` async function main() { const listener = Deno.listen({ port: 3500 }); listener.unref(); listener.ref(); // This restores 'ref' state of listener + console.log("started"); await listener.accept(); console.log("accepted") } main(); `); - // TODO(kt3k): This is racy. Find a correct way to - // wait for the server to be ready - setTimeout(async () => { - const conn = await Deno.connect({ port: 3500 }); - conn.close(); - }, 200); - const [statusCode, output] = await p; + await p.waitStdoutText("started"); + const conn = await Deno.connect({ port: 3500 }); + conn.close(); + const [statusCode, output] = await p.finished(); assertEquals(statusCode, 0); - assertEquals(output.trim(), "accepted"); + assertEquals(output.trim(), "started\naccepted"); }, ); diff --git a/cli/tests/unit/os_test.ts b/cli/tests/unit/os_test.ts index 04ddf8ae0b..72e0b57bae 100644 --- a/cli/tests/unit/os_test.ts +++ b/cli/tests/unit/os_test.ts @@ -74,10 +74,10 @@ Deno.test( console.log( ${JSON.stringify(Object.keys(expectedEnv))}.map(k => Deno.env.get(k)) )`; - const { success, stdout } = await Deno.spawn(Deno.execPath(), { + const { success, stdout } = await new Deno.Command(Deno.execPath(), { args: ["eval", src], env: { ...inputEnv, NO_COLOR: "1" }, - }); + }).output(); assertEquals(success, true); const expectedValues = Object.values(expectedEnv); const actualValues = JSON.parse(new TextDecoder().decode(stdout)); @@ -162,10 +162,10 @@ Deno.test( { permissions: { run: true, read: true } }, async function osPpidIsEqualToPidOfParentProcess() { const decoder = new TextDecoder(); - const { stdout } = await Deno.spawn(Deno.execPath(), { + const { stdout } = await new Deno.Command(Deno.execPath(), { args: ["eval", "-p", "--unstable", "Deno.ppid"], env: { NO_COLOR: "true" }, - }); + }).output(); const expected = Deno.pid; const actual = parseInt(decoder.decode(stdout)); @@ -212,9 +212,9 @@ Deno.test( { permissions: { run: [Deno.execPath()], read: true } }, // See https://github.com/denoland/deno/issues/16527 async function hostnameWithoutOtherNetworkUsages() { - const { stdout } = await Deno.spawn(Deno.execPath(), { + const { stdout } = await new Deno.Command(Deno.execPath(), { args: ["eval", "-p", "Deno.hostname()"], - }); + }).output(); const hostname = new TextDecoder().decode(stdout).trim(); assert(hostname.length > 0); }, diff --git a/cli/tests/unit/remove_test.ts b/cli/tests/unit/remove_test.ts index ae439e3058..0032459eb5 100644 --- a/cli/tests/unit/remove_test.ts +++ b/cli/tests/unit/remove_test.ts @@ -260,10 +260,10 @@ if (Deno.build.os === "windows") { Deno.test( { permissions: { run: true, write: true, read: true } }, async function removeFileSymlink() { - const { success } = await Deno.spawn("cmd", { + const { success } = await new Deno.Command("cmd", { args: ["/c", "mklink", "file_link", "bar"], stdout: "null", - }); + }).output(); assert(success); await Deno.remove("file_link"); @@ -276,10 +276,10 @@ if (Deno.build.os === "windows") { Deno.test( { permissions: { run: true, write: true, read: true } }, async function removeDirSymlink() { - const { success } = await Deno.spawn("cmd", { + const { success } = await new Deno.Command("cmd", { args: ["/c", "mklink", "/d", "dir_link", "bar"], stdout: "null", - }); + }).output(); assert(success); await Deno.remove("dir_link"); diff --git a/cli/tests/unit/signal_test.ts b/cli/tests/unit/signal_test.ts index 86092a298e..25143da1f1 100644 --- a/cli/tests/unit/signal_test.ts +++ b/cli/tests/unit/signal_test.ts @@ -185,13 +185,13 @@ Deno.test( permissions: { run: true, read: true }, }, async function canExitWhileListeningToSignal() { - const { code } = await Deno.spawn(Deno.execPath(), { + const { code } = await new Deno.Command(Deno.execPath(), { args: [ "eval", "--unstable", "Deno.addSignalListener('SIGINT', () => {})", ], - }); + }).output(); assertEquals(code, 0); }, ); diff --git a/cli/tests/unit/test_util.ts b/cli/tests/unit/test_util.ts index c33da53388..ce945c7dba 100644 --- a/cli/tests/unit/test_util.ts +++ b/cli/tests/unit/test_util.ts @@ -29,16 +29,53 @@ export function pathToAbsoluteFileUrl(path: string): URL { return new URL(`file://${Deno.build.os === "windows" ? "/" : ""}${path}`); } -const decoder = new TextDecoder(); +export function execCode(code: string): Promise { + return execCode2(code).finished(); +} -export async function execCode(code: string): Promise<[number, string]> { - const output = await Deno.spawn(Deno.execPath(), { +export function execCode2(code: string) { + const command = new Deno.Command(Deno.execPath(), { args: [ "eval", "--unstable", "--no-check", code, ], + stdout: "piped", + stderr: "inherit", }); - return [output.code, decoder.decode(output.stdout)]; + + const child = command.spawn(); + const stdout = child.stdout.pipeThrough(new TextDecoderStream()).getReader(); + let output = ""; + + return { + async waitStdoutText(text: string) { + while (true) { + const readData = await stdout.read(); + if (readData.value) { + output += readData.value; + if (output.includes(text)) { + return; + } + } + if (readData.done) { + throw new Error(`Did not find text '${text}' in stdout.`); + } + } + }, + async finished() { + while (true) { + const readData = await stdout.read(); + if (readData.value) { + output += readData.value; + } + if (readData.done) { + break; + } + } + const status = await child.status; + return [status.code, output] as const; + }, + }; } diff --git a/cli/tests/unit/tls_test.ts b/cli/tests/unit/tls_test.ts index d3ef4d0bf5..e5ad6e66c5 100644 --- a/cli/tests/unit/tls_test.ts +++ b/cli/tests/unit/tls_test.ts @@ -1046,9 +1046,9 @@ function createHttpsListener(port: number): Deno.Listener { } async function curl(url: string): Promise { - const { success, code, stdout } = await Deno.spawn("curl", { + const { success, code, stdout } = await new Deno.Command("curl", { args: ["--insecure", url], - }); + }).output(); if (!success) { throw new Error(`curl ${url} failed: ${code}`); diff --git a/cli/tests/unit/tty_color_test.ts b/cli/tests/unit/tty_color_test.ts index 7662d039b7..f819a1a63d 100644 --- a/cli/tests/unit/tty_color_test.ts +++ b/cli/tests/unit/tty_color_test.ts @@ -6,9 +6,9 @@ import { assertEquals } from "./test_util.ts"; Deno.test( { permissions: { run: true, read: true } }, async function noColorIfNotTty() { - const { stdout } = await Deno.spawn(Deno.execPath(), { + const { stdout } = await new Deno.Command(Deno.execPath(), { args: ["eval", "console.log(1)"], - }); + }).output(); const output = new TextDecoder().decode(stdout); assertEquals(output, "1\n"); }, diff --git a/cli/tests/unit/version_test.ts b/cli/tests/unit/version_test.ts index 4f8a1c5e46..d9984dbf24 100644 --- a/cli/tests/unit/version_test.ts +++ b/cli/tests/unit/version_test.ts @@ -1,14 +1,8 @@ -import { assert } from "./test_util.ts"; +import { assert, assertEquals } from "./test_util.ts"; Deno.test(function version() { const pattern = /^\d+\.\d+\.\d+/; assert(pattern.test(Deno.version.deno)); assert(pattern.test(Deno.version.v8)); - // Unreleased version of TypeScript now set the version to 0-dev - assert( - pattern.test(Deno.version.typescript) || - Deno.version.typescript === "0-dev" || - Deno.version.typescript === "0-beta" || - Deno.version.typescript === "1-rc", - ); + assertEquals(Deno.version.typescript, "4.9.3"); }); diff --git a/cli/tests/upgrade_tests.rs b/cli/tests/upgrade_tests.rs new file mode 100644 index 0000000000..f67e302ff8 --- /dev/null +++ b/cli/tests/upgrade_tests.rs @@ -0,0 +1,197 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +use std::process::{Command, Stdio}; +use test_util as util; +use test_util::TempDir; + +mod upgrade { + use super::*; + + // Warning: this test requires internet access. + // TODO(#7412): reenable. test is flaky + #[test] + #[ignore] + fn upgrade_in_tmpdir() { + let temp_dir = TempDir::new(); + let exe_path = temp_dir.path().join("deno"); + let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + assert!(exe_path.exists()); + let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); + let status = Command::new(&exe_path) + .arg("upgrade") + .arg("--force") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + let _mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); + // TODO(ry) assert!(mtime1 < mtime2); + } + + // Warning: this test requires internet access. + // TODO(#7412): reenable. test is flaky + #[test] + #[ignore] + fn upgrade_with_space_in_path() { + let temp_dir = TempDir::new_with_prefix("directory with spaces"); + let exe_path = temp_dir.path().join("deno"); + let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + assert!(exe_path.exists()); + let status = Command::new(&exe_path) + .arg("upgrade") + .arg("--force") + .env("TMP", temp_dir.path()) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + + // Warning: this test requires internet access. + // TODO(#7412): reenable. test is flaky + #[test] + #[ignore] + fn upgrade_with_version_in_tmpdir() { + let temp_dir = TempDir::new(); + let exe_path = temp_dir.path().join("deno"); + let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + assert!(exe_path.exists()); + let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); + let status = Command::new(&exe_path) + .arg("upgrade") + .arg("--force") + .arg("--version") + .arg("1.11.5") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + let upgraded_deno_version = String::from_utf8( + Command::new(&exe_path).arg("-V").output().unwrap().stdout, + ) + .unwrap(); + assert!(upgraded_deno_version.contains("1.11.5")); + let _mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); + // TODO(ry) assert!(mtime1 < mtime2); + } + + // Warning: this test requires internet access. + // TODO(#7412): reenable. test is flaky + #[test] + #[ignore] + fn upgrade_with_canary_in_tmpdir() { + let temp_dir = TempDir::new(); + let exe_path = temp_dir.path().join("deno"); + let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + assert!(exe_path.exists()); + let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); + let status = Command::new(&exe_path) + .arg("upgrade") + .arg("--canary") + .arg("--version") + .arg("e6685f0f01b8a11a5eaff020f5babcfde76b3038") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + let upgraded_deno_version = String::from_utf8( + Command::new(&exe_path).arg("-V").output().unwrap().stdout, + ) + .unwrap(); + assert!(upgraded_deno_version.contains("e6685f0")); + let _mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); + // TODO(ry) assert!(mtime1 < mtime2); + } + + // Warning: this test requires internet access. + // TODO(#7412): reenable. test is flaky + #[test] + #[ignore] + fn upgrade_with_out_in_tmpdir() { + let temp_dir = TempDir::new(); + let exe_path = temp_dir.path().join("deno"); + let new_exe_path = temp_dir.path().join("foo"); + let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + assert!(exe_path.exists()); + let mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); + let status = Command::new(&exe_path) + .arg("upgrade") + .arg("--version") + .arg("1.11.5") + .arg("--output") + .arg(new_exe_path.to_str().unwrap()) + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + assert!(new_exe_path.exists()); + let mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); + assert_eq!(mtime1, mtime2); // Original exe_path was not changed. + + let v = String::from_utf8( + Command::new(&new_exe_path) + .arg("-V") + .output() + .unwrap() + .stdout, + ) + .unwrap(); + assert!(v.contains("1.11.5")); + } + + // Warning: this test requires internet access. + // TODO(#7412): reenable. test is flaky + #[test] + #[ignore] + fn upgrade_invalid_stable_version() { + let temp_dir = TempDir::new(); + let exe_path = temp_dir.path().join("deno"); + let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + assert!(exe_path.exists()); + let output = Command::new(&exe_path) + .arg("upgrade") + .arg("--version") + .arg("foobar") + .stderr(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + assert_eq!( + "error: Invalid semver passed\n", + util::strip_ansi_codes(&String::from_utf8(output.stderr).unwrap()) + ); + } + + // Warning: this test requires internet access. + // TODO(#7412): reenable. test is flaky + #[test] + #[ignore] + fn upgrade_invalid_canary_version() { + let temp_dir = TempDir::new(); + let exe_path = temp_dir.path().join("deno"); + let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + assert!(exe_path.exists()); + let output = Command::new(&exe_path) + .arg("upgrade") + .arg("--canary") + .arg("--version") + .arg("foobar") + .stderr(Stdio::piped()) + .spawn() + .unwrap() + .wait_with_output() + .unwrap(); + assert!(!output.status.success()); + assert_eq!( + "error: Invalid commit hash passed\n", + util::strip_ansi_codes(&String::from_utf8(output.stderr).unwrap()) + ); + } +} diff --git a/cli/tests/vendor_tests.rs b/cli/tests/vendor_tests.rs new file mode 100644 index 0000000000..6f9628a406 --- /dev/null +++ b/cli/tests/vendor_tests.rs @@ -0,0 +1,583 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod vendor { + use deno_core::serde_json; + use deno_core::serde_json::json; + use pretty_assertions::assert_eq; + use std::fmt::Write as _; + use std::path::PathBuf; + use std::process::Stdio; + use test_util as util; + use test_util::TempDir; + use util::http_server; + use util::new_deno_dir; + + #[test] + fn output_dir_exists() { + let t = TempDir::new(); + t.write("mod.ts", ""); + t.create_dir_all("vendor"); + t.write("vendor/mod.ts", ""); + + let deno = util::deno_cmd() + .current_dir(t.path()) + .env("NO_COLOR", "1") + .arg("vendor") + .arg("mod.ts") + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!( + String::from_utf8_lossy(&output.stderr).trim(), + concat!( + "error: Output directory was not empty. Please specify an empty ", + "directory or use --force to ignore this error and potentially ", + "overwrite its contents.", + ), + ); + assert!(!output.status.success()); + + // ensure it errors when using the `--output` arg too + let deno = util::deno_cmd() + .current_dir(t.path()) + .env("NO_COLOR", "1") + .arg("vendor") + .arg("--output") + .arg("vendor") + .arg("mod.ts") + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!( + String::from_utf8_lossy(&output.stderr).trim(), + concat!( + "error: Output directory was not empty. Please specify an empty ", + "directory or use --force to ignore this error and potentially ", + "overwrite its contents.", + ), + ); + assert!(!output.status.success()); + + // now use `--force` + let status = util::deno_cmd() + .current_dir(t.path()) + .env("NO_COLOR", "1") + .arg("vendor") + .arg("mod.ts") + .arg("--force") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + + #[test] + fn standard_test() { + let _server = http_server(); + let t = TempDir::new(); + let vendor_dir = t.path().join("vendor2"); + t.write( + "my_app.ts", + "import {Logger} from 'http://localhost:4545/vendor/query_reexport.ts?testing'; new Logger().log('outputted');", + ); + + let deno = util::deno_cmd() + .current_dir(t.path()) + .arg("vendor") + .arg("my_app.ts") + .arg("--output") + .arg("vendor2") + .env("NO_COLOR", "1") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!( + String::from_utf8_lossy(&output.stderr).trim(), + format!( + concat!( + "Download http://localhost:4545/vendor/query_reexport.ts?testing\n", + "Download http://localhost:4545/vendor/logger.ts?test\n", + "{}", + ), + success_text("2 modules", "vendor2", true), + ) + ); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), ""); + assert!(output.status.success()); + + assert!(vendor_dir.exists()); + assert!(!t.path().join("vendor").exists()); + let import_map: serde_json::Value = + serde_json::from_str(&t.read_to_string("vendor2/import_map.json")) + .unwrap(); + assert_eq!( + import_map, + json!({ + "imports": { + "http://localhost:4545/vendor/query_reexport.ts?testing": "./localhost_4545/vendor/query_reexport.ts", + "http://localhost:4545/": "./localhost_4545/", + }, + "scopes": { + "./localhost_4545/": { + "./localhost_4545/vendor/logger.ts?test": "./localhost_4545/vendor/logger.ts" + } + } + }), + ); + + // try running the output with `--no-remote` + let deno = util::deno_cmd() + .current_dir(t.path()) + .env("NO_COLOR", "1") + .arg("run") + .arg("--no-remote") + .arg("--check") + .arg("--quiet") + .arg("--import-map") + .arg("vendor2/import_map.json") + .arg("my_app.ts") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!(String::from_utf8_lossy(&output.stderr).trim(), ""); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "outputted"); + assert!(output.status.success()); + } + + #[test] + fn import_map_output_dir() { + let _server = http_server(); + let t = TempDir::new(); + t.write("mod.ts", ""); + t.create_dir_all("vendor"); + t.write( + "vendor/import_map.json", + // will be ignored + "{ \"imports\": { \"https://localhost:4545/\": \"./localhost/\" }}", + ); + t.write( + "deno.json", + "{ \"import_map\": \"./vendor/import_map.json\" }", + ); + t.write( + "my_app.ts", + "import {Logger} from 'http://localhost:4545/vendor/logger.ts'; new Logger().log('outputted');", + ); + + let deno = util::deno_cmd() + .current_dir(t.path()) + .env("NO_COLOR", "1") + .arg("vendor") + .arg("--force") + .arg("--import-map") + .arg("vendor/import_map.json") + .arg("my_app.ts") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!( + String::from_utf8_lossy(&output.stderr).trim(), + format!( + concat!( + "Ignoring import map. Specifying an import map file ({}) in the deno ", + "vendor output directory is not supported. If you wish to use an ", + "import map while vendoring, please specify one located outside this ", + "directory.\n", + "Download http://localhost:4545/vendor/logger.ts\n", + "{}", + ), + PathBuf::from("vendor").join("import_map.json").display(), + success_text_updated_deno_json("1 module", "vendor/"), + ) + ); + assert!(output.status.success()); + } + + #[test] + fn remote_module_test() { + let _server = http_server(); + let t = TempDir::new(); + let vendor_dir = t.path().join("vendor"); + + let deno = util::deno_cmd() + .current_dir(t.path()) + .env("NO_COLOR", "1") + .arg("vendor") + .arg("http://localhost:4545/vendor/query_reexport.ts") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!( + String::from_utf8_lossy(&output.stderr).trim(), + format!( + concat!( + "Download http://localhost:4545/vendor/query_reexport.ts\n", + "Download http://localhost:4545/vendor/logger.ts?test\n", + "{}", + ), + success_text("2 modules", "vendor/", true), + ) + ); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), ""); + assert!(output.status.success()); + assert!(vendor_dir.exists()); + assert!(vendor_dir + .join("localhost_4545/vendor/query_reexport.ts") + .exists()); + assert!(vendor_dir.join("localhost_4545/vendor/logger.ts").exists()); + let import_map: serde_json::Value = + serde_json::from_str(&t.read_to_string("vendor/import_map.json")) + .unwrap(); + assert_eq!( + import_map, + json!({ + "imports": { + "http://localhost:4545/": "./localhost_4545/", + }, + "scopes": { + "./localhost_4545/": { + "./localhost_4545/vendor/logger.ts?test": "./localhost_4545/vendor/logger.ts", + } + } + }), + ); + } + + #[test] + fn existing_import_map_no_remote() { + let _server = http_server(); + let t = TempDir::new(); + t.write( + "mod.ts", + "import {Logger} from 'http://localhost:4545/vendor/logger.ts';", + ); + let import_map_filename = "imports2.json"; + let import_map_text = + r#"{ "imports": { "http://localhost:4545/vendor/": "./logger/" } }"#; + t.write(import_map_filename, import_map_text); + t.create_dir_all("logger"); + t.write("logger/logger.ts", "export class Logger {}"); + + let deno = util::deno_cmd() + .current_dir(t.path()) + .env("NO_COLOR", "1") + .arg("vendor") + .arg("mod.ts") + .arg("--import-map") + .arg(import_map_filename) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!( + String::from_utf8_lossy(&output.stderr).trim(), + success_text("0 modules", "vendor/", false) + ); + assert!(output.status.success()); + // it should not have found any remote dependencies because + // the provided import map mapped it to a local directory + assert_eq!(t.read_to_string(import_map_filename), import_map_text); + } + + #[test] + fn existing_import_map_mixed_with_remote() { + let _server = http_server(); + let deno_dir = new_deno_dir(); + let t = TempDir::new(); + t.write( + "mod.ts", + "import {Logger} from 'http://localhost:4545/vendor/logger.ts';", + ); + + let status = util::deno_cmd_with_deno_dir(&deno_dir) + .current_dir(t.path()) + .arg("vendor") + .arg("mod.ts") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + + assert_eq!( + t.read_to_string("vendor/import_map.json"), + r#"{ + "imports": { + "http://localhost:4545/": "./localhost_4545/" + } +} +"#, + ); + + // make the import map specific to support vendoring mod.ts in the next step + t.write( + "vendor/import_map.json", + r#"{ + "imports": { + "http://localhost:4545/vendor/logger.ts": "./localhost_4545/vendor/logger.ts" + } +} +"#, + ); + + t.write( + "mod.ts", + concat!( + "import {Logger} from 'http://localhost:4545/vendor/logger.ts';\n", + "import {Logger as OtherLogger} from 'http://localhost:4545/vendor/mod.ts';\n", + ), + ); + + // now vendor with the existing import map in a separate vendor directory + let deno = util::deno_cmd_with_deno_dir(&deno_dir) + .env("NO_COLOR", "1") + .current_dir(t.path()) + .arg("vendor") + .arg("mod.ts") + .arg("--import-map") + .arg("vendor/import_map.json") + .arg("--output") + .arg("vendor2") + .stderr(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!( + String::from_utf8_lossy(&output.stderr).trim(), + format!( + concat!("Download http://localhost:4545/vendor/mod.ts\n", "{}",), + success_text("1 module", "vendor2", true), + ) + ); + assert!(output.status.success()); + + // tricky scenario here where the output directory now contains a mapping + // back to the previous vendor location + assert_eq!( + t.read_to_string("vendor2/import_map.json"), + r#"{ + "imports": { + "http://localhost:4545/vendor/logger.ts": "../vendor/localhost_4545/vendor/logger.ts", + "http://localhost:4545/": "./localhost_4545/" + }, + "scopes": { + "./localhost_4545/": { + "./localhost_4545/vendor/logger.ts": "../vendor/localhost_4545/vendor/logger.ts" + } + } +} +"#, + ); + + // ensure it runs + let status = util::deno_cmd() + .current_dir(t.path()) + .arg("run") + .arg("--check") + .arg("--no-remote") + .arg("--import-map") + .arg("vendor2/import_map.json") + .arg("mod.ts") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + } + + #[test] + fn dynamic_import() { + let _server = http_server(); + let t = TempDir::new(); + t.write( + "mod.ts", + "import {Logger} from 'http://localhost:4545/vendor/dynamic.ts'; new Logger().log('outputted');", + ); + + let status = util::deno_cmd() + .current_dir(t.path()) + .arg("vendor") + .arg("mod.ts") + .spawn() + .unwrap() + .wait() + .unwrap(); + assert!(status.success()); + let import_map: serde_json::Value = + serde_json::from_str(&t.read_to_string("vendor/import_map.json")) + .unwrap(); + assert_eq!( + import_map, + json!({ + "imports": { + "http://localhost:4545/": "./localhost_4545/", + } + }), + ); + + // try running the output with `--no-remote` + let deno = util::deno_cmd() + .current_dir(t.path()) + .env("NO_COLOR", "1") + .arg("run") + .arg("--allow-read=.") + .arg("--no-remote") + .arg("--check") + .arg("--quiet") + .arg("--import-map") + .arg("vendor/import_map.json") + .arg("mod.ts") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!(String::from_utf8_lossy(&output.stderr).trim(), ""); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "outputted"); + assert!(output.status.success()); + } + + #[test] + fn dynamic_non_analyzable_import() { + let _server = http_server(); + let t = TempDir::new(); + t.write( + "mod.ts", + "import {Logger} from 'http://localhost:4545/vendor/dynamic_non_analyzable.ts'; new Logger().log('outputted');", + ); + + let deno = util::deno_cmd() + .current_dir(t.path()) + .env("NO_COLOR", "1") + .arg("vendor") + .arg("--reload") + .arg("mod.ts") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + // todo(https://github.com/denoland/deno_graph/issues/138): it should warn about + // how it couldn't analyze the dynamic import + assert_eq!( + String::from_utf8_lossy(&output.stderr).trim(), + format!( + "Download http://localhost:4545/vendor/dynamic_non_analyzable.ts\n{}", + success_text("1 module", "vendor/", true), + ) + ); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), ""); + assert!(output.status.success()); + } + + #[test] + fn update_existing_config_test() { + let _server = http_server(); + let t = TempDir::new(); + t.write( + "my_app.ts", + "import {Logger} from 'http://localhost:4545/vendor/logger.ts'; new Logger().log('outputted');", + ); + t.write("deno.json", "{\n}"); + + let deno = util::deno_cmd() + .current_dir(t.path()) + .arg("vendor") + .arg("my_app.ts") + .arg("--output") + .arg("vendor2") + .env("NO_COLOR", "1") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!( + String::from_utf8_lossy(&output.stderr).trim(), + format!( + "Download http://localhost:4545/vendor/logger.ts\n{}", + success_text_updated_deno_json("1 module", "vendor2",) + ) + ); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), ""); + assert!(output.status.success()); + + // try running the output with `--no-remote` and not specifying a `--vendor` + let deno = util::deno_cmd() + .current_dir(t.path()) + .env("NO_COLOR", "1") + .arg("run") + .arg("--no-remote") + .arg("--check") + .arg("--quiet") + .arg("my_app.ts") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = deno.wait_with_output().unwrap(); + assert_eq!(String::from_utf8_lossy(&output.stderr).trim(), ""); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "outputted"); + assert!(output.status.success()); + } + + fn success_text( + module_count: &str, + dir: &str, + has_import_map: bool, + ) -> String { + let mut text = format!("Vendored {} into {} directory.", module_count, dir); + if has_import_map { + let f = format!( + concat!( + "\n\nTo use vendored modules, specify the `--import-map {}import_map.json` flag when ", + r#"invoking Deno subcommands or add an `"importMap": ""` "#, + "entry to a deno.json file.", + ), + if dir != "vendor/" { + format!("{}{}", dir.trim_end_matches('/'), if cfg!(windows) { '\\' } else {'/'}) + } else { + dir.to_string() + } + ); + write!(text, "{}", f).unwrap(); + } + text + } + + fn success_text_updated_deno_json(module_count: &str, dir: &str) -> String { + format!( + concat!( + "Vendored {} into {} directory.\n\n", + "Updated your local Deno configuration file with a reference to the ", + "new vendored import map at {}import_map.json. Invoking Deno subcommands will ", + "now automatically resolve using the vendored modules. You may override ", + "this by providing the `--import-map ` flag or by ", + "manually editing your Deno configuration file.", + ), + module_count, + dir, + if dir != "vendor/" { + format!( + "{}{}", + dir.trim_end_matches('/'), + if cfg!(windows) { '\\' } else { '/' } + ) + } else { + dir.to_string() + } + ) + } +} diff --git a/cli/tests/watcher_tests.rs b/cli/tests/watcher_tests.rs new file mode 100644 index 0000000000..f9c8e1508a --- /dev/null +++ b/cli/tests/watcher_tests.rs @@ -0,0 +1,1182 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +use flaky_test::flaky_test; +use std::fs::write; +use std::io::BufRead; +use test_util as util; +use test_util::assert_contains; +use test_util::TempDir; + +mod watcher { + use super::*; + + const CLEAR_SCREEN: &str = r#"[2J"#; + + // Helper function to skip watcher output that contains "Restarting" + // phrase. + fn skip_restarting_line( + stderr_lines: &mut impl Iterator, + ) -> String { + loop { + let msg = stderr_lines.next().unwrap(); + if !msg.contains("Restarting") { + return msg; + } + } + } + + fn read_all_lints(stderr_lines: &mut impl Iterator) -> String { + let mut str = String::new(); + for t in stderr_lines { + let t = util::strip_ansi_codes(&t); + if t.starts_with("Watcher File change detected") { + continue; + } + if t.starts_with("Watcher") { + break; + } + if t.starts_with('(') { + str.push_str(&t); + str.push('\n'); + } + } + str + } + + fn wait_for( + condition: impl Fn(&str) -> bool, + lines: &mut impl Iterator, + ) { + loop { + let msg = lines.next().unwrap(); + if condition(&msg) { + break; + } + } + } + + fn wait_contains(s: &str, lines: &mut impl Iterator) { + wait_for(|msg| msg.contains(s), lines) + } + + fn read_line(s: &str, lines: &mut impl Iterator) -> String { + lines.find(|m| m.contains(s)).unwrap() + } + + fn check_alive_then_kill(mut child: std::process::Child) { + assert!(child.try_wait().unwrap().is_none()); + child.kill().unwrap(); + } + + fn child_lines( + child: &mut std::process::Child, + ) -> (impl Iterator, impl Iterator) { + let stdout_lines = std::io::BufReader::new(child.stdout.take().unwrap()) + .lines() + .map(|r| { + let line = r.unwrap(); + eprintln!("STDOUT: {}", line); + line + }); + let stderr_lines = std::io::BufReader::new(child.stderr.take().unwrap()) + .lines() + .map(|r| { + let line = r.unwrap(); + eprintln!("STERR: {}", line); + line + }); + (stdout_lines, stderr_lines) + } + + #[test] + fn lint_watch_test() { + let t = TempDir::new(); + let badly_linted_original = + util::testdata_path().join("lint/watch/badly_linted.js"); + let badly_linted_output = + util::testdata_path().join("lint/watch/badly_linted.js.out"); + let badly_linted_fixed1 = + util::testdata_path().join("lint/watch/badly_linted_fixed1.js"); + let badly_linted_fixed1_output = + util::testdata_path().join("lint/watch/badly_linted_fixed1.js.out"); + let badly_linted_fixed2 = + util::testdata_path().join("lint/watch/badly_linted_fixed2.js"); + let badly_linted_fixed2_output = + util::testdata_path().join("lint/watch/badly_linted_fixed2.js.out"); + let badly_linted = t.path().join("badly_linted.js"); + + std::fs::copy(&badly_linted_original, &badly_linted).unwrap(); + + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("lint") + .arg(&badly_linted) + .arg("--watch") + .arg("--unstable") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); + let next_line = stderr_lines.next().unwrap(); + assert_contains!(&next_line, "Lint started"); + let mut output = read_all_lints(&mut stderr_lines); + let expected = std::fs::read_to_string(badly_linted_output).unwrap(); + assert_eq!(output, expected); + + // Change content of the file again to be badly-linted1 + std::fs::copy(&badly_linted_fixed1, &badly_linted).unwrap(); + std::thread::sleep(std::time::Duration::from_secs(1)); + + output = read_all_lints(&mut stderr_lines); + let expected = std::fs::read_to_string(badly_linted_fixed1_output).unwrap(); + assert_eq!(output, expected); + + // Change content of the file again to be badly-linted1 + std::fs::copy(&badly_linted_fixed2, &badly_linted).unwrap(); + + output = read_all_lints(&mut stderr_lines); + let expected = std::fs::read_to_string(badly_linted_fixed2_output).unwrap(); + assert_eq!(output, expected); + + // the watcher process is still alive + assert!(child.try_wait().unwrap().is_none()); + + child.kill().unwrap(); + drop(t); + } + + #[test] + fn lint_watch_without_args_test() { + let t = TempDir::new(); + let badly_linted_original = + util::testdata_path().join("lint/watch/badly_linted.js"); + let badly_linted_output = + util::testdata_path().join("lint/watch/badly_linted.js.out"); + let badly_linted_fixed1 = + util::testdata_path().join("lint/watch/badly_linted_fixed1.js"); + let badly_linted_fixed1_output = + util::testdata_path().join("lint/watch/badly_linted_fixed1.js.out"); + let badly_linted_fixed2 = + util::testdata_path().join("lint/watch/badly_linted_fixed2.js"); + let badly_linted_fixed2_output = + util::testdata_path().join("lint/watch/badly_linted_fixed2.js.out"); + let badly_linted = t.path().join("badly_linted.js"); + + std::fs::copy(&badly_linted_original, &badly_linted).unwrap(); + + let mut child = util::deno_cmd() + .current_dir(t.path()) + .arg("lint") + .arg("--watch") + .arg("--unstable") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); + + let next_line = stderr_lines.next().unwrap(); + assert_contains!(&next_line, "Lint started"); + let mut output = read_all_lints(&mut stderr_lines); + let expected = std::fs::read_to_string(badly_linted_output).unwrap(); + assert_eq!(output, expected); + + // Change content of the file again to be badly-linted1 + std::fs::copy(&badly_linted_fixed1, &badly_linted).unwrap(); + + output = read_all_lints(&mut stderr_lines); + let expected = std::fs::read_to_string(badly_linted_fixed1_output).unwrap(); + assert_eq!(output, expected); + + // Change content of the file again to be badly-linted1 + std::fs::copy(&badly_linted_fixed2, &badly_linted).unwrap(); + std::thread::sleep(std::time::Duration::from_secs(1)); + + output = read_all_lints(&mut stderr_lines); + let expected = std::fs::read_to_string(badly_linted_fixed2_output).unwrap(); + assert_eq!(output, expected); + + // the watcher process is still alive + assert!(child.try_wait().unwrap().is_none()); + + child.kill().unwrap(); + drop(t); + } + + #[test] + fn lint_all_files_on_each_change_test() { + let t = TempDir::new(); + let badly_linted_fixed0 = + util::testdata_path().join("lint/watch/badly_linted.js"); + let badly_linted_fixed1 = + util::testdata_path().join("lint/watch/badly_linted_fixed1.js"); + let badly_linted_fixed2 = + util::testdata_path().join("lint/watch/badly_linted_fixed2.js"); + + let badly_linted_1 = t.path().join("badly_linted_1.js"); + let badly_linted_2 = t.path().join("badly_linted_2.js"); + std::fs::copy(&badly_linted_fixed0, &badly_linted_1).unwrap(); + std::fs::copy(&badly_linted_fixed1, &badly_linted_2).unwrap(); + + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("lint") + .arg(t.path()) + .arg("--watch") + .arg("--unstable") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); + + assert_contains!( + read_line("Checked", &mut stderr_lines), + "Checked 2 files" + ); + + std::fs::copy(&badly_linted_fixed2, &badly_linted_2).unwrap(); + + assert_contains!( + read_line("Checked", &mut stderr_lines), + "Checked 2 files" + ); + + assert!(child.try_wait().unwrap().is_none()); + + child.kill().unwrap(); + drop(t); + } + + #[test] + fn fmt_watch_test() { + let fmt_testdata_path = util::testdata_path().join("fmt"); + let t = TempDir::new(); + let fixed = fmt_testdata_path.join("badly_formatted_fixed.js"); + let badly_formatted_original = + fmt_testdata_path.join("badly_formatted.mjs"); + let badly_formatted = t.path().join("badly_formatted.js"); + std::fs::copy(&badly_formatted_original, &badly_formatted).unwrap(); + + let mut child = util::deno_cmd() + .current_dir(&fmt_testdata_path) + .arg("fmt") + .arg(&badly_formatted) + .arg("--watch") + .arg("--unstable") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); + + let next_line = stderr_lines.next().unwrap(); + assert_contains!(&next_line, "Fmt started"); + assert_contains!( + skip_restarting_line(&mut stderr_lines), + "badly_formatted.js" + ); + assert_contains!(read_line("Checked", &mut stderr_lines), "Checked 1 file"); + + let expected = std::fs::read_to_string(fixed.clone()).unwrap(); + let actual = std::fs::read_to_string(badly_formatted.clone()).unwrap(); + assert_eq!(actual, expected); + + // Change content of the file again to be badly formatted + std::fs::copy(&badly_formatted_original, &badly_formatted).unwrap(); + + assert_contains!( + skip_restarting_line(&mut stderr_lines), + "badly_formatted.js" + ); + assert_contains!(read_line("Checked", &mut stderr_lines), "Checked 1 file"); + + // Check if file has been automatically formatted by watcher + let expected = std::fs::read_to_string(fixed).unwrap(); + let actual = std::fs::read_to_string(badly_formatted).unwrap(); + assert_eq!(actual, expected); + check_alive_then_kill(child); + } + + #[test] + fn fmt_watch_without_args_test() { + let fmt_testdata_path = util::testdata_path().join("fmt"); + let t = TempDir::new(); + let fixed = fmt_testdata_path.join("badly_formatted_fixed.js"); + let badly_formatted_original = + fmt_testdata_path.join("badly_formatted.mjs"); + let badly_formatted = t.path().join("badly_formatted.js"); + std::fs::copy(&badly_formatted_original, &badly_formatted).unwrap(); + + let mut child = util::deno_cmd() + .current_dir(t.path()) + .arg("fmt") + .arg("--watch") + .arg("--unstable") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); + + let next_line = stderr_lines.next().unwrap(); + assert_contains!(&next_line, "Fmt started"); + assert_contains!( + skip_restarting_line(&mut stderr_lines), + "badly_formatted.js" + ); + assert_contains!(read_line("Checked", &mut stderr_lines), "Checked 1 file"); + + let expected = std::fs::read_to_string(fixed.clone()).unwrap(); + let actual = std::fs::read_to_string(badly_formatted.clone()).unwrap(); + assert_eq!(actual, expected); + + // Change content of the file again to be badly formatted + std::fs::copy(&badly_formatted_original, &badly_formatted).unwrap(); + assert_contains!( + skip_restarting_line(&mut stderr_lines), + "badly_formatted.js" + ); + assert_contains!(read_line("Checked", &mut stderr_lines), "Checked 1 file"); + + // Check if file has been automatically formatted by watcher + let expected = std::fs::read_to_string(fixed).unwrap(); + let actual = std::fs::read_to_string(badly_formatted).unwrap(); + assert_eq!(actual, expected); + check_alive_then_kill(child); + } + + #[test] + fn fmt_check_all_files_on_each_change_test() { + let t = TempDir::new(); + let fmt_testdata_path = util::testdata_path().join("fmt"); + let badly_formatted_original = + fmt_testdata_path.join("badly_formatted.mjs"); + let badly_formatted_1 = t.path().join("badly_formatted_1.js"); + let badly_formatted_2 = t.path().join("badly_formatted_2.js"); + std::fs::copy(&badly_formatted_original, &badly_formatted_1).unwrap(); + std::fs::copy(&badly_formatted_original, &badly_formatted_2).unwrap(); + + let mut child = util::deno_cmd() + .current_dir(&fmt_testdata_path) + .arg("fmt") + .arg(t.path()) + .arg("--watch") + .arg("--check") + .arg("--unstable") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (_stdout_lines, mut stderr_lines) = child_lines(&mut child); + + assert_contains!( + read_line("error", &mut stderr_lines), + "Found 2 not formatted files in 2 files" + ); + + // Change content of the file again to be badly formatted + std::fs::copy(&badly_formatted_original, &badly_formatted_1).unwrap(); + + assert_contains!( + read_line("error", &mut stderr_lines), + "Found 2 not formatted files in 2 files" + ); + + check_alive_then_kill(child); + } + + #[test] + fn bundle_js_watch() { + use std::path::PathBuf; + // Test strategy extends this of test bundle_js by adding watcher + let t = TempDir::new(); + let file_to_watch = t.path().join("file_to_watch.ts"); + write(&file_to_watch, "console.log('Hello world');").unwrap(); + assert!(file_to_watch.is_file()); + let t = TempDir::new(); + let bundle = t.path().join("mod6.bundle.js"); + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg(&file_to_watch) + .arg(&bundle) + .arg("--watch") + .arg("--unstable") + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let (_stdout_lines, mut stderr_lines) = child_lines(&mut deno); + + assert_contains!(stderr_lines.next().unwrap(), "Check"); + let next_line = stderr_lines.next().unwrap(); + assert_contains!(&next_line, "Bundle started"); + assert_contains!(stderr_lines.next().unwrap(), "file_to_watch.ts"); + assert_contains!(stderr_lines.next().unwrap(), "mod6.bundle.js"); + let file = PathBuf::from(&bundle); + assert!(file.is_file()); + wait_contains("Bundle finished", &mut stderr_lines); + + write(&file_to_watch, "console.log('Hello world2');").unwrap(); + + assert_contains!(stderr_lines.next().unwrap(), "Check"); + let next_line = stderr_lines.next().unwrap(); + assert_contains!(&next_line, CLEAR_SCREEN); + assert_contains!(&next_line, "File change detected!"); + assert_contains!(stderr_lines.next().unwrap(), "file_to_watch.ts"); + assert_contains!(stderr_lines.next().unwrap(), "mod6.bundle.js"); + let file = PathBuf::from(&bundle); + assert!(file.is_file()); + wait_contains("Bundle finished", &mut stderr_lines); + + // Confirm that the watcher keeps on working even if the file is updated and has invalid syntax + write(&file_to_watch, "syntax error ^^").unwrap(); + + assert_contains!(stderr_lines.next().unwrap(), "File change detected!"); + assert_contains!(stderr_lines.next().unwrap(), "error: "); + wait_contains("Bundle failed", &mut stderr_lines); + check_alive_then_kill(deno); + } + + /// Confirm that the watcher continues to work even if module resolution fails at the *first* attempt + #[test] + fn bundle_watch_not_exit() { + let t = TempDir::new(); + let file_to_watch = t.path().join("file_to_watch.ts"); + write(&file_to_watch, "syntax error ^^").unwrap(); + let target_file = t.path().join("target.js"); + + let mut deno = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("bundle") + .arg(&file_to_watch) + .arg(&target_file) + .arg("--watch") + .arg("--unstable") + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (_stdout_lines, mut stderr_lines) = child_lines(&mut deno); + + let next_line = stderr_lines.next().unwrap(); + assert_contains!(&next_line, "Bundle started"); + assert_contains!(stderr_lines.next().unwrap(), "error:"); + assert_contains!(stderr_lines.next().unwrap(), "Bundle failed"); + // the target file hasn't been created yet + assert!(!target_file.is_file()); + + // Make sure the watcher actually restarts and works fine with the proper syntax + write(&file_to_watch, "console.log(42);").unwrap(); + + assert_contains!(stderr_lines.next().unwrap(), "Check"); + let next_line = stderr_lines.next().unwrap(); + assert_contains!(&next_line, CLEAR_SCREEN); + assert_contains!(&next_line, "File change detected!"); + assert_contains!(stderr_lines.next().unwrap(), "file_to_watch.ts"); + assert_contains!(stderr_lines.next().unwrap(), "target.js"); + + wait_contains("Bundle finished", &mut stderr_lines); + + // bundled file is created + assert!(target_file.is_file()); + check_alive_then_kill(deno); + } + + #[test] + fn run_watch_no_dynamic() { + let t = TempDir::new(); + let file_to_watch = t.path().join("file_to_watch.js"); + write(&file_to_watch, "console.log('Hello world');").unwrap(); + + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--watch") + .arg("--unstable") + .arg("-L") + .arg("debug") + .arg(&file_to_watch) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); + + wait_contains("Hello world", &mut stdout_lines); + wait_for( + |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), + &mut stderr_lines, + ); + + // Change content of the file + write(&file_to_watch, "console.log('Hello world2');").unwrap(); + + wait_contains("Restarting", &mut stderr_lines); + wait_contains("Hello world2", &mut stdout_lines); + wait_for( + |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), + &mut stderr_lines, + ); + + // Add dependency + let another_file = t.path().join("another_file.js"); + write(&another_file, "export const foo = 0;").unwrap(); + write( + &file_to_watch, + "import { foo } from './another_file.js'; console.log(foo);", + ) + .unwrap(); + + wait_contains("Restarting", &mut stderr_lines); + wait_contains("0", &mut stdout_lines); + wait_for( + |m| m.contains("Watching paths") && m.contains("another_file.js"), + &mut stderr_lines, + ); + + // Confirm that restarting occurs when a new file is updated + write(&another_file, "export const foo = 42;").unwrap(); + + wait_contains("Restarting", &mut stderr_lines); + wait_contains("42", &mut stdout_lines); + wait_for( + |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), + &mut stderr_lines, + ); + + // Confirm that the watcher keeps on working even if the file is updated and has invalid syntax + write(&file_to_watch, "syntax error ^^").unwrap(); + + wait_contains("Restarting", &mut stderr_lines); + wait_contains("error:", &mut stderr_lines); + wait_for( + |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), + &mut stderr_lines, + ); + + // Then restore the file + write( + &file_to_watch, + "import { foo } from './another_file.js'; console.log(foo);", + ) + .unwrap(); + + wait_contains("Restarting", &mut stderr_lines); + wait_contains("42", &mut stdout_lines); + wait_for( + |m| m.contains("Watching paths") && m.contains("another_file.js"), + &mut stderr_lines, + ); + + // Update the content of the imported file with invalid syntax + write(&another_file, "syntax error ^^").unwrap(); + + wait_contains("Restarting", &mut stderr_lines); + wait_contains("error:", &mut stderr_lines); + wait_for( + |m| m.contains("Watching paths") && m.contains("another_file.js"), + &mut stderr_lines, + ); + + // Modify the imported file and make sure that restarting occurs + write(&another_file, "export const foo = 'modified!';").unwrap(); + + wait_contains("Restarting", &mut stderr_lines); + wait_contains("modified!", &mut stdout_lines); + wait_contains("Watching paths", &mut stderr_lines); + check_alive_then_kill(child); + } + + // TODO(bartlomieju): this test became flaky on macOS runner; it is unclear + // if that's because of a bug in code or the runner itself. We should reenable + // it once we upgrade to XL runners for macOS. + #[cfg(not(target_os = "macos"))] + #[test] + fn run_watch_external_watch_files() { + let t = TempDir::new(); + let file_to_watch = t.path().join("file_to_watch.js"); + write(&file_to_watch, "console.log('Hello world');").unwrap(); + + let external_file_to_watch = t.path().join("external_file_to_watch.txt"); + write(&external_file_to_watch, "Hello world").unwrap(); + + let mut watch_arg = "--watch=".to_owned(); + let external_file_to_watch_str = external_file_to_watch + .clone() + .into_os_string() + .into_string() + .unwrap(); + watch_arg.push_str(&external_file_to_watch_str); + + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg(watch_arg) + .arg("-L") + .arg("debug") + .arg("--unstable") + .arg(&file_to_watch) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); + wait_contains("Process started", &mut stderr_lines); + wait_contains("Hello world", &mut stdout_lines); + wait_for( + |m| { + m.contains("Watching paths") && m.contains("external_file_to_watch.txt") + }, + &mut stderr_lines, + ); + + // Change content of the external file + write(&external_file_to_watch, "Hello world2").unwrap(); + + wait_contains("Restarting", &mut stderr_lines); + wait_contains("Process finished", &mut stderr_lines); + check_alive_then_kill(child); + } + + #[test] + fn run_watch_load_unload_events() { + let t = TempDir::new(); + let file_to_watch = t.path().join("file_to_watch.js"); + write( + &file_to_watch, + r#" + setInterval(() => {}, 0); + window.addEventListener("load", () => { + console.log("load"); + }); + + window.addEventListener("unload", () => { + console.log("unload"); + }); + "#, + ) + .unwrap(); + + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--watch") + .arg("--unstable") + .arg("-L") + .arg("debug") + .arg(&file_to_watch) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); + + // Wait for the first load event to fire + wait_contains("load", &mut stdout_lines); + wait_for( + |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), + &mut stderr_lines, + ); + + // Change content of the file, this time without an interval to keep it alive. + write( + &file_to_watch, + r#" + window.addEventListener("load", () => { + console.log("load"); + }); + + window.addEventListener("unload", () => { + console.log("unload"); + }); + "#, + ) + .unwrap(); + + // Wait for the restart + wait_contains("Restarting", &mut stderr_lines); + + // Confirm that the unload event was dispatched from the first run + wait_contains("unload", &mut stdout_lines); + + // Followed by the load event of the second run + wait_contains("load", &mut stdout_lines); + + // Which is then unloaded as there is nothing keeping it alive. + wait_contains("unload", &mut stdout_lines); + check_alive_then_kill(child); + } + + /// Confirm that the watcher continues to work even if module resolution fails at the *first* attempt + #[test] + fn run_watch_not_exit() { + let t = TempDir::new(); + let file_to_watch = t.path().join("file_to_watch.js"); + write(&file_to_watch, "syntax error ^^").unwrap(); + + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--watch") + .arg("--unstable") + .arg("-L") + .arg("debug") + .arg(&file_to_watch) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); + + wait_contains("Process started", &mut stderr_lines); + wait_contains("error:", &mut stderr_lines); + wait_for( + |m| m.contains("Watching paths") && m.contains("file_to_watch.js"), + &mut stderr_lines, + ); + + // Make sure the watcher actually restarts and works fine with the proper syntax + write(&file_to_watch, "console.log(42);").unwrap(); + + wait_contains("Restarting", &mut stderr_lines); + wait_contains("42", &mut stdout_lines); + wait_contains("Process finished", &mut stderr_lines); + check_alive_then_kill(child); + } + + #[test] + fn run_watch_with_import_map_and_relative_paths() { + fn create_relative_tmp_file( + directory: &TempDir, + filename: &'static str, + filecontent: &'static str, + ) -> std::path::PathBuf { + let absolute_path = directory.path().join(filename); + write(&absolute_path, filecontent).unwrap(); + let relative_path = absolute_path + .strip_prefix(util::testdata_path()) + .unwrap() + .to_owned(); + assert!(relative_path.is_relative()); + relative_path + } + let temp_directory = TempDir::new_in(&util::testdata_path()); + let file_to_watch = create_relative_tmp_file( + &temp_directory, + "file_to_watch.js", + "console.log('Hello world');", + ); + let import_map_path = create_relative_tmp_file( + &temp_directory, + "import_map.json", + "{\"imports\": {}}", + ); + + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--unstable") + .arg("--watch") + .arg("--import-map") + .arg(&import_map_path) + .arg(&file_to_watch) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); + let next_line = stderr_lines.next().unwrap(); + assert_contains!(&next_line, "Process started"); + assert_contains!(stderr_lines.next().unwrap(), "Process finished"); + assert_contains!(stdout_lines.next().unwrap(), "Hello world"); + + check_alive_then_kill(child); + } + + #[test] + fn run_watch_error_messages() { + let t = TempDir::new(); + let file_to_watch = t.path().join("file_to_watch.js"); + write( + &file_to_watch, + "throw SyntaxError(`outer`, {cause: TypeError(`inner`)})", + ) + .unwrap(); + + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--watch") + .arg(&file_to_watch) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (_, mut stderr_lines) = child_lines(&mut child); + + wait_contains("Process started", &mut stderr_lines); + wait_contains("error: Uncaught SyntaxError: outer", &mut stderr_lines); + wait_contains("Caused by: TypeError: inner", &mut stderr_lines); + wait_contains("Process finished", &mut stderr_lines); + + check_alive_then_kill(child); + } + + #[test] + fn test_watch() { + let t = TempDir::new(); + + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("test") + .arg("--watch") + .arg("--unstable") + .arg("--no-check") + .arg(t.path()) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); + + assert_eq!(stdout_lines.next().unwrap(), ""); + assert_contains!(stdout_lines.next().unwrap(), "0 passed | 0 failed"); + wait_contains("Test finished", &mut stderr_lines); + + let foo_file = t.path().join("foo.js"); + let bar_file = t.path().join("bar.js"); + let foo_test = t.path().join("foo_test.js"); + let bar_test = t.path().join("bar_test.js"); + write(&foo_file, "export default function foo() { 1 + 1 }").unwrap(); + write(&bar_file, "export default function bar() { 2 + 2 }").unwrap(); + write( + &foo_test, + "import foo from './foo.js'; Deno.test('foo', foo);", + ) + .unwrap(); + write( + &bar_test, + "import bar from './bar.js'; Deno.test('bar', bar);", + ) + .unwrap(); + + assert_eq!(stdout_lines.next().unwrap(), ""); + assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); + assert_contains!(stdout_lines.next().unwrap(), "foo", "bar"); + assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); + assert_contains!(stdout_lines.next().unwrap(), "foo", "bar"); + stdout_lines.next(); + stdout_lines.next(); + stdout_lines.next(); + wait_contains("Test finished", &mut stderr_lines); + + // Change content of the file + write( + &foo_test, + "import foo from './foo.js'; Deno.test('foobar', foo);", + ) + .unwrap(); + + assert_contains!(stderr_lines.next().unwrap(), "Restarting"); + assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); + assert_contains!(stdout_lines.next().unwrap(), "foobar"); + stdout_lines.next(); + stdout_lines.next(); + stdout_lines.next(); + wait_contains("Test finished", &mut stderr_lines); + + // Add test + let another_test = t.path().join("new_test.js"); + write(&another_test, "Deno.test('another one', () => 3 + 3)").unwrap(); + assert_contains!(stderr_lines.next().unwrap(), "Restarting"); + assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); + assert_contains!(stdout_lines.next().unwrap(), "another one"); + stdout_lines.next(); + stdout_lines.next(); + stdout_lines.next(); + wait_contains("Test finished", &mut stderr_lines); + + // Confirm that restarting occurs when a new file is updated + write(&another_test, "Deno.test('another one', () => 3 + 3); Deno.test('another another one', () => 4 + 4)") + .unwrap(); + assert_contains!(stderr_lines.next().unwrap(), "Restarting"); + assert_contains!(stdout_lines.next().unwrap(), "running 2 tests"); + assert_contains!(stdout_lines.next().unwrap(), "another one"); + assert_contains!(stdout_lines.next().unwrap(), "another another one"); + stdout_lines.next(); + stdout_lines.next(); + stdout_lines.next(); + wait_contains("Test finished", &mut stderr_lines); + + // Confirm that the watcher keeps on working even if the file is updated and has invalid syntax + write(&another_test, "syntax error ^^").unwrap(); + assert_contains!(stderr_lines.next().unwrap(), "Restarting"); + assert_contains!(stderr_lines.next().unwrap(), "error:"); + assert_contains!(stderr_lines.next().unwrap(), "Test failed"); + + // Then restore the file + write(&another_test, "Deno.test('another one', () => 3 + 3)").unwrap(); + assert_contains!(stderr_lines.next().unwrap(), "Restarting"); + assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); + assert_contains!(stdout_lines.next().unwrap(), "another one"); + stdout_lines.next(); + stdout_lines.next(); + stdout_lines.next(); + wait_contains("Test finished", &mut stderr_lines); + + // Confirm that the watcher keeps on working even if the file is updated and the test fails + // This also confirms that it restarts when dependencies change + write( + &foo_file, + "export default function foo() { throw new Error('Whoops!'); }", + ) + .unwrap(); + assert_contains!(stderr_lines.next().unwrap(), "Restarting"); + assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); + assert_contains!(stdout_lines.next().unwrap(), "FAILED"); + wait_for(|m| m.contains("FAILED"), &mut stdout_lines); + stdout_lines.next(); + wait_contains("Test finished", &mut stderr_lines); + + // Then restore the file + write(&foo_file, "export default function foo() { 1 + 1 }").unwrap(); + assert_contains!(stderr_lines.next().unwrap(), "Restarting"); + assert_contains!(stdout_lines.next().unwrap(), "running 1 test"); + assert_contains!(stdout_lines.next().unwrap(), "foo"); + stdout_lines.next(); + stdout_lines.next(); + stdout_lines.next(); + wait_contains("Test finished", &mut stderr_lines); + + // Test that circular dependencies work fine + write( + &foo_file, + "import './bar.js'; export default function foo() { 1 + 1 }", + ) + .unwrap(); + write( + &bar_file, + "import './foo.js'; export default function bar() { 2 + 2 }", + ) + .unwrap(); + check_alive_then_kill(child); + } + + #[flaky_test] + fn test_watch_doc() { + let t = TempDir::new(); + + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("test") + .arg("--watch") + .arg("--doc") + .arg("--unstable") + .arg(t.path()) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); + + assert_eq!(stdout_lines.next().unwrap(), ""); + assert_contains!(stdout_lines.next().unwrap(), "0 passed | 0 failed"); + wait_contains("Test finished", &mut stderr_lines); + + let foo_file = t.path().join("foo.ts"); + write( + &foo_file, + r#" + export default function foo() {} + "#, + ) + .unwrap(); + + write( + &foo_file, + r#" + /** + * ```ts + * import foo from "./foo.ts"; + * ``` + */ + export default function foo() {} + "#, + ) + .unwrap(); + + // We only need to scan for a Check file://.../foo.ts$3-6 line that + // corresponds to the documentation block being type-checked. + assert_contains!(skip_restarting_line(&mut stderr_lines), "foo.ts$3-6"); + check_alive_then_kill(child); + } + + #[test] + fn test_watch_module_graph_error_referrer() { + let t = TempDir::new(); + let file_to_watch = t.path().join("file_to_watch.js"); + write(&file_to_watch, "import './nonexistent.js';").unwrap(); + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--watch") + .arg("--unstable") + .arg(&file_to_watch) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (_, mut stderr_lines) = child_lines(&mut child); + let line1 = stderr_lines.next().unwrap(); + assert_contains!(&line1, "Process started"); + let line2 = stderr_lines.next().unwrap(); + assert_contains!(&line2, "error: Module not found"); + assert_contains!(&line2, "nonexistent.js"); + let line3 = stderr_lines.next().unwrap(); + assert_contains!(&line3, " at "); + assert_contains!(&line3, "file_to_watch.js"); + wait_contains("Process finished", &mut stderr_lines); + check_alive_then_kill(child); + } + + // Regression test for https://github.com/denoland/deno/issues/15428. + #[test] + fn test_watch_unload_handler_error_on_drop() { + let t = TempDir::new(); + let file_to_watch = t.path().join("file_to_watch.js"); + write( + &file_to_watch, + r#" + addEventListener("unload", () => { + throw new Error("foo"); + }); + setTimeout(() => { + throw new Error("bar"); + }); + "#, + ) + .unwrap(); + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--watch") + .arg(&file_to_watch) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (_, mut stderr_lines) = child_lines(&mut child); + wait_contains("Process started", &mut stderr_lines); + wait_contains("Uncaught Error: bar", &mut stderr_lines); + wait_contains("Process finished", &mut stderr_lines); + check_alive_then_kill(child); + } + + #[test] + fn run_watch_dynamic_imports() { + let t = TempDir::new(); + let file_to_watch = t.path().join("file_to_watch.js"); + write( + &file_to_watch, + r#" + console.log("Hopefully dynamic import will be watched..."); + await import("./imported.js"); + "#, + ) + .unwrap(); + let file_to_watch2 = t.path().join("imported.js"); + write( + &file_to_watch2, + r#" + import "./imported2.js"; + console.log("I'm dynamically imported and I cause restarts!"); + "#, + ) + .unwrap(); + let file_to_watch3 = t.path().join("imported2.js"); + write( + &file_to_watch3, + r#" + console.log("I'm statically imported from the dynamic import"); + "#, + ) + .unwrap(); + + let mut child = util::deno_cmd() + .current_dir(util::testdata_path()) + .arg("run") + .arg("--watch") + .arg("--unstable") + .arg("--allow-read") + .arg("-L") + .arg("debug") + .arg(&file_to_watch) + .env("NO_COLOR", "1") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (mut stdout_lines, mut stderr_lines) = child_lines(&mut child); + + assert_contains!(stderr_lines.next().unwrap(), "Process started"); + + wait_contains( + "Hopefully dynamic import will be watched...", + &mut stdout_lines, + ); + wait_contains( + "I'm statically imported from the dynamic import", + &mut stdout_lines, + ); + wait_contains( + "I'm dynamically imported and I cause restarts!", + &mut stdout_lines, + ); + + wait_contains("finished", &mut stderr_lines); + wait_for( + |m| m.contains("Watching paths") && m.contains("imported2.js"), + &mut stderr_lines, + ); + + write( + &file_to_watch3, + r#" + console.log("I'm statically imported from the dynamic import and I've changed"); + "#, + ) + .unwrap(); + + wait_contains("Restarting", &mut stderr_lines); + wait_contains( + "Hopefully dynamic import will be watched...", + &mut stdout_lines, + ); + wait_contains( + "I'm statically imported from the dynamic import and I've changed", + &mut stdout_lines, + ); + wait_contains( + "I'm dynamically imported and I cause restarts!", + &mut stdout_lines, + ); + + check_alive_then_kill(child); + } +} diff --git a/cli/tests/worker_tests.rs b/cli/tests/worker_tests.rs new file mode 100644 index 0000000000..1c74225e31 --- /dev/null +++ b/cli/tests/worker_tests.rs @@ -0,0 +1,116 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +mod integration; + +mod worker { + use super::*; + + itest!(workers { + args: "test --reload --location http://127.0.0.1:4545/ -A --unstable workers/test.ts", + output: "workers/test.ts.out", + http_server: true, + }); + + itest!(worker_error { + args: "run -A workers/worker_error.ts", + output: "workers/worker_error.ts.out", + exit_code: 1, + }); + + itest!(worker_nested_error { + args: "run -A workers/worker_nested_error.ts", + output: "workers/worker_nested_error.ts.out", + exit_code: 1, + }); + + itest!(worker_async_error { + args: "run -A --quiet --reload workers/worker_async_error.ts", + output: "workers/worker_async_error.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(worker_message_handler_error { + args: "run -A --quiet --reload workers/worker_message_handler_error.ts", + output: "workers/worker_message_handler_error.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(nonexistent_worker { + args: "run --allow-read workers/nonexistent_worker.ts", + output: "workers/nonexistent_worker.out", + exit_code: 1, + }); + + itest!(_084_worker_custom_inspect { + args: "run --allow-read workers/custom_inspect/main.ts", + output: "workers/custom_inspect/main.out", + }); + + itest!(error_worker_permissions_local { + args: "run --reload workers/error_worker_permissions_local.ts", + output: "workers/error_worker_permissions_local.ts.out", + exit_code: 1, + }); + + itest!(error_worker_permissions_remote { + args: "run --reload workers/error_worker_permissions_remote.ts", + http_server: true, + output: "workers/error_worker_permissions_remote.ts.out", + exit_code: 1, + }); + + itest!(worker_permissions_remote_remote { + args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_remote_remote.ts", + output: "workers/permissions_remote_remote.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(worker_permissions_dynamic_remote { + args: "run --quiet --reload --allow-net --unstable workers/permissions_dynamic_remote.ts", + output: "workers/permissions_dynamic_remote.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(worker_permissions_data_remote { + args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_data_remote.ts", + output: "workers/permissions_data_remote.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(worker_permissions_blob_remote { + args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_blob_remote.ts", + output: "workers/permissions_blob_remote.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(worker_permissions_data_local { + args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_data_local.ts", + output: "workers/permissions_data_local.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(worker_permissions_blob_local { + args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_blob_local.ts", + output: "workers/permissions_blob_local.ts.out", + http_server: true, + exit_code: 1, + }); + + itest!(worker_terminate_tla_crash { + args: "run --quiet --reload workers/terminate_tla_crash.js", + output: "workers/terminate_tla_crash.js.out", + }); + + itest!(worker_error_event { + args: "run --quiet -A workers/error_event.ts", + output: "workers/error_event.ts.out", + exit_code: 1, + }); +} diff --git a/cli/tools/bench.rs b/cli/tools/bench.rs index a81c0a406e..eeda3ea1a2 100644 --- a/cli/tools/bench.rs +++ b/cli/tools/bench.rs @@ -4,16 +4,16 @@ use crate::args::BenchFlags; use crate::args::Flags; use crate::args::TypeCheckMode; use crate::colors; -use crate::file_watcher; -use crate::file_watcher::ResolutionResult; -use crate::fs_util::collect_specifiers; -use crate::fs_util::is_supported_bench_path; use crate::graph_util::contains_specifier; use crate::graph_util::graph_valid; use crate::ops; use crate::proc_state::ProcState; use crate::tools::test::format_test_error; use crate::tools::test::TestFilter; +use crate::util::file_watcher; +use crate::util::file_watcher::ResolutionResult; +use crate::util::fs::collect_specifiers; +use crate::util::path::is_supported_ext; use crate::worker::create_main_worker_for_test_or_bench; use deno_core::error::generic_error; @@ -32,6 +32,7 @@ use log::Level; use serde::Deserialize; use serde::Serialize; use std::collections::HashSet; +use std::path::Path; use std::path::PathBuf; use tokio::sync::mpsc::unbounded_channel; use tokio::sync::mpsc::UnboundedSender; @@ -469,6 +470,19 @@ async fn bench_specifiers( Ok(()) } +/// Checks if the path has a basename and extension Deno supports for benches. +fn is_supported_bench_path(path: &Path) -> bool { + if let Some(name) = path.file_stem() { + let basename = name.to_string_lossy(); + (basename.ends_with("_bench") + || basename.ends_with(".bench") + || basename == "bench") + && is_supported_ext(path) + } else { + false + } +} + pub async fn run_benchmarks( flags: Flags, bench_flags: BenchFlags, diff --git a/cli/tools/coverage/mod.rs b/cli/tools/coverage/mod.rs index b76792b1e6..aacaf3d836 100644 --- a/cli/tools/coverage/mod.rs +++ b/cli/tools/coverage/mod.rs @@ -3,10 +3,11 @@ use crate::args::CoverageFlags; use crate::args::Flags; use crate::colors; -use crate::fs_util::collect_files; +use crate::emit::get_source_hash; use crate::proc_state::ProcState; -use crate::text_encoding::source_map_from_code; use crate::tools::fmt::format_json; +use crate::util::fs::FileCollector; +use crate::util::text_encoding::source_map_from_code; use deno_ast::MediaType; use deno_ast::ModuleSpecifier; @@ -557,9 +558,13 @@ fn collect_coverages( ignore: Vec, ) -> Result, AnyError> { let mut coverages: Vec = Vec::new(); - let file_paths = collect_files(&files, &ignore, |file_path| { + let file_paths = FileCollector::new(|file_path| { file_path.extension().map_or(false, |ext| ext == "json") - })?; + }) + .ignore_git_folder() + .ignore_node_modules() + .add_ignore_paths(&ignore) + .collect_files(&files)?; for file_path in file_paths { let json = fs::read_to_string(file_path.as_path())?; @@ -677,7 +682,8 @@ pub async fn cover_files( | MediaType::Mts | MediaType::Cts | MediaType::Tsx => { - match ps.emit_cache.get_emit_code(&file.specifier, None) { + let source_hash = get_source_hash(&file.source, ps.emit_options_hash); + match ps.emit_cache.get_emit_code(&file.specifier, source_hash) { Some(code) => code, None => { return Err(anyhow!( diff --git a/cli/tools/doc.rs b/cli/tools/doc.rs index e301c0000f..30211d3793 100644 --- a/cli/tools/doc.rs +++ b/cli/tools/doc.rs @@ -49,7 +49,6 @@ pub async fn print_docs( is_dynamic: false, imports: None, resolver: None, - locker: None, module_analyzer: Some(&analyzer), reporter: None, }, diff --git a/cli/tools/fmt.rs b/cli/tools/fmt.rs index 9474411b7d..7b5797d887 100644 --- a/cli/tools/fmt.rs +++ b/cli/tools/fmt.rs @@ -12,13 +12,13 @@ use crate::args::FmtFlags; use crate::args::FmtOptionsConfig; use crate::args::ProseWrap; use crate::colors; -use crate::diff::diff; -use crate::file_watcher; -use crate::file_watcher::ResolutionResult; -use crate::fs_util::collect_files; -use crate::fs_util::get_extension; -use crate::fs_util::specifier_to_file_path; -use crate::text_encoding; +use crate::util::diff::diff; +use crate::util::file_watcher; +use crate::util::file_watcher::ResolutionResult; +use crate::util::fs::FileCollector; +use crate::util::path::get_extension; +use crate::util::path::specifier_to_file_path; +use crate::util::text_encoding; use deno_ast::ParsedSource; use deno_core::anyhow::bail; use deno_core::anyhow::Context; @@ -92,17 +92,11 @@ pub async fn format( maybe_fmt_config.map(|c| c.options).unwrap_or_default(), ); - let fmt_predicate = |path: &Path| { - is_supported_ext_fmt(path) - && !contains_git(path) - && !contains_node_modules(path) - }; - let resolver = |changed: Option>| { let files_changed = changed.is_some(); - let result = collect_files(&include_files, &exclude_files, fmt_predicate) - .map(|files| { + let result = + collect_fmt_files(&include_files, &exclude_files).map(|files| { let refmt_files = if let Some(paths) = changed { if check { files @@ -164,8 +158,8 @@ pub async fn format( ) .await?; } else { - let files = collect_files(&include_files, &exclude_files, fmt_predicate) - .and_then(|files| { + let files = + collect_fmt_files(&include_files, &exclude_files).and_then(|files| { if files.is_empty() { Err(generic_error("No target files found.")) } else { @@ -178,6 +172,17 @@ pub async fn format( Ok(()) } +fn collect_fmt_files( + include_files: &[PathBuf], + exclude_files: &[PathBuf], +) -> Result, AnyError> { + FileCollector::new(is_supported_ext_fmt) + .ignore_git_folder() + .ignore_node_modules() + .add_ignore_paths(exclude_files) + .collect_files(include_files) +} + /// Formats markdown (using ) and its code blocks /// (ts/tsx, js/jsx). fn format_markdown( @@ -734,14 +739,6 @@ fn is_supported_ext_fmt(path: &Path) -> bool { } } -fn contains_git(path: &Path) -> bool { - path.components().any(|c| c.as_os_str() == ".git") -} - -fn contains_node_modules(path: &Path) -> bool { - path.components().any(|c| c.as_os_str() == "node_modules") -} - #[cfg(test)] mod test { use super::*; @@ -773,26 +770,6 @@ mod test { assert!(is_supported_ext_fmt(Path::new("foo.JsON"))); } - #[test] - fn test_is_located_in_git() { - assert!(contains_git(Path::new("test/.git"))); - assert!(contains_git(Path::new(".git/bad.json"))); - assert!(contains_git(Path::new("test/.git/bad.json"))); - assert!(!contains_git(Path::new("test/bad.git/bad.json"))); - } - - #[test] - fn test_is_located_in_node_modules() { - assert!(contains_node_modules(Path::new("test/node_modules"))); - assert!(contains_node_modules(Path::new("node_modules/bad.json"))); - assert!(contains_node_modules(Path::new( - "test/node_modules/bad.json" - ))); - assert!(!contains_node_modules(Path::new( - "test/bad.node_modules/bad.json" - ))); - } - #[test] #[should_panic(expected = "Formatting not stable. Bailed after 5 tries.")] fn test_format_ensure_stable_unstable_format() { diff --git a/cli/tools/info.rs b/cli/tools/info.rs index 38aa40a5e3..f494c8d009 100644 --- a/cli/tools/info.rs +++ b/cli/tools/info.rs @@ -20,7 +20,6 @@ use deno_runtime::colors; use crate::args::Flags; use crate::args::InfoFlags; -use crate::checksum; use crate::display; use crate::npm::NpmPackageId; use crate::npm::NpmPackageReference; @@ -29,6 +28,7 @@ use crate::npm::NpmPackageResolver; use crate::npm::NpmResolutionPackage; use crate::npm::NpmResolutionSnapshot; use crate::proc_state::ProcState; +use crate::util::checksum; pub async fn info(flags: Flags, info_flags: InfoFlags) -> Result<(), AnyError> { let ps = ProcState::build(flags).await?; @@ -311,7 +311,7 @@ impl NpmInfo { } for (specifier, _) in graph.specifiers() { - if let Ok(reference) = NpmPackageReference::from_specifier(&specifier) { + if let Ok(reference) = NpmPackageReference::from_specifier(specifier) { info .specifiers .insert(specifier.clone(), reference.req.clone()); @@ -421,9 +421,8 @@ impl<'a> GraphDisplayContext<'a> { } } writeln!(writer, "{} {}", colors::bold("type:"), root.media_type)?; - let modules = self.graph.modules(); let total_modules_size = - modules.iter().map(|m| m.size() as f64).sum::(); + self.graph.modules().map(|m| m.size() as f64).sum::(); let total_npm_package_size = self .npm_info .package_sizes @@ -431,7 +430,8 @@ impl<'a> GraphDisplayContext<'a> { .map(|s| *s as f64) .sum::(); let total_size = total_modules_size + total_npm_package_size; - let dep_count = modules.len() - 1 + self.npm_info.packages.len() + let dep_count = self.graph.modules().count() - 1 + + self.npm_info.packages.len() - self.npm_info.resolved_reqs.len(); writeln!( writer, @@ -595,9 +595,6 @@ impl<'a> GraphDisplayContext<'a> { ) -> TreeNode { self.seen.insert(specifier.to_string()); match err { - ModuleGraphError::InvalidSource(_, _) => { - self.build_error_msg(specifier, "(invalid source)") - } ModuleGraphError::InvalidTypeAssertion { .. } => { self.build_error_msg(specifier, "(invalid import assertion)") } diff --git a/cli/tools/installer.rs b/cli/tools/installer.rs index b964619d98..6914c99193 100644 --- a/cli/tools/installer.rs +++ b/cli/tools/installer.rs @@ -4,8 +4,8 @@ use crate::args::ConfigFlag; use crate::args::Flags; use crate::args::InstallFlags; use crate::args::TypeCheckMode; -use crate::fs_util; use crate::npm::NpmPackageReference; +use crate::util::fs::canonicalize_path_maybe_not_exists; use deno_core::anyhow::Context; use deno_core::error::generic_error; use deno_core::error::AnyError; @@ -107,9 +107,7 @@ exec deno {} "$@" fn get_installer_root() -> Result { if let Ok(env_dir) = env::var("DENO_INSTALL_ROOT") { if !env_dir.is_empty() { - return fs_util::canonicalize_path_maybe_not_exists(&PathBuf::from( - env_dir, - )); + return canonicalize_path_maybe_not_exists(&PathBuf::from(env_dir)); } } // Note: on Windows, the $HOME environment variable may be set by users or by @@ -167,7 +165,7 @@ pub fn infer_name_from_url(url: &Url) -> Option { pub fn uninstall(name: String, root: Option) -> Result<(), AnyError> { let root = if let Some(root) = root { - fs_util::canonicalize_path_maybe_not_exists(&root)? + canonicalize_path_maybe_not_exists(&root)? } else { get_installer_root()? }; @@ -275,7 +273,7 @@ fn resolve_shim_data( install_flags: &InstallFlags, ) -> Result { let root = if let Some(root) = &install_flags.root { - fs_util::canonicalize_path_maybe_not_exists(root)? + canonicalize_path_maybe_not_exists(root)? } else { get_installer_root()? }; @@ -450,6 +448,7 @@ mod tests { use super::*; use crate::args::ConfigFlag; + use crate::util::fs::canonicalize_path; use std::process::Command; use test_util::testdata_path; use test_util::TempDir; @@ -746,7 +745,7 @@ mod tests { #[test] fn install_npm_lockfile_default() { - let temp_dir = fs_util::canonicalize_path(&env::temp_dir()).unwrap(); + let temp_dir = canonicalize_path(&env::temp_dir()).unwrap(); let shim_data = resolve_shim_data( &Flags { allow_all: true, diff --git a/cli/tools/lint.rs b/cli/tools/lint.rs index bfbff8005e..1b2487e4cd 100644 --- a/cli/tools/lint.rs +++ b/cli/tools/lint.rs @@ -10,13 +10,13 @@ use crate::args::Flags; use crate::args::LintConfig; use crate::args::LintFlags; use crate::colors; -use crate::file_watcher; -use crate::file_watcher::ResolutionResult; -use crate::fs_util::collect_files; -use crate::fs_util::is_supported_ext; -use crate::fs_util::specifier_to_file_path; use crate::proc_state::ProcState; use crate::tools::fmt::run_parallelized; +use crate::util::file_watcher; +use crate::util::file_watcher::ResolutionResult; +use crate::util::fs::FileCollector; +use crate::util::path::is_supported_ext; +use crate::util::path::specifier_to_file_path; use deno_ast::MediaType; use deno_core::anyhow::anyhow; use deno_core::error::generic_error; @@ -143,19 +143,17 @@ pub async fn lint(flags: Flags, lint_flags: LintFlags) -> Result<(), AnyError> { let resolver = |changed: Option>| { let files_changed = changed.is_some(); let result = - collect_files(&include_files, &exclude_files, is_supported_ext).map( - |files| { - if let Some(paths) = changed { - files - .iter() - .any(|path| paths.contains(path)) - .then_some(files) - .unwrap_or_else(|| [].to_vec()) - } else { - files - } - }, - ); + collect_lint_files(&include_files, &exclude_files).map(|files| { + if let Some(paths) = changed { + files + .iter() + .any(|path| paths.contains(path)) + .then_some(files) + .unwrap_or_else(|| [].to_vec()) + } else { + files + } + }); let paths_to_watch = include_files.clone(); @@ -251,15 +249,14 @@ pub async fn lint(flags: Flags, lint_flags: LintFlags) -> Result<(), AnyError> { ); reporter_lock.lock().unwrap().close(1); } else { - let target_files = - collect_files(&include_files, &exclude_files, is_supported_ext) - .and_then(|files| { - if files.is_empty() { - Err(generic_error("No target files found.")) - } else { - Ok(files) - } - })?; + let target_files = collect_lint_files(&include_files, &exclude_files) + .and_then(|files| { + if files.is_empty() { + Err(generic_error("No target files found.")) + } else { + Ok(files) + } + })?; debug!("Found {} files", target_files.len()); operation(target_files).await?; }; @@ -272,6 +269,17 @@ pub async fn lint(flags: Flags, lint_flags: LintFlags) -> Result<(), AnyError> { Ok(()) } +fn collect_lint_files( + include_files: &[PathBuf], + exclude_files: &[PathBuf], +) -> Result, AnyError> { + FileCollector::new(is_supported_ext) + .ignore_git_folder() + .ignore_node_modules() + .add_ignore_paths(exclude_files) + .collect_files(include_files) +} + pub fn print_rules_list(json: bool) { let lint_rules = rules::get_recommended_rules(); diff --git a/cli/tools/repl/mod.rs b/cli/tools/repl/mod.rs index 28ad41375a..bf9a6f6eb4 100644 --- a/cli/tools/repl/mod.rs +++ b/cli/tools/repl/mod.rs @@ -1,5 +1,7 @@ // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. +use crate::args::ReplFlags; +use crate::colors; use crate::proc_state::ProcState; use crate::worker::create_main_worker_with_extensions; use deno_core::anyhow::Context; @@ -105,8 +107,7 @@ pub fn op_repl_save( async fn create_repl_session( ps: &ProcState, module_url: ModuleSpecifier, - maybe_eval_files: Option>, - maybe_eval: Option, + repl_flags: ReplFlags, ) -> Result { let extension = Extension::builder() .ops(vec![op_repl_reload::decl(), op_repl_save::decl()]) @@ -129,9 +130,10 @@ async fn create_repl_session( .await?; worker.setup_repl().await?; let worker = worker.into_main_worker(); + let mut repl_session = ReplSession::initialize(worker).await?; - if let Some(eval_files) = maybe_eval_files { + if let Some(eval_files) = repl_flags.eval_files { for eval_file in eval_files { match read_eval_file(ps, &eval_file).await { Ok(eval_source) => { @@ -140,21 +142,24 @@ async fn create_repl_session( .await?; // only output errors if let EvaluationOutput::Error(error_text) = output { - println!("error in --eval-file file {}. {}", eval_file, error_text); + println!( + "Error in --eval-file file \"{}\": {}", + eval_file, error_text + ); } } Err(e) => { - println!("error in --eval-file file {}. {}", eval_file, e); + println!("Error in --eval-file file \"{}\": {}", eval_file, e); } } } } - if let Some(eval) = maybe_eval { + if let Some(eval) = repl_flags.eval { let output = repl_session.evaluate_line_and_get_output(&eval).await?; // only output errors if let EvaluationOutput::Error(error_text) = output { - println!("error in --eval flag. {}", error_text); + println!("Error in --eval flag: {}", error_text); } } @@ -178,16 +183,10 @@ fn save_session_to_file( pub async fn run( ps: &ProcState, module_url: ModuleSpecifier, - maybe_eval_files: Option>, - maybe_eval: Option, + repl_flags: ReplFlags, ) -> Result { - let mut repl_session = create_repl_session( - ps, - module_url.clone(), - maybe_eval_files.clone(), - maybe_eval.clone(), - ) - .await?; + let mut repl_session = + create_repl_session(ps, module_url.clone(), repl_flags.clone()).await?; let mut rustyline_channel = rustyline_channel(); let mut should_exit_on_interrupt = false; @@ -200,9 +199,20 @@ pub async fn run( let history_file_path = ps.dir.repl_history_file_path(); let editor = ReplEditor::new(helper, history_file_path)?; - println!("Deno {}", crate::version::deno()); - println!("Run repl.help() for help"); - println!("Exit using ctrl+d, ctrl+c, or close()"); + // Doing this manually, instead of using `log::info!` because these messages + // are supposed to go to stdout, not stderr. + if !ps.options.is_quiet() { + println!("Deno {}", crate::version::deno()); + println!("Run repl.help() for help"); + println!("exit using ctrl+d, ctrl+c, or close()"); + if repl_flags.is_default_command { + println!( + "{}", + colors::yellow("REPL is running with all permissions allowed.") + ); + println!("To specify permissions, run `deno repl` with allow flags.") + } + } let mut session_history: Vec = vec![]; loop { @@ -236,13 +246,9 @@ pub async fn run( }; if repl_state.needs_reload { drop(op_state); - repl_session = create_repl_session( - ps, - module_url.clone(), - maybe_eval_files.clone(), - maybe_eval.clone(), - ) - .await?; + repl_session = + create_repl_session(ps, module_url.clone(), repl_flags.clone()) + .await?; println!("Started a new REPL session. Global scope is now clean."); } else if repl_state.needs_save { let mut op_state = op_state.borrow_mut(); diff --git a/cli/tools/repl/session.rs b/cli/tools/repl/session.rs index 9b921dfc0a..1c65bb471d 100644 --- a/cli/tools/repl/session.rs +++ b/cli/tools/repl/session.rs @@ -119,17 +119,19 @@ impl ReplSession { for notification in session.notifications() { let method = notification.get("method").unwrap().as_str().unwrap(); let params = notification.get("params").unwrap(); - if method == "Runtime.executionContextCreated" { - context_id = params - .get("context") + let context = params.get("context").unwrap(); + assert!(context + .get("auxData") .unwrap() - .get("id") + .get("isDefault") .unwrap() - .as_u64() - .unwrap(); + .as_bool() + .unwrap()); + context_id = context.get("id").unwrap().as_u64().unwrap(); } } + assert_ne!(context_id, 0); let mut repl_session = ReplSession { worker, diff --git a/cli/tools/standalone.rs b/cli/tools/standalone.rs index f173103cb2..4436aaa282 100644 --- a/cli/tools/standalone.rs +++ b/cli/tools/standalone.rs @@ -6,9 +6,9 @@ use crate::args::Flags; use crate::args::RunFlags; use crate::args::TypeCheckMode; use crate::cache::DenoDir; -use crate::fs_util; use crate::standalone::Metadata; use crate::standalone::MAGIC_TRAILER; +use crate::util::path::path_has_trailing_slash; use crate::ProcState; use deno_core::anyhow::bail; use deno_core::anyhow::Context; @@ -299,7 +299,7 @@ pub fn resolve_compile_executable_output_path( ) -> Result { let module_specifier = resolve_url_or_path(&compile_flags.source_file)?; compile_flags.output.as_ref().and_then(|output| { - if fs_util::path_has_trailing_slash(output) { + if path_has_trailing_slash(output) { let infer_file_name = infer_name_from_url(&module_specifier).map(PathBuf::from)?; Some(output.join(infer_file_name)) } else { diff --git a/cli/tools/task.rs b/cli/tools/task.rs index 4cbba8661d..39d493492f 100644 --- a/cli/tools/task.rs +++ b/cli/tools/task.rs @@ -3,8 +3,8 @@ use crate::args::Flags; use crate::args::TaskFlags; use crate::colors; -use crate::fs_util; use crate::proc_state::ProcState; +use crate::util::fs::canonicalize_path; use deno_core::anyhow::bail; use deno_core::anyhow::Context; use deno_core::error::AnyError; @@ -40,7 +40,7 @@ pub async fn execute_script( } let cwd = match task_flags.cwd { - Some(path) => fs_util::canonicalize_path(&PathBuf::from(path))?, + Some(path) => canonicalize_path(&PathBuf::from(path))?, None => config_file_path.parent().unwrap().to_owned(), }; let task_name = task_flags.task; diff --git a/cli/tools/test.rs b/cli/tools/test.rs index 1bb891a1ea..5fa72f7a7c 100644 --- a/cli/tools/test.rs +++ b/cli/tools/test.rs @@ -3,20 +3,20 @@ use crate::args::Flags; use crate::args::TestFlags; use crate::args::TypeCheckMode; -use crate::checksum; use crate::colors; use crate::display; use crate::file_fetcher::File; -use crate::file_watcher; -use crate::file_watcher::ResolutionResult; -use crate::fs_util::collect_specifiers; -use crate::fs_util::is_supported_test_ext; -use crate::fs_util::is_supported_test_path; -use crate::fs_util::specifier_to_file_path; use crate::graph_util::contains_specifier; use crate::graph_util::graph_valid; use crate::ops; use crate::proc_state::ProcState; +use crate::util::checksum; +use crate::util::file_watcher; +use crate::util::file_watcher::ResolutionResult; +use crate::util::fs::collect_specifiers; +use crate::util::path::get_extension; +use crate::util::path::is_supported_ext; +use crate::util::path::specifier_to_file_path; use crate::worker::create_main_worker_for_test_or_bench; use deno_ast::swc::common::comments::CommentKind; @@ -51,7 +51,9 @@ use std::fmt::Write as _; use std::io::Read; use std::io::Write; use std::num::NonZeroUsize; +use std::path::Path; use std::path::PathBuf; +use std::sync::atomic::AtomicUsize; use std::sync::Arc; use std::time::Duration; use std::time::Instant; @@ -712,18 +714,25 @@ async fn test_specifier( permissions: Permissions, specifier: ModuleSpecifier, mode: TestMode, - sender: &TestEventSender, + sender: TestEventSender, + fail_fast_tracker: FailFastTracker, options: TestSpecifierOptions, ) -> Result<(), AnyError> { + let stdout = StdioPipe::File(sender.stdout()); + let stderr = StdioPipe::File(sender.stderr()); let mut worker = create_main_worker_for_test_or_bench( &ps, specifier.clone(), permissions, - vec![ops::testing::init(sender.clone(), options.filter.clone())], + vec![ops::testing::init( + sender, + fail_fast_tracker, + options.filter.clone(), + )], Stdio { stdin: StdioPipe::Inherit, - stdout: StdioPipe::File(sender.stdout()), - stderr: StdioPipe::File(sender.stderr()), + stdout, + stderr, }, ) .await?; @@ -998,9 +1007,9 @@ async fn test_specifiers( }; let (sender, mut receiver) = unbounded_channel::(); + let fail_fast_tracker = FailFastTracker::new(options.fail_fast); let sender = TestEventSender::new(sender); let concurrent_jobs = options.concurrent_jobs; - let fail_fast = options.fail_fast; let join_handles = specifiers_with_mode.iter().map(move |(specifier, mode)| { @@ -1010,15 +1019,21 @@ async fn test_specifiers( let mode = mode.clone(); let mut sender = sender.clone(); let options = options.clone(); + let fail_fast_tracker = fail_fast_tracker.clone(); tokio::task::spawn_blocking(move || { + if fail_fast_tracker.should_stop() { + return Ok(()); + } + let origin = specifier.to_string(); let file_result = run_local(test_specifier( ps, permissions, specifier, mode, - &sender, + sender.clone(), + fail_fast_tracker, options, )); if let Err(error) = file_result { @@ -1147,12 +1162,6 @@ async fn test_specifiers( ); } } - - if let Some(x) = fail_fast { - if summary.failed >= x.get() { - break; - } - } } let elapsed = Instant::now().duration_since(earlier); @@ -1184,6 +1193,44 @@ async fn test_specifiers( Ok(()) } +/// Checks if the path has a basename and extension Deno supports for tests. +fn is_supported_test_path(path: &Path) -> bool { + if let Some(name) = path.file_stem() { + let basename = name.to_string_lossy(); + (basename.ends_with("_test") + || basename.ends_with(".test") + || basename == "test") + && is_supported_ext(path) + } else { + false + } +} + +/// Checks if the path has an extension Deno supports for tests. +fn is_supported_test_ext(path: &Path) -> bool { + if let Some(ext) = get_extension(path) { + matches!( + ext.as_str(), + "ts" + | "tsx" + | "js" + | "jsx" + | "mjs" + | "mts" + | "cjs" + | "cts" + | "md" + | "mkd" + | "mkdn" + | "mdwn" + | "mdown" + | "markdown" + ) + } else { + false + } +} + /// Collects specifiers marking them with the appropriate test mode while maintaining the natural /// input order. /// @@ -1525,6 +1572,42 @@ pub async fn run_tests_with_watch( Ok(()) } +/// Tracks failures for the `--fail-fast` argument in +/// order to tell when to stop running tests. +#[derive(Clone)] +pub struct FailFastTracker { + max_count: Option, + failure_count: Arc, +} + +impl FailFastTracker { + pub fn new(fail_fast: Option) -> Self { + Self { + max_count: fail_fast.map(|v| v.into()), + failure_count: Default::default(), + } + } + + pub fn add_failure(&self) -> bool { + if let Some(max_count) = &self.max_count { + self + .failure_count + .fetch_add(1, std::sync::atomic::Ordering::SeqCst) + >= *max_count + } else { + false + } + } + + pub fn should_stop(&self) -> bool { + if let Some(max_count) = &self.max_count { + self.failure_count.load(std::sync::atomic::Ordering::SeqCst) >= *max_count + } else { + false + } + } +} + #[derive(Clone)] pub struct TestEventSender { sender: UnboundedSender, @@ -1557,6 +1640,7 @@ impl TestEventSender { TestEvent::Result(_, _, _) | TestEvent::StepWait(_) | TestEvent::StepResult(_, _, _) + | TestEvent::UncaughtError(_, _) ) { self.flush_stdout_and_stderr(); } @@ -1667,3 +1751,67 @@ fn start_output_redirect_thread( } }); } + +#[cfg(test)] +mod inner_test { + use std::path::Path; + + use super::*; + + #[test] + fn test_is_supported_test_ext() { + assert!(!is_supported_test_ext(Path::new("tests/subdir/redirects"))); + assert!(is_supported_test_ext(Path::new("README.md"))); + assert!(is_supported_test_ext(Path::new("readme.MD"))); + assert!(is_supported_test_ext(Path::new("lib/typescript.d.ts"))); + assert!(is_supported_test_ext(Path::new( + "testdata/run/001_hello.js" + ))); + assert!(is_supported_test_ext(Path::new( + "testdata/run/002_hello.ts" + ))); + assert!(is_supported_test_ext(Path::new("foo.jsx"))); + assert!(is_supported_test_ext(Path::new("foo.tsx"))); + assert!(is_supported_test_ext(Path::new("foo.TS"))); + assert!(is_supported_test_ext(Path::new("foo.TSX"))); + assert!(is_supported_test_ext(Path::new("foo.JS"))); + assert!(is_supported_test_ext(Path::new("foo.JSX"))); + assert!(is_supported_test_ext(Path::new("foo.mjs"))); + assert!(is_supported_test_ext(Path::new("foo.mts"))); + assert!(is_supported_test_ext(Path::new("foo.cjs"))); + assert!(is_supported_test_ext(Path::new("foo.cts"))); + assert!(!is_supported_test_ext(Path::new("foo.mjsx"))); + assert!(!is_supported_test_ext(Path::new("foo.jsonc"))); + assert!(!is_supported_test_ext(Path::new("foo.JSONC"))); + assert!(!is_supported_test_ext(Path::new("foo.json"))); + assert!(!is_supported_test_ext(Path::new("foo.JsON"))); + } + + #[test] + fn test_is_supported_test_path() { + assert!(is_supported_test_path(Path::new( + "tests/subdir/foo_test.ts" + ))); + assert!(is_supported_test_path(Path::new( + "tests/subdir/foo_test.tsx" + ))); + assert!(is_supported_test_path(Path::new( + "tests/subdir/foo_test.js" + ))); + assert!(is_supported_test_path(Path::new( + "tests/subdir/foo_test.jsx" + ))); + assert!(is_supported_test_path(Path::new("bar/foo.test.ts"))); + assert!(is_supported_test_path(Path::new("bar/foo.test.tsx"))); + assert!(is_supported_test_path(Path::new("bar/foo.test.js"))); + assert!(is_supported_test_path(Path::new("bar/foo.test.jsx"))); + assert!(is_supported_test_path(Path::new("foo/bar/test.js"))); + assert!(is_supported_test_path(Path::new("foo/bar/test.jsx"))); + assert!(is_supported_test_path(Path::new("foo/bar/test.ts"))); + assert!(is_supported_test_path(Path::new("foo/bar/test.tsx"))); + assert!(!is_supported_test_path(Path::new("README.md"))); + assert!(!is_supported_test_path(Path::new("lib/typescript.d.ts"))); + assert!(!is_supported_test_path(Path::new("notatest.js"))); + assert!(!is_supported_test_path(Path::new("NotAtest.ts"))); + } +} diff --git a/cli/tools/upgrade.rs b/cli/tools/upgrade.rs index c5f4698351..8c987e82cb 100644 --- a/cli/tools/upgrade.rs +++ b/cli/tools/upgrade.rs @@ -4,9 +4,11 @@ use crate::args::UpgradeFlags; use crate::colors; +use crate::util::progress_bar::ProgressBar; use crate::version; use deno_core::anyhow::bail; +use deno_core::anyhow::Context; use deno_core::error::AnyError; use deno_core::futures::future::BoxFuture; use deno_core::futures::FutureExt; @@ -17,7 +19,6 @@ use once_cell::sync::Lazy; use std::borrow::Cow; use std::env; use std::fs; -use std::io::Write; use std::ops::Sub; use std::path::Path; use std::path::PathBuf; @@ -234,14 +235,14 @@ async fn fetch_and_store_latest_version< } pub async fn upgrade(upgrade_flags: UpgradeFlags) -> Result<(), AnyError> { - let old_exe_path = std::env::current_exe()?; - let metadata = fs::metadata(&old_exe_path)?; + let current_exe_path = std::env::current_exe()?; + let metadata = fs::metadata(¤t_exe_path)?; let permissions = metadata.permissions(); if permissions.readonly() { bail!( "You do not have write permission to {}", - old_exe_path.display() + current_exe_path.display() ); } #[cfg(unix)] @@ -252,7 +253,7 @@ pub async fn upgrade(upgrade_flags: UpgradeFlags) -> Result<(), AnyError> { "You don't have write permission to {} because it's owned by root.\n", "Consider updating deno through your package manager if its installed from it.\n", "Otherwise run `deno upgrade` as root.", - ), old_exe_path.display()); + ), current_exe_path.display()); } let client = build_http_client(upgrade_flags.ca_file)?; @@ -281,7 +282,7 @@ pub async fn upgrade(upgrade_flags: UpgradeFlags) -> Result<(), AnyError> { && upgrade_flags.output.is_none() && current_is_passed { - println!("Version {} is already installed", crate::version::deno()); + log::info!("Version {} is already installed", crate::version::deno()); return Ok(()); } else { passed_version @@ -289,10 +290,10 @@ pub async fn upgrade(upgrade_flags: UpgradeFlags) -> Result<(), AnyError> { } None => { let latest_version = if upgrade_flags.canary { - println!("Looking up latest canary version"); + log::info!("Looking up latest canary version"); get_latest_canary_version(&client).await? } else { - println!("Looking up latest version"); + log::info!("Looking up latest version"); get_latest_release_version(&client).await? }; @@ -311,13 +312,13 @@ pub async fn upgrade(upgrade_flags: UpgradeFlags) -> Result<(), AnyError> { && upgrade_flags.output.is_none() && current_is_most_recent { - println!( + log::info!( "Local deno version {} is the most recent release", crate::version::deno() ); return Ok(()); } else { - println!("Found latest version {}", latest_version); + log::info!("Found latest version {}", latest_version); latest_version } } @@ -341,23 +342,44 @@ pub async fn upgrade(upgrade_flags: UpgradeFlags) -> Result<(), AnyError> { let archive_data = download_package(client, &download_url).await?; - println!("Deno is upgrading to version {}", &install_version); + log::info!("Deno is upgrading to version {}", &install_version); let new_exe_path = unpack(archive_data, cfg!(windows))?; fs::set_permissions(&new_exe_path, permissions)?; check_exe(&new_exe_path)?; if !upgrade_flags.dry_run { - match upgrade_flags.output { - Some(path) => { - fs::rename(&new_exe_path, &path) - .or_else(|_| fs::copy(&new_exe_path, &path).map(|_| ()))?; + let output_exe_path = + upgrade_flags.output.as_ref().unwrap_or(¤t_exe_path); + let output_result = if *output_exe_path == current_exe_path { + replace_exe(&new_exe_path, output_exe_path) + } else { + fs::rename(&new_exe_path, output_exe_path) + .or_else(|_| fs::copy(&new_exe_path, output_exe_path).map(|_| ())) + }; + if let Err(err) = output_result { + const WIN_ERROR_ACCESS_DENIED: i32 = 5; + if cfg!(windows) && err.raw_os_error() == Some(WIN_ERROR_ACCESS_DENIED) { + return Err(err).with_context(|| { + format!( + concat!( + "Access denied: Could not replace the deno executable. This may be ", + "because an existing deno process is running. Please ensure there ", + "are no running deno processes (ex. Stop-Process -Name deno ; deno {}), ", + "close any editors before upgrading, and ensure you have sufficient ", + "permission to '{}'." + ), + std::env::args().collect::>().join(" "), + output_exe_path.display(), + ) + }); + } else { + return Err(err.into()); } - None => replace_exe(&new_exe_path, &old_exe_path)?, } } - println!("Upgraded successfully"); + log::info!("Upgraded successfully"); Ok(()) } @@ -407,7 +429,7 @@ async fn download_package( client: Client, download_url: &str, ) -> Result, AnyError> { - println!("Checking {}", &download_url); + log::info!("Downloading {}", &download_url); let res = client.get(download_url).send().await?; @@ -417,32 +439,27 @@ async fn download_package( let mut data = Vec::with_capacity(total_size as usize); let mut stream = res.bytes_stream(); let mut skip_print = 0; - let is_tty = atty::is(atty::Stream::Stdout); const MEBIBYTE: f64 = 1024.0 * 1024.0; + let progress_bar = ProgressBar::default(); + let clear_guard = progress_bar.clear_guard(); while let Some(item) = stream.next().await { let bytes = item?; current_size += bytes.len() as f64; data.extend_from_slice(&bytes); if skip_print == 0 { - if is_tty { - print!("\u{001b}[1G\u{001b}[2K"); - } - print!( + progress_bar.update(&format!( "{:>4.1} MiB / {:.1} MiB ({:^5.1}%)", current_size / MEBIBYTE, total_size / MEBIBYTE, (current_size / total_size) * 100.0, - ); - std::io::stdout().flush()?; + )); skip_print = 10; } else { skip_print -= 1; } } - if is_tty { - print!("\u{001b}[1G\u{001b}[2K"); - } - println!( + drop(clear_guard); + log::info!( "{:.1} MiB / {:.1} MiB (100.0%)", current_size / MEBIBYTE, total_size / MEBIBYTE @@ -450,7 +467,7 @@ async fn download_package( Ok(data) } else { - println!("Download could not be found, aborting"); + log::info!("Download could not be found, aborting"); std::process::exit(1) } } @@ -524,17 +541,17 @@ pub fn unpack( Ok(exe_path) } -fn replace_exe(new: &Path, old: &Path) -> Result<(), std::io::Error> { +fn replace_exe(from: &Path, to: &Path) -> Result<(), std::io::Error> { if cfg!(windows) { // On windows you cannot replace the currently running executable. // so first we rename it to deno.old.exe - fs::rename(old, old.with_extension("old.exe"))?; + fs::rename(to, to.with_extension("old.exe"))?; } else { - fs::remove_file(old)?; + fs::remove_file(to)?; } // Windows cannot rename files across device boundaries, so if rename fails, // we try again with copy. - fs::rename(new, old).or_else(|_| fs::copy(new, old).map(|_| ()))?; + fs::rename(from, to).or_else(|_| fs::copy(from, to).map(|_| ()))?; Ok(()) } diff --git a/cli/tools/vendor/build.rs b/cli/tools/vendor/build.rs index dadd84e22e..bdb384e436 100644 --- a/cli/tools/vendor/build.rs +++ b/cli/tools/vendor/build.rs @@ -3,18 +3,22 @@ use std::fmt::Write as _; use std::path::Path; use std::path::PathBuf; +use std::sync::Arc; use deno_ast::ModuleSpecifier; use deno_core::anyhow::bail; use deno_core::anyhow::Context; use deno_core::error::AnyError; +use deno_core::parking_lot::Mutex; use deno_graph::Module; use deno_graph::ModuleGraph; use deno_graph::ModuleKind; use import_map::ImportMap; use import_map::SpecifierMap; +use crate::args::Lockfile; use crate::cache::ParsedSourceCache; +use crate::graph_util::graph_lock_or_exit; use super::analyze::has_default_export; use super::import_map::build_import_map; @@ -57,6 +61,7 @@ pub fn build( parsed_source_cache: &ParsedSourceCache, output_dir: &Path, original_import_map: Option<&ImportMap>, + maybe_lockfile: Option>>, environment: &impl VendorEnvironment, ) -> Result { assert!(output_dir.is_absolute()); @@ -68,18 +73,20 @@ pub fn build( } // build the graph - graph.lock()?; + if let Some(lockfile) = maybe_lockfile { + graph_lock_or_exit(&graph, &mut lockfile.lock()); + } - let graph_errors = graph.errors(); - if !graph_errors.is_empty() { - for err in &graph_errors { + let mut graph_errors = graph.errors().peekable(); + if graph_errors.peek().is_some() { + for err in graph_errors { log::error!("{}", err); } bail!("failed vendoring"); } // figure out how to map remote modules to local - let all_modules = graph.modules(); + let all_modules = graph.modules().collect::>(); let remote_modules = all_modules .iter() .filter(|m| is_remote_specifier(&m.specifier)) @@ -1064,6 +1071,41 @@ mod test { ); } + #[tokio::test] + async fn existing_import_map_http_key() { + let mut builder = VendorTestBuilder::with_default_setup(); + let mut original_import_map = builder.new_import_map("/import_map.json"); + original_import_map + .imports_mut() + .append( + "http/".to_string(), + "https://deno.land/std/http/".to_string(), + ) + .unwrap(); + let output = builder + .with_loader(|loader| { + loader.add("/mod.ts", "import 'http/mod.ts';"); + loader.add("https://deno.land/std/http/mod.ts", "console.log(5);"); + }) + .set_original_import_map(original_import_map.clone()) + .build() + .await + .unwrap(); + assert_eq!( + output.import_map, + Some(json!({ + "imports": { + "http/mod.ts": "./deno.land/std/http/mod.ts", + "https://deno.land/": "./deno.land/", + } + })) + ); + assert_eq!( + output.files, + to_file_vec(&[("/vendor/deno.land/std/http/mod.ts", "console.log(5);")]), + ); + } + #[tokio::test] async fn vendor_file_fails_loading_dynamic_import() { let mut builder = VendorTestBuilder::with_default_setup(); diff --git a/cli/tools/vendor/mappings.rs b/cli/tools/vendor/mappings.rs index 5435361283..d1152b12b4 100644 --- a/cli/tools/vendor/mappings.rs +++ b/cli/tools/vendor/mappings.rs @@ -13,8 +13,8 @@ use deno_graph::ModuleGraph; use deno_graph::Position; use deno_graph::Resolved; -use crate::fs_util::path_with_stem_suffix; -use crate::fs_util::relative_specifier; +use crate::util::path::path_with_stem_suffix; +use crate::util::path::relative_specifier; use super::specifiers::dir_name_for_root; use super::specifiers::get_unique_path; diff --git a/cli/tools/vendor/mod.rs b/cli/tools/vendor/mod.rs index 3fd381b213..ed0c69501e 100644 --- a/cli/tools/vendor/mod.rs +++ b/cli/tools/vendor/mod.rs @@ -15,11 +15,12 @@ use crate::args::CliOptions; use crate::args::Flags; use crate::args::FmtOptionsConfig; use crate::args::VendorFlags; -use crate::fs_util; -use crate::fs_util::relative_specifier; -use crate::fs_util::specifier_to_file_path; use crate::proc_state::ProcState; use crate::tools::fmt::format_json; +use crate::util::fs::canonicalize_path; +use crate::util::fs::resolve_from_cwd; +use crate::util::path::relative_specifier; +use crate::util::path::specifier_to_file_path; mod analyze; mod build; @@ -38,7 +39,7 @@ pub async fn vendor( Some(output_path) => output_path.to_owned(), None => PathBuf::from("vendor/"), }; - let output_dir = fs_util::resolve_from_cwd(&raw_output_dir)?; + let output_dir = resolve_from_cwd(&raw_output_dir)?; validate_output_dir(&output_dir, &vendor_flags)?; validate_options(&mut cli_options, &output_dir)?; let ps = ProcState::from_options(Arc::new(cli_options)).await?; @@ -48,6 +49,7 @@ pub async fn vendor( &ps.parsed_source_cache, &output_dir, ps.maybe_import_map.as_deref(), + ps.lockfile.clone(), &build::RealVendorEnvironment, )?; @@ -110,18 +112,17 @@ fn validate_options( if let Some(import_map_path) = options .resolve_import_map_specifier()? .and_then(|p| specifier_to_file_path(&p).ok()) - .and_then(|p| fs_util::canonicalize_path(&p).ok()) + .and_then(|p| canonicalize_path(&p).ok()) { // make the output directory in order to canonicalize it for the check below std::fs::create_dir_all(output_dir)?; - let output_dir = - fs_util::canonicalize_path(output_dir).with_context(|| { - format!("Failed to canonicalize: {}", output_dir.display()) - })?; + let output_dir = canonicalize_path(output_dir).with_context(|| { + format!("Failed to canonicalize: {}", output_dir.display()) + })?; if import_map_path.starts_with(&output_dir) { // canonicalize to make the test for this pass on the CI - let cwd = fs_util::canonicalize_path(&std::env::current_dir()?)?; + let cwd = canonicalize_path(&std::env::current_dir()?)?; // We don't allow using the output directory to help generate the // new state because this may lead to cryptic error messages. log::warn!( diff --git a/cli/tools/vendor/specifiers.rs b/cli/tools/vendor/specifiers.rs index 5d4f982786..21ae2ca85f 100644 --- a/cli/tools/vendor/specifiers.rs +++ b/cli/tools/vendor/specifiers.rs @@ -8,8 +8,9 @@ use deno_ast::ModuleSpecifier; use deno_core::anyhow::anyhow; use deno_core::error::AnyError; -use crate::fs_util; -use crate::fs_util::path_with_stem_suffix; +use crate::util::path::is_banned_path_char; +use crate::util::path::path_with_stem_suffix; +use crate::util::path::root_url_to_safe_local_dirname; /// Partitions the provided specifiers by the non-path and non-query parts of a specifier. pub fn partition_by_root_specifiers<'a>( @@ -30,7 +31,7 @@ pub fn partition_by_root_specifiers<'a>( /// Gets the directory name to use for the provided root. pub fn dir_name_for_root(root: &ModuleSpecifier) -> PathBuf { - fs_util::root_url_to_safe_local_dirname(root) + root_url_to_safe_local_dirname(root) } /// Gets a unique file path given the provided file path @@ -68,19 +69,14 @@ pub fn is_remote_specifier(specifier: &ModuleSpecifier) -> bool { } pub fn is_remote_specifier_text(text: &str) -> bool { - text.trim_start().to_lowercase().starts_with("http") + let text = text.trim_start().to_lowercase(); + text.starts_with("http:") || text.starts_with("https:") } pub fn sanitize_filepath(text: &str) -> String { text .chars() - .map(|c| { - if fs_util::is_banned_path_char(c) { - '_' - } else { - c - } - }) + .map(|c| if is_banned_path_char(c) { '_' } else { c }) .collect() } diff --git a/cli/tools/vendor/test.rs b/cli/tools/vendor/test.rs index ee779468b8..c703357d8f 100644 --- a/cli/tools/vendor/test.rs +++ b/cli/tools/vendor/test.rs @@ -234,6 +234,7 @@ impl VendorTestBuilder { &parsed_source_cache, &output_dir, self.original_import_map.as_ref(), + None, &self.environment, )?; @@ -273,7 +274,6 @@ async fn build_test_graph( is_dynamic: false, imports: None, resolver: resolver.as_ref().map(|r| r.as_graph_resolver()), - locker: None, module_analyzer: Some(analyzer), reporter: None, }, diff --git a/cli/tsc/00_typescript.js b/cli/tsc/00_typescript.js index 4f2a0c4675..914f2e3f05 100644 --- a/cli/tsc/00_typescript.js +++ b/cli/tsc/00_typescript.js @@ -44,7 +44,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) { function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); - while (_) try { + while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { @@ -91,210 +91,15 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -/* @internal */ -var ts; -(function (ts) { - function createMapData() { - var sentinel = {}; - sentinel.prev = sentinel; - return { head: sentinel, tail: sentinel, size: 0 }; - } - function createMapEntry(key, value) { - return { key: key, value: value, next: undefined, prev: undefined }; - } - function sameValueZero(x, y) { - // Treats -0 === 0 and NaN === NaN - return x === y || x !== x && y !== y; - } - function getPrev(entry) { - var prev = entry.prev; - // Entries without a 'prev' have been removed from the map. - // An entry whose 'prev' points to itself is the head of the list and is invalid here. - if (!prev || prev === entry) - throw new Error("Illegal state"); - return prev; - } - function getNext(entry) { - while (entry) { - // Entries without a 'prev' have been removed from the map. Their 'next' - // pointer should point to the previous entry prior to deletion and - // that entry should be skipped to resume iteration. - var skipNext = !entry.prev; - entry = entry.next; - if (skipNext) { - continue; - } - return entry; - } - } - function getEntry(data, key) { - // We walk backwards from 'tail' to prioritize recently added entries. - // We skip 'head' because it is an empty entry used to track iteration start. - for (var entry = data.tail; entry !== data.head; entry = getPrev(entry)) { - if (sameValueZero(entry.key, key)) { - return entry; - } - } - } - function addOrUpdateEntry(data, key, value) { - var existing = getEntry(data, key); - if (existing) { - existing.value = value; - return; - } - var entry = createMapEntry(key, value); - entry.prev = data.tail; - data.tail.next = entry; - data.tail = entry; - data.size++; - return entry; - } - function deleteEntry(data, key) { - // We walk backwards from 'tail' to prioritize recently added entries. - // We skip 'head' because it is an empty entry used to track iteration start. - for (var entry = data.tail; entry !== data.head; entry = getPrev(entry)) { - // all entries in the map should have a 'prev' pointer. - if (entry.prev === undefined) - throw new Error("Illegal state"); - if (sameValueZero(entry.key, key)) { - if (entry.next) { - entry.next.prev = entry.prev; - } - else { - // an entry in the map without a 'next' pointer must be the 'tail'. - if (data.tail !== entry) - throw new Error("Illegal state"); - data.tail = entry.prev; - } - entry.prev.next = entry.next; - entry.next = entry.prev; - entry.prev = undefined; - data.size--; - return entry; - } - } - } - function clearEntries(data) { - var node = data.tail; - while (node !== data.head) { - var prev = getPrev(node); - node.next = data.head; - node.prev = undefined; - node = prev; - } - data.head.next = undefined; - data.tail = data.head; - data.size = 0; - } - function forEachEntry(data, action) { - var entry = data.head; - while (entry) { - entry = getNext(entry); - if (entry) { - action(entry.value, entry.key); - } - } - } - function forEachIteration(iterator, action) { - if (iterator) { - for (var step = iterator.next(); !step.done; step = iterator.next()) { - action(step.value); - } - } - } - function createIteratorData(data, selector) { - return { current: data.head, selector: selector }; - } - function iteratorNext(data) { - // Navigate to the next entry. - data.current = getNext(data.current); - if (data.current) { - return { value: data.selector(data.current.key, data.current.value), done: false }; - } - else { - return { value: undefined, done: true }; - } - } - /* @internal */ - var ShimCollections; - (function (ShimCollections) { - function createMapShim(getIterator) { - var MapIterator = /** @class */ (function () { - function MapIterator(data, selector) { - this._data = createIteratorData(data, selector); - } - MapIterator.prototype.next = function () { return iteratorNext(this._data); }; - return MapIterator; - }()); - return /** @class */ (function () { - function Map(iterable) { - var _this = this; - this._mapData = createMapData(); - forEachIteration(getIterator(iterable), function (_a) { - var key = _a[0], value = _a[1]; - return _this.set(key, value); - }); - } - Object.defineProperty(Map.prototype, "size", { - get: function () { return this._mapData.size; }, - enumerable: false, - configurable: true - }); - Map.prototype.get = function (key) { var _a; return (_a = getEntry(this._mapData, key)) === null || _a === void 0 ? void 0 : _a.value; }; - Map.prototype.set = function (key, value) { return addOrUpdateEntry(this._mapData, key, value), this; }; - Map.prototype.has = function (key) { return !!getEntry(this._mapData, key); }; - Map.prototype.delete = function (key) { return !!deleteEntry(this._mapData, key); }; - Map.prototype.clear = function () { clearEntries(this._mapData); }; - Map.prototype.keys = function () { return new MapIterator(this._mapData, function (key, _value) { return key; }); }; - Map.prototype.values = function () { return new MapIterator(this._mapData, function (_key, value) { return value; }); }; - Map.prototype.entries = function () { return new MapIterator(this._mapData, function (key, value) { return [key, value]; }); }; - Map.prototype.forEach = function (action) { forEachEntry(this._mapData, action); }; - return Map; - }()); - } - ShimCollections.createMapShim = createMapShim; - function createSetShim(getIterator) { - var SetIterator = /** @class */ (function () { - function SetIterator(data, selector) { - this._data = createIteratorData(data, selector); - } - SetIterator.prototype.next = function () { return iteratorNext(this._data); }; - return SetIterator; - }()); - return /** @class */ (function () { - function Set(iterable) { - var _this = this; - this._mapData = createMapData(); - forEachIteration(getIterator(iterable), function (value) { return _this.add(value); }); - } - Object.defineProperty(Set.prototype, "size", { - get: function () { return this._mapData.size; }, - enumerable: false, - configurable: true - }); - Set.prototype.add = function (value) { return addOrUpdateEntry(this._mapData, value, value), this; }; - Set.prototype.has = function (value) { return !!getEntry(this._mapData, value); }; - Set.prototype.delete = function (value) { return !!deleteEntry(this._mapData, value); }; - Set.prototype.clear = function () { clearEntries(this._mapData); }; - Set.prototype.keys = function () { return new SetIterator(this._mapData, function (key, _value) { return key; }); }; - Set.prototype.values = function () { return new SetIterator(this._mapData, function (_key, value) { return value; }); }; - Set.prototype.entries = function () { return new SetIterator(this._mapData, function (key, value) { return [key, value]; }); }; - Set.prototype.forEach = function (action) { forEachEntry(this._mapData, action); }; - return Set; - }()); - } - ShimCollections.createSetShim = createSetShim; - })(ShimCollections = ts.ShimCollections || (ts.ShimCollections = {})); -})(ts || (ts = {})); var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.8"; + ts.versionMajorMinor = "4.9"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = "4.8.3"; + ts.version = "".concat(ts.versionMajorMinor, ".3"); /* @internal */ var Comparison; (function (Comparison) { @@ -315,8 +120,12 @@ var ts; function tryGetNativeMap() { // Internet Explorer's Map doesn't support iteration, so don't use it. var gMap = globals === null || globals === void 0 ? void 0 : globals.Map; - // eslint-disable-next-line no-in-operator - return typeof gMap !== "undefined" && "entries" in gMap.prototype && new gMap([[0, 0]]).size === 1 ? gMap : undefined; + // eslint-disable-next-line local/no-in-operator + var constructor = typeof gMap !== "undefined" && "entries" in gMap.prototype && new gMap([[0, 0]]).size === 1 ? gMap : undefined; + if (!constructor) { + throw new Error("No compatible Map implementation found."); + } + return constructor; } NativeCollections.tryGetNativeMap = tryGetNativeMap; /** @@ -325,24 +134,19 @@ var ts; function tryGetNativeSet() { // Internet Explorer's Set doesn't support iteration, so don't use it. var gSet = globals === null || globals === void 0 ? void 0 : globals.Set; - // eslint-disable-next-line no-in-operator - return typeof gSet !== "undefined" && "entries" in gSet.prototype && new gSet([0]).size === 1 ? gSet : undefined; + // eslint-disable-next-line local/no-in-operator + var constructor = typeof gSet !== "undefined" && "entries" in gSet.prototype && new gSet([0]).size === 1 ? gSet : undefined; + if (!constructor) { + throw new Error("No compatible Set implementation found."); + } + return constructor; } NativeCollections.tryGetNativeSet = tryGetNativeSet; })(NativeCollections || (NativeCollections = {})); /* @internal */ - ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); + ts.Map = NativeCollections.tryGetNativeMap(); /* @internal */ - ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); - /* @internal */ - function getCollectionImplementation(name, nativeFactory, shimFactory) { - var _a; - // NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it. - var constructor = (_a = NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](ts.getIterator); - if (constructor) - return constructor; - throw new Error("TypeScript requires an environment that provides a compatible native ".concat(name, " implementation.")); - } + ts.Set = NativeCollections.tryGetNativeSet(); })(ts || (ts = {})); /* @internal */ var ts; @@ -1058,15 +862,18 @@ var ts; function insertSorted(array, insert, compare, allowDuplicates) { if (array.length === 0) { array.push(insert); - return; + return true; } var insertIndex = binarySearch(array, insert, identity, compare); if (insertIndex < 0) { array.splice(~insertIndex, 0, insert); + return true; } - else if (allowDuplicates) { + if (allowDuplicates) { array.splice(insertIndex, 0, insert); + return true; } + return false; } ts.insertSorted = insertSorted; function sortAndDeduplicate(array, comparer, equalityComparer) { @@ -1346,6 +1153,13 @@ var ts; : undefined; } ts.singleOrUndefined = singleOrUndefined; + /** + * Returns the only element of an array if it contains only one element; throws otherwise. + */ + function single(array) { + return ts.Debug.checkDefined(singleOrUndefined(array)); + } + ts.single = single; function singleOrMany(array) { return array && array.length === 1 ? array[0] @@ -2077,8 +1891,8 @@ var ts; return compareValues(a === null || a === void 0 ? void 0 : a.start, b === null || b === void 0 ? void 0 : b.start) || compareValues(a === null || a === void 0 ? void 0 : a.length, b === null || b === void 0 ? void 0 : b.length); } ts.compareTextSpans = compareTextSpans; - function min(a, b, compare) { - return compare(a, b) === -1 /* Comparison.LessThan */ ? a : b; + function min(items, compare) { + return reduceLeft(items, function (x, y) { return compare(x, y) === -1 /* Comparison.LessThan */ ? x : y; }); } ts.min = min; /** @@ -2869,7 +2683,7 @@ var ts; if (typeof func !== "function") { return ""; } - else if (func.hasOwnProperty("name")) { + else if (ts.hasProperty(func, "name")) { return func.name; } else { @@ -3019,7 +2833,7 @@ var ts; Debug.formatControlFlowGraph = formatControlFlowGraph; var flowNodeProto; function attachFlowNodeDebugInfoWorker(flowNode) { - if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line local/no-in-operator Object.defineProperties(flowNode, { // for use with vscode-js-debug's new customDescriptionGenerator in launch.json __tsDebuggerDisplay: { @@ -3065,7 +2879,7 @@ var ts; Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; var nodeArrayProto; function attachNodeArrayDebugInfoWorker(array) { - if (!("__tsDebuggerDisplay" in array)) { // eslint-disable-line no-in-operator + if (!("__tsDebuggerDisplay" in array)) { // eslint-disable-line local/no-in-operator Object.defineProperties(array, { __tsDebuggerDisplay: { value: function (defaultValue) { @@ -3194,7 +3008,7 @@ var ts; ]; for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { var ctor = nodeConstructors_1[_i]; - if (!ctor.prototype.hasOwnProperty("__debugKind")) { + if (!ts.hasProperty(ctor.prototype, "__debugKind")) { Object.defineProperties(ctor.prototype, { // for use with vscode-js-debug's new customDescriptionGenerator in launch.json __tsDebuggerDisplay: { @@ -3391,11 +3205,13 @@ var ts; // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers // > MUST NOT include leading zeroes. var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; // https://semver.org/#spec-item-10 // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated // > identifiers immediately following the patch or pre-release version. Identifiers MUST // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var buildPartRegExp = /^[a-z0-9-]+$/i; // https://semver.org/#spec-item-9 // > Numeric identifiers MUST NOT include leading zeroes. var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; @@ -3415,13 +3231,15 @@ var ts; ts.Debug.assert(major >= 0, "Invalid argument: major"); ts.Debug.assert(minor >= 0, "Invalid argument: minor"); ts.Debug.assert(patch >= 0, "Invalid argument: patch"); - ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); - ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + var prereleaseArray = prerelease ? ts.isArray(prerelease) ? prerelease : prerelease.split(".") : ts.emptyArray; + var buildArray = build ? ts.isArray(build) ? build : build.split(".") : ts.emptyArray; + ts.Debug.assert(ts.every(prereleaseArray, function (s) { return prereleasePartRegExp.test(s); }), "Invalid argument: prerelease"); + ts.Debug.assert(ts.every(buildArray, function (s) { return buildPartRegExp.test(s); }), "Invalid argument: build"); this.major = major; this.minor = minor; this.patch = patch; - this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; - this.build = build ? build.split(".") : ts.emptyArray; + this.prerelease = prereleaseArray; + this.build = buildArray; } Version.tryParse = function (text) { var result = tryParseComponents(text); @@ -3460,6 +3278,10 @@ var ts; default: return ts.Debug.assertNever(field); } }; + Version.prototype.with = function (fields) { + var _a = fields.major, major = _a === void 0 ? this.major : _a, _b = fields.minor, minor = _b === void 0 ? this.minor : _b, _c = fields.patch, patch = _c === void 0 ? this.patch : _c, _d = fields.prerelease, prerelease = _d === void 0 ? this.prerelease : _d, _e = fields.build, build = _e === void 0 ? this.build : _e; + return new Version(major, minor, patch, prerelease, build); + }; Version.prototype.toString = function () { var result = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); if (ts.some(this.prerelease)) @@ -3468,7 +3290,7 @@ var ts; result += "+".concat(this.build.join(".")); return result; }; - Version.zero = new Version(0, 0, 0); + Version.zero = new Version(0, 0, 0, ["0"]); return Version; }()); ts.Version = Version; @@ -3551,6 +3373,10 @@ var ts; } return undefined; }; + /** + * Tests whether a version matches the range. This is equivalent to `satisfies(version, range, { includePrerelease: true })`. + * in `node-semver`. + */ VersionRange.prototype.test = function (version) { if (typeof version === "string") version = new Version(version); @@ -3661,19 +3487,20 @@ var ts; break; case "<": case ">=": - comparators.push(createComparator(operator, version)); + comparators.push(isWildcard(minor) || isWildcard(patch) ? createComparator(operator, version.with({ prerelease: "0" })) : + createComparator(operator, version)); break; case "<=": case ">": - comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : - isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major").with({ prerelease: "0" })) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor").with({ prerelease: "0" })) : createComparator(operator, version)); break; case "=": case undefined: if (isWildcard(minor) || isWildcard(patch)) { - comparators.push(createComparator(">=", version)); - comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + comparators.push(createComparator(">=", version.with({ prerelease: "0" }))); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor").with({ prerelease: "0" }))); } else { comparators.push(createComparator("=", version)); @@ -3747,6 +3574,8 @@ var ts; typeof performance.mark === "function" && typeof performance.measure === "function" && typeof performance.now === "function" && + typeof performance.clearMarks === "function" && + typeof performance.clearMeasures === "function" && typeof PerformanceObserver === "function"; } function tryGetWebPerformanceHooks() { @@ -3791,7 +3620,9 @@ var ts; if (end === "__performance.measure-fix__") { nodePerformance_1.clearMarks("__performance.measure-fix__"); } - } + }, + clearMarks: function (name) { return nodePerformance_1.clearMarks(name); }, + clearMeasures: function (name) { return nodePerformance_1.clearMeasures(name); }, }; } return { @@ -3924,6 +3755,30 @@ var ts; durations.forEach(function (duration, measureName) { return cb(measureName, duration); }); } performance.forEachMeasure = forEachMeasure; + function forEachMark(cb) { + marks.forEach(function (_time, markName) { return cb(markName); }); + } + performance.forEachMark = forEachMark; + function clearMeasures(name) { + if (name !== undefined) + durations.delete(name); + else + durations.clear(); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.clearMeasures(name); + } + performance.clearMeasures = clearMeasures; + function clearMarks(name) { + if (name !== undefined) { + counts.delete(name); + marks.delete(name); + } + else { + counts.clear(); + marks.clear(); + } + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.clearMarks(name); + } + performance.clearMarks = clearMarks; /** * Indicates whether the performance API is enabled. */ @@ -4021,7 +3876,6 @@ var ts; var typeCatalog = []; // NB: id is index + 1 var legendPath; var legend = []; - ; /** Starts tracing for the given project. */ function startTracing(tracingMode, traceDir, configFilePath) { ts.Debug.assert(!ts.tracing, "Tracing already started"); @@ -4226,7 +4080,7 @@ var ts; var substitutionType = type; substitutionProperties = { substitutionBaseType: (_o = substitutionType.baseType) === null || _o === void 0 ? void 0 : _o.id, - substituteType: (_p = substitutionType.substitute) === null || _p === void 0 ? void 0 : _p.id, + constraintType: (_p = substitutionType.constraint) === null || _p === void 0 ? void 0 : _p.id, }; } var reverseMappedProperties = {}; @@ -4426,257 +4280,260 @@ var ts; SyntaxKind[SyntaxKind["YieldKeyword"] = 125] = "YieldKeyword"; // Contextual keywords SyntaxKind[SyntaxKind["AbstractKeyword"] = 126] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 127] = "AsKeyword"; - SyntaxKind[SyntaxKind["AssertsKeyword"] = 128] = "AssertsKeyword"; - SyntaxKind[SyntaxKind["AssertKeyword"] = 129] = "AssertKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 130] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 131] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 132] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 133] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 134] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 135] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 136] = "GetKeyword"; - SyntaxKind[SyntaxKind["InferKeyword"] = 137] = "InferKeyword"; - SyntaxKind[SyntaxKind["IntrinsicKeyword"] = 138] = "IntrinsicKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 139] = "IsKeyword"; - SyntaxKind[SyntaxKind["KeyOfKeyword"] = 140] = "KeyOfKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 141] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 142] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 143] = "NeverKeyword"; - SyntaxKind[SyntaxKind["OutKeyword"] = 144] = "OutKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 145] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 146] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 147] = "NumberKeyword"; - SyntaxKind[SyntaxKind["ObjectKeyword"] = 148] = "ObjectKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 149] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 150] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 151] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 152] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 153] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["UniqueKeyword"] = 154] = "UniqueKeyword"; - SyntaxKind[SyntaxKind["UnknownKeyword"] = 155] = "UnknownKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 156] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 157] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["BigIntKeyword"] = 158] = "BigIntKeyword"; - SyntaxKind[SyntaxKind["OverrideKeyword"] = 159] = "OverrideKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 160] = "OfKeyword"; + SyntaxKind[SyntaxKind["AccessorKeyword"] = 127] = "AccessorKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 128] = "AsKeyword"; + SyntaxKind[SyntaxKind["AssertsKeyword"] = 129] = "AssertsKeyword"; + SyntaxKind[SyntaxKind["AssertKeyword"] = 130] = "AssertKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 131] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 132] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 133] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 134] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 135] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 136] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 137] = "GetKeyword"; + SyntaxKind[SyntaxKind["InferKeyword"] = 138] = "InferKeyword"; + SyntaxKind[SyntaxKind["IntrinsicKeyword"] = 139] = "IntrinsicKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 140] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 141] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 142] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 143] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 144] = "NeverKeyword"; + SyntaxKind[SyntaxKind["OutKeyword"] = 145] = "OutKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 146] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 147] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 148] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 149] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SatisfiesKeyword"] = 150] = "SatisfiesKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 151] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 152] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 153] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 154] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 155] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 156] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 157] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 158] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 159] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["BigIntKeyword"] = 160] = "BigIntKeyword"; + SyntaxKind[SyntaxKind["OverrideKeyword"] = 161] = "OverrideKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 162] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 161] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 162] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 163] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 164] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 163] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 164] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 165] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 165] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 166] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 167] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 166] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 167] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 168] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 169] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["ClassStaticBlockDeclaration"] = 170] = "ClassStaticBlockDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 171] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 172] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 173] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 174] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 175] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 176] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 168] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 169] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 170] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 171] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["ClassStaticBlockDeclaration"] = 172] = "ClassStaticBlockDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 173] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 174] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 175] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 176] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 177] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 178] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 177] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 178] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 179] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 180] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 181] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 182] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 183] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 184] = "TupleType"; - SyntaxKind[SyntaxKind["OptionalType"] = 185] = "OptionalType"; - SyntaxKind[SyntaxKind["RestType"] = 186] = "RestType"; - SyntaxKind[SyntaxKind["UnionType"] = 187] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 188] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 189] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 190] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 191] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 192] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 193] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 194] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 195] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 196] = "LiteralType"; - SyntaxKind[SyntaxKind["NamedTupleMember"] = 197] = "NamedTupleMember"; - SyntaxKind[SyntaxKind["TemplateLiteralType"] = 198] = "TemplateLiteralType"; - SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 199] = "TemplateLiteralTypeSpan"; - SyntaxKind[SyntaxKind["ImportType"] = 200] = "ImportType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 179] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 180] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 181] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 182] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 183] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 184] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 185] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 186] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 187] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 188] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 189] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 190] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 191] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 192] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 193] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 194] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 195] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 196] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 197] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 198] = "LiteralType"; + SyntaxKind[SyntaxKind["NamedTupleMember"] = 199] = "NamedTupleMember"; + SyntaxKind[SyntaxKind["TemplateLiteralType"] = 200] = "TemplateLiteralType"; + SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 201] = "TemplateLiteralTypeSpan"; + SyntaxKind[SyntaxKind["ImportType"] = 202] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 201] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 202] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 203] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 203] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 204] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 205] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 204] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 205] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 206] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 207] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 208] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 209] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 210] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 211] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 212] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 213] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 214] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 215] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 216] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 217] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 218] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 219] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 220] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 221] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 222] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 223] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 224] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 225] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 226] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 227] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 228] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 229] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 230] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 231] = "MetaProperty"; - SyntaxKind[SyntaxKind["SyntheticExpression"] = 232] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 206] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 207] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 208] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 209] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 210] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 211] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 212] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 213] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 214] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 215] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 216] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 217] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 218] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 219] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 220] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 221] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 222] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 223] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 224] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 225] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 226] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 227] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 228] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 229] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 230] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 231] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 232] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 233] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 234] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["SatisfiesExpression"] = 235] = "SatisfiesExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 233] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 234] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 236] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 237] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 235] = "Block"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 236] = "EmptyStatement"; - SyntaxKind[SyntaxKind["VariableStatement"] = 237] = "VariableStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 238] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 239] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 240] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 241] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 242] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 243] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 244] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 245] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 246] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 247] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 248] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 249] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 250] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 251] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 252] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 253] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 254] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 255] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 256] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 257] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 258] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 259] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 260] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 261] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 262] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 263] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 264] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 265] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 266] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 267] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 268] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 269] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 270] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 271] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 272] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 273] = "NamedExports"; - SyntaxKind[SyntaxKind["NamespaceExport"] = 274] = "NamespaceExport"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 275] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 276] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 238] = "Block"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 239] = "EmptyStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 240] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 241] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 242] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 243] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 244] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 245] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 246] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 247] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 248] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 249] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 250] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 251] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 252] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 253] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 254] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 255] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 256] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 257] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 258] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 259] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 260] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 261] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 262] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 263] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 264] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 265] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 266] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 267] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 268] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 269] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 270] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 271] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 272] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 273] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 274] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 275] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 276] = "NamedExports"; + SyntaxKind[SyntaxKind["NamespaceExport"] = 277] = "NamespaceExport"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 278] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 279] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 277] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 280] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 278] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 279] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 280] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 281] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 282] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 283] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 284] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 285] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 286] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 287] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 288] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 281] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 282] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 283] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 284] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 285] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 286] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 287] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 288] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 289] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 290] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 291] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 289] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 290] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 291] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 292] = "CatchClause"; - SyntaxKind[SyntaxKind["AssertClause"] = 293] = "AssertClause"; - SyntaxKind[SyntaxKind["AssertEntry"] = 294] = "AssertEntry"; - SyntaxKind[SyntaxKind["ImportTypeAssertionContainer"] = 295] = "ImportTypeAssertionContainer"; + SyntaxKind[SyntaxKind["CaseClause"] = 292] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 293] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 294] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 295] = "CatchClause"; + SyntaxKind[SyntaxKind["AssertClause"] = 296] = "AssertClause"; + SyntaxKind[SyntaxKind["AssertEntry"] = 297] = "AssertEntry"; + SyntaxKind[SyntaxKind["ImportTypeAssertionContainer"] = 298] = "ImportTypeAssertionContainer"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 296] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 297] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 298] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 299] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 300] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 301] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 299] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 302] = "EnumMember"; // Unparsed - SyntaxKind[SyntaxKind["UnparsedPrologue"] = 300] = "UnparsedPrologue"; - SyntaxKind[SyntaxKind["UnparsedPrepend"] = 301] = "UnparsedPrepend"; - SyntaxKind[SyntaxKind["UnparsedText"] = 302] = "UnparsedText"; - SyntaxKind[SyntaxKind["UnparsedInternalText"] = 303] = "UnparsedInternalText"; - SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 304] = "UnparsedSyntheticReference"; + SyntaxKind[SyntaxKind["UnparsedPrologue"] = 303] = "UnparsedPrologue"; + SyntaxKind[SyntaxKind["UnparsedPrepend"] = 304] = "UnparsedPrepend"; + SyntaxKind[SyntaxKind["UnparsedText"] = 305] = "UnparsedText"; + SyntaxKind[SyntaxKind["UnparsedInternalText"] = 306] = "UnparsedInternalText"; + SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 307] = "UnparsedSyntheticReference"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 305] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 306] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 307] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 308] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 308] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 309] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 310] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 311] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 309] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocNameReference"] = 310] = "JSDocNameReference"; - SyntaxKind[SyntaxKind["JSDocMemberName"] = 311] = "JSDocMemberName"; - SyntaxKind[SyntaxKind["JSDocAllType"] = 312] = "JSDocAllType"; - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 313] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 314] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 315] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 316] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 317] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 318] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocNamepathType"] = 319] = "JSDocNamepathType"; - SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 312] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocNameReference"] = 313] = "JSDocNameReference"; + SyntaxKind[SyntaxKind["JSDocMemberName"] = 314] = "JSDocMemberName"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 315] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 316] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 317] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 318] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 319] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 320] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 321] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocNamepathType"] = 322] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDoc"] = 323] = "JSDoc"; /** @deprecated Use SyntaxKind.JSDoc */ - SyntaxKind[SyntaxKind["JSDocComment"] = 320] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocText"] = 321] = "JSDocText"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 322] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 323] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocLink"] = 324] = "JSDocLink"; - SyntaxKind[SyntaxKind["JSDocLinkCode"] = 325] = "JSDocLinkCode"; - SyntaxKind[SyntaxKind["JSDocLinkPlain"] = 326] = "JSDocLinkPlain"; - SyntaxKind[SyntaxKind["JSDocTag"] = 327] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 328] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 329] = "JSDocImplementsTag"; - SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 330] = "JSDocAuthorTag"; - SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 331] = "JSDocDeprecatedTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 332] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocPublicTag"] = 333] = "JSDocPublicTag"; - SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 334] = "JSDocPrivateTag"; - SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 335] = "JSDocProtectedTag"; - SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 336] = "JSDocReadonlyTag"; - SyntaxKind[SyntaxKind["JSDocOverrideTag"] = 337] = "JSDocOverrideTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 338] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 339] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 340] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 341] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 342] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 343] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 344] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 345] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocSeeTag"] = 346] = "JSDocSeeTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 347] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocComment"] = 323] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocText"] = 324] = "JSDocText"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 325] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 326] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocLink"] = 327] = "JSDocLink"; + SyntaxKind[SyntaxKind["JSDocLinkCode"] = 328] = "JSDocLinkCode"; + SyntaxKind[SyntaxKind["JSDocLinkPlain"] = 329] = "JSDocLinkPlain"; + SyntaxKind[SyntaxKind["JSDocTag"] = 330] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 331] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 332] = "JSDocImplementsTag"; + SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 333] = "JSDocAuthorTag"; + SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 334] = "JSDocDeprecatedTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 335] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocPublicTag"] = 336] = "JSDocPublicTag"; + SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 337] = "JSDocPrivateTag"; + SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 338] = "JSDocProtectedTag"; + SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 339] = "JSDocReadonlyTag"; + SyntaxKind[SyntaxKind["JSDocOverrideTag"] = 340] = "JSDocOverrideTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 341] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 342] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 343] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 344] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 345] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 346] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 347] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 348] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocSeeTag"] = 349] = "JSDocSeeTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 350] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 348] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 351] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 349] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 350] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 351] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 352] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 353] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 354] = "SyntheticReferenceExpression"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 352] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 353] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 354] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 355] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 356] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 357] = "SyntheticReferenceExpression"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 355] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 358] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 63] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 78] = "LastAssignment"; @@ -4685,15 +4542,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 81] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 116] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 81] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 160] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 162] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 117] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 125] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 177] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 200] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 179] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 202] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 78] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 160] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 162] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -4702,15 +4559,15 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 78] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstStatement"] = 237] = "FirstStatement"; - SyntaxKind[SyntaxKind["LastStatement"] = 253] = "LastStatement"; - SyntaxKind[SyntaxKind["FirstNode"] = 161] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 309] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 347] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 327] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 347] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstStatement"] = 240] = "FirstStatement"; + SyntaxKind[SyntaxKind["LastStatement"] = 256] = "LastStatement"; + SyntaxKind[SyntaxKind["FirstNode"] = 163] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 312] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 350] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 330] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 350] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 126] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 160] = "LastContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 162] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -4775,9 +4632,10 @@ var ts; ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; - ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; - ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; - ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Accessor"] = 128] = "Accessor"; + ModifierFlags[ModifierFlags["Abstract"] = 256] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 512] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 1024] = "Default"; ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers"; ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated"; @@ -4790,10 +4648,10 @@ var ts; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - ModifierFlags[ModifierFlags["TypeScriptModifier"] = 116958] = "TypeScriptModifier"; - ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 257023] = "All"; - ModifierFlags[ModifierFlags["Modifier"] = 125951] = "Modifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 117086] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 1025] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 258047] = "All"; + ModifierFlags[ModifierFlags["Modifier"] = 126975] = "Modifier"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -4989,6 +4847,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["WriteComputedProps"] = 1073741824] = "WriteComputedProps"; // Errors (cont.) NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; @@ -5049,8 +4908,10 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // { [E.A]: 1 } + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["WriteComputedProps"] = 16] = "WriteComputedProps"; // Skip building an accessible symbol chain - /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 32] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -5164,6 +5025,7 @@ var ts; SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes"; SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes"; SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["AccessorExcludes"] = 13247] = "AccessorExcludes"; SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes"; SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; @@ -5247,8 +5109,8 @@ var ts; NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAccessInAsync"] = 2048] = "MethodWithSuperPropertyAccessInAsync"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAssignmentInAsync"] = 4096] = "MethodWithSuperPropertyAssignmentInAsync"; NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; @@ -6290,7 +6152,6 @@ var ts; var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); /* @internal */ ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); - /* @internal */ function setCustomPollingValues(system) { if (!system.getEnvironmentVariable) { return; @@ -6333,7 +6194,6 @@ var ts; createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels); } } - ts.setCustomPollingValues = setCustomPollingValues; function pollWatchedFileQueue(host, queue, pollIndex, chunkSize, callbackOnWatchFileStat) { var definedValueCopyToIndex = pollIndex; // Max visit would be all elements of the queue @@ -6379,7 +6239,6 @@ var ts; } } } - /* @internal */ function createDynamicPriorityPollingWatchFile(host) { var watchedFiles = []; var changedFilesInLastPoll = []; @@ -6488,7 +6347,6 @@ var ts; pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); } } - ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { // One file can have multiple watchers var fileWatcherCallbacks = ts.createMultiMap(); @@ -6567,42 +6425,38 @@ var ts; pollScheduled = host.setTimeout(pollQueue, PollingInterval.High); } } - /* @internal */ - function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) { - var cache = new ts.Map(); - var callbacksCache = ts.createMultiMap(); + function createSingleWatcherPerName(cache, useCaseSensitiveFileNames, name, callback, createWatcher) { var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - return function (fileName, callback, pollingInterval, options) { - var path = toCanonicalFileName(fileName); - var existing = cache.get(path); - if (existing) { - existing.refCount++; + var path = toCanonicalFileName(name); + var existing = cache.get(path); + if (existing) { + existing.callbacks.push(callback); + } + else { + cache.set(path, { + watcher: createWatcher(( + // Cant infer types correctly so lets satisfy checker + function (param1, param2, param3) { var _a; return (_a = cache.get(path)) === null || _a === void 0 ? void 0 : _a.callbacks.slice().forEach(function (cb) { return cb(param1, param2, param3); }); })), + callbacks: [callback] + }); + } + return { + close: function () { + var watcher = cache.get(path); + // Watcher is not expected to be undefined, but if it is normally its because + // exception was thrown somewhere else and watch state is not what it should be + if (!watcher) + return; + if (!ts.orderedRemoveItem(watcher.callbacks, callback) || watcher.callbacks.length) + return; + cache.delete(path); + ts.closeFileWatcherOf(watcher); } - else { - cache.set(path, { - watcher: watchFile(fileName, function (fileName, eventKind, modifiedTime) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind, modifiedTime); }); }, pollingInterval, options), - refCount: 1 - }); - } - callbacksCache.add(path, callback); - return { - close: function () { - var watcher = ts.Debug.checkDefined(cache.get(path)); - callbacksCache.remove(path, callback); - watcher.refCount--; - if (watcher.refCount) - return; - cache.delete(path); - ts.closeFileWatcherOf(watcher); - } - }; }; } - ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName; /** * Returns true if file status changed */ - /*@internal*/ function onWatchedFileStat(watchedFile, modifiedTime) { var oldTime = watchedFile.mtime.getTime(); var newTime = modifiedTime.getTime(); @@ -6614,7 +6468,6 @@ var ts; } return false; } - ts.onWatchedFileStat = onWatchedFileStat; /*@internal*/ function getFileWatcherEventKind(oldTime, newTime) { return oldTime === 0 @@ -6642,7 +6495,6 @@ var ts; * that means if this is recursive watcher, watch the children directories as well * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile) */ - /*@internal*/ function createDirectoryWatcherSupportingRecursive(_a) { var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, fileSystemEntryExists = _a.fileSystemEntryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; var cache = new ts.Map(); @@ -6851,18 +6703,15 @@ var ts; return ts.stringContains(toCanonicalFilePath(path), searchPath); } } - ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive; /*@internal*/ var FileSystemEntryKind; (function (FileSystemEntryKind) { FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {})); - /*@internal*/ function createFileWatcherCallback(callback) { return function (_fileName, eventKind, modifiedTime) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", "", modifiedTime); }; } - ts.createFileWatcherCallback = createFileWatcherCallback; function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime) { return function (eventName, _relativeFileName, modifiedTime) { if (eventName === "rename") { @@ -6896,7 +6745,10 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; + var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; + var pollingWatches = new ts.Map(); + var fsWatches = new ts.Map(); + var fsWatchesRecursive = new ts.Map(); var dynamicPollingWatchFile; var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; @@ -6959,8 +6811,8 @@ var ts; return useNonPollingWatchers ? // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : - // Default to do not use fixed polling interval - { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.FixedPollingInterval }; + // Default to using fs events + { watchFile: ts.WatchFileKind.UseFsEvents }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -7031,7 +6883,13 @@ var ts; }; } } + function pollingWatchFile(fileName, callback, pollingInterval, options) { + return createSingleWatcherPerName(pollingWatches, useCaseSensitiveFileNames, fileName, callback, function (cb) { return pollingWatchFileWorker(fileName, cb, pollingInterval, options); }); + } function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { + return createSingleWatcherPerName(recursive ? fsWatchesRecursive : fsWatches, useCaseSensitiveFileNames, fileOrDirectory, callback, function (cb) { return fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, cb, recursive, fallbackPollingInterval, fallbackOptions); }); + } + function fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { var lastDirectoryPartWithDirectorySeparator; var lastDirectoryPart; if (inodeWatching) { @@ -7210,7 +7068,7 @@ var ts; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); var _b = createSystemWatchFunctions({ - pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames), + pollingWatchFileWorker: fsWatchFileWorker, getModifiedTime: getModifiedTime, setTimeout: setTimeout, clearTimeout: clearTimeout, @@ -7226,7 +7084,6 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, - defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, inodeWatching: isLinuxOrMacOs, sysLog: sysLog, }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; @@ -8030,12 +7887,9 @@ var ts; * Normalize path separators, converting `\` into `/`. */ function normalizeSlashes(path) { - var index = path.indexOf("\\"); - if (index === -1) { - return path; - } - backslashRegExp.lastIndex = index; // prime regex with known position - return path.replace(backslashRegExp, ts.directorySeparator); + return path.indexOf("\\") !== -1 + ? path.replace(backslashRegExp, ts.directorySeparator) + : path; } ts.normalizeSlashes = normalizeSlashes; /** @@ -8618,6 +8472,8 @@ var ts; A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled: diag(1272, ts.DiagnosticCategory.Error, "A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_w_1272", "A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled."), _0_modifier_cannot_appear_on_a_type_parameter: diag(1273, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_parameter_1273", "'{0}' modifier cannot appear on a type parameter"), _0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias: diag(1274, ts.DiagnosticCategory.Error, "_0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias_1274", "'{0}' modifier can only appear on a type parameter of a class, interface or type alias"), + accessor_modifier_can_only_appear_on_a_property_declaration: diag(1275, ts.DiagnosticCategory.Error, "accessor_modifier_can_only_appear_on_a_property_declaration_1275", "'accessor' modifier can only appear on a property declaration."), + An_accessor_property_cannot_be_declared_optional: diag(1276, ts.DiagnosticCategory.Error, "An_accessor_property_cannot_be_declared_optional_1276", "An 'accessor' property cannot be declared optional."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."), The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level: diag(1309, ts.DiagnosticCategory.Error, "The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level_1309", "The current file is a CommonJS module and cannot use 'await' at the top level."), @@ -8668,7 +8524,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), - Class_constructor_may_not_be_a_generator: diag(1360, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_a_generator_1360", "Class constructor may not be a generator."), + Type_0_does_not_satisfy_the_expected_type_1: diag(1360, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_expected_type_1_1360", "Type '{0}' does not satisfy the expected type '{1}'."), _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."), _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), @@ -8676,6 +8532,7 @@ var ts; Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"), Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"), Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"), + Class_constructor_may_not_be_a_generator: diag(1368, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_a_generator_1368", "Class constructor may not be a generator."), Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"), This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error: diag(1371, ts.DiagnosticCategory.Error, "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371", "This import is never used as a value and must use 'import type' because 'importsNotUsedAsValues' is set to 'error'."), Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"), @@ -8849,14 +8706,12 @@ var ts; The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), - The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or__2360", "The left-hand side of an 'in' expression must be a private identifier or of type 'any', 'string', 'number', or 'symbol'."), - The_right_hand_side_of_an_in_expression_must_not_be_a_primitive: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361", "The right-hand side of an 'in' expression must not be a primitive."), The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), - This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."), + This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367", "This comparison appears to be unintentional because the types '{0}' and '{1}' have no overlap."), Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), @@ -9099,6 +8954,7 @@ var ts; Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable: diag(2635, ts.DiagnosticCategory.Error, "Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable_2635", "Type '{0}' has no signatures for which the type argument list is applicable."), Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation: diag(2636, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation_2636", "Type '{0}' is not assignable to type '{1}' as implied by variance annotation."), Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types: diag(2637, ts.DiagnosticCategory.Error, "Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_t_2637", "Variance annotations are only supported in type aliases for object, function, constructor, and mapped types."), + Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operator: diag(2638, ts.DiagnosticCategory.Error, "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638", "Type '{0}' may represent a primitive value, which is not permitted as the right operand of the 'in' operator."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -9279,6 +9135,7 @@ var ts; _0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation: diag(2842, ts.DiagnosticCategory.Error, "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842", "'{0}' is an unused renaming of '{1}'. Did you intend to use it as a type annotation?"), We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here: diag(2843, ts.DiagnosticCategory.Error, "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843", "We can only write a type for '{0}' by adding a type for the entire parameter here."), Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2844, ts.DiagnosticCategory.Error, "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844", "Type of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + This_condition_will_always_return_0: diag(2845, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_2845", "This condition will always return '{0}'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -9736,6 +9593,11 @@ var ts; Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6398, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was not resolved."), Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted: diag(6399, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399", "Project '{0}' is out of date because buildinfo file '{1}' indicates that some of the changes were not emitted"), Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files: diag(6400, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400", "Project '{0}' is up to date but needs to update timestamps of output files that are older than input files"), + Project_0_is_out_of_date_because_there_was_error_reading_file_1: diag(6401, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401", "Project '{0}' is out of date because there was error reading file '{1}'"), + Resolving_in_0_mode_with_conditions_1: diag(6402, ts.DiagnosticCategory.Message, "Resolving_in_0_mode_with_conditions_1_6402", "Resolving in {0} mode with conditions {1}."), + Matched_0_condition_1: diag(6403, ts.DiagnosticCategory.Message, "Matched_0_condition_1_6403", "Matched '{0}' condition '{1}'."), + Using_0_subpath_1_with_target_2: diag(6404, ts.DiagnosticCategory.Message, "Using_0_subpath_1_with_target_2_6404", "Using '{0}' subpath '{1}' with target '{2}'."), + Saw_non_matching_condition_0: diag(6405, ts.DiagnosticCategory.Message, "Saw_non_matching_condition_0_6405", "Saw non-matching condition '{0}'."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -9978,6 +9840,7 @@ var ts; The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."), You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder: diag(8035, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035", "You cannot rename elements that are defined in a 'node_modules' folder."), You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), + Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files: diag(8037, ts.DiagnosticCategory.Error, "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037", "Type satisfaction expressions can only be used in TypeScript files."), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -10051,6 +9914,8 @@ var ts; Remove_type_from_import_of_0_from_1: diag(90056, ts.DiagnosticCategory.Message, "Remove_type_from_import_of_0_from_1_90056", "Remove 'type' from import of '{0}' from \"{1}\""), Add_import_from_0: diag(90057, ts.DiagnosticCategory.Message, "Add_import_from_0_90057", "Add import from \"{0}\""), Update_import_from_0: diag(90058, ts.DiagnosticCategory.Message, "Update_import_from_0_90058", "Update import from \"{0}\""), + Export_0_from_module_1: diag(90059, ts.DiagnosticCategory.Message, "Export_0_from_module_1_90059", "Export '{0}' from module '{1}'"), + Export_all_referenced_locals: diag(90060, ts.DiagnosticCategory.Message, "Export_all_referenced_locals_90060", "Export all referenced locals"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -10149,6 +10014,7 @@ var ts; Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"), Convert_invalid_character_to_its_html_entity_code: diag(95100, ts.DiagnosticCategory.Message, "Convert_invalid_character_to_its_html_entity_code_95100", "Convert invalid character to its html entity code"), Convert_all_invalid_characters_to_HTML_entity_code: diag(95101, ts.DiagnosticCategory.Message, "Convert_all_invalid_characters_to_HTML_entity_code_95101", "Convert all invalid characters to HTML entity code"), + Convert_all_const_to_let: diag(95102, ts.DiagnosticCategory.Message, "Convert_all_const_to_let_95102", "Convert all 'const' to 'let'"), Convert_function_expression_0_to_arrow_function: diag(95105, ts.DiagnosticCategory.Message, "Convert_function_expression_0_to_arrow_function_95105", "Convert function expression '{0}' to arrow function"), Convert_function_declaration_0_to_arrow_function: diag(95106, ts.DiagnosticCategory.Message, "Convert_function_declaration_0_to_arrow_function_95106", "Convert function declaration '{0}' to arrow function"), Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"), @@ -10218,6 +10084,8 @@ var ts; Delete_unused_param_tag_0: diag(95171, ts.DiagnosticCategory.Message, "Delete_unused_param_tag_0_95171", "Delete unused '@param' tag '{0}'"), Delete_all_unused_param_tags: diag(95172, ts.DiagnosticCategory.Message, "Delete_all_unused_param_tags_95172", "Delete all unused '@param' tags"), Rename_param_tag_name_0_to_1: diag(95173, ts.DiagnosticCategory.Message, "Rename_param_tag_name_0_to_1_95173", "Rename '@param' tag name '{0}' to '{1}'"), + Use_0: diag(95174, ts.DiagnosticCategory.Message, "Use_0_95174", "Use `{0}`."), + Use_Number_isNaN_in_all_conditions: diag(95175, ts.DiagnosticCategory.Message, "Use_Number_isNaN_in_all_conditions_95175", "Use `Number.isNaN` in all conditions."), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -10251,6 +10119,12 @@ var ts; _0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation: diag(18042, ts.DiagnosticCategory.Error, "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042", "'{0}' is a type and cannot be imported in JavaScript files. Use '{1}' in a JSDoc type annotation."), Types_cannot_appear_in_export_declarations_in_JavaScript_files: diag(18043, ts.DiagnosticCategory.Error, "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043", "Types cannot appear in export declarations in JavaScript files."), _0_is_automatically_exported_here: diag(18044, ts.DiagnosticCategory.Message, "_0_is_automatically_exported_here_18044", "'{0}' is automatically exported here."), + Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18045, ts.DiagnosticCategory.Error, "Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher_18045", "Properties with the 'accessor' modifier are only available when targeting ECMAScript 2015 and higher."), + _0_is_of_type_unknown: diag(18046, ts.DiagnosticCategory.Error, "_0_is_of_type_unknown_18046", "'{0}' is of type 'unknown'."), + _0_is_possibly_null: diag(18047, ts.DiagnosticCategory.Error, "_0_is_possibly_null_18047", "'{0}' is possibly 'null'."), + _0_is_possibly_undefined: diag(18048, ts.DiagnosticCategory.Error, "_0_is_possibly_undefined_18048", "'{0}' is possibly 'undefined'."), + _0_is_possibly_null_or_undefined: diag(18049, ts.DiagnosticCategory.Error, "_0_is_possibly_null_or_undefined_18049", "'{0}' is possibly 'null' or 'undefined'."), + The_value_0_cannot_be_used_here: diag(18050, ts.DiagnosticCategory.Error, "The_value_0_cannot_be_used_here_18050", "The value '{0}' cannot be used here."), }; })(ts || (ts = {})); var ts; @@ -10269,12 +10143,13 @@ var ts; /** @internal */ ts.textToKeywordObj = (_a = { abstract: 126 /* SyntaxKind.AbstractKeyword */, - any: 130 /* SyntaxKind.AnyKeyword */, - as: 127 /* SyntaxKind.AsKeyword */, - asserts: 128 /* SyntaxKind.AssertsKeyword */, - assert: 129 /* SyntaxKind.AssertKeyword */, - bigint: 158 /* SyntaxKind.BigIntKeyword */, - boolean: 133 /* SyntaxKind.BooleanKeyword */, + accessor: 127 /* SyntaxKind.AccessorKeyword */, + any: 131 /* SyntaxKind.AnyKeyword */, + as: 128 /* SyntaxKind.AsKeyword */, + asserts: 129 /* SyntaxKind.AssertsKeyword */, + assert: 130 /* SyntaxKind.AssertKeyword */, + bigint: 160 /* SyntaxKind.BigIntKeyword */, + boolean: 134 /* SyntaxKind.BooleanKeyword */, break: 81 /* SyntaxKind.BreakKeyword */, case: 82 /* SyntaxKind.CaseKeyword */, catch: 83 /* SyntaxKind.CatchKeyword */, @@ -10282,9 +10157,9 @@ var ts; continue: 86 /* SyntaxKind.ContinueKeyword */, const: 85 /* SyntaxKind.ConstKeyword */ }, - _a["" + "constructor"] = 134 /* SyntaxKind.ConstructorKeyword */, + _a["" + "constructor"] = 135 /* SyntaxKind.ConstructorKeyword */, _a.debugger = 87 /* SyntaxKind.DebuggerKeyword */, - _a.declare = 135 /* SyntaxKind.DeclareKeyword */, + _a.declare = 136 /* SyntaxKind.DeclareKeyword */, _a.default = 88 /* SyntaxKind.DefaultKeyword */, _a.delete = 89 /* SyntaxKind.DeleteKeyword */, _a.do = 90 /* SyntaxKind.DoKeyword */, @@ -10295,60 +10170,61 @@ var ts; _a.false = 95 /* SyntaxKind.FalseKeyword */, _a.finally = 96 /* SyntaxKind.FinallyKeyword */, _a.for = 97 /* SyntaxKind.ForKeyword */, - _a.from = 156 /* SyntaxKind.FromKeyword */, + _a.from = 158 /* SyntaxKind.FromKeyword */, _a.function = 98 /* SyntaxKind.FunctionKeyword */, - _a.get = 136 /* SyntaxKind.GetKeyword */, + _a.get = 137 /* SyntaxKind.GetKeyword */, _a.if = 99 /* SyntaxKind.IfKeyword */, _a.implements = 117 /* SyntaxKind.ImplementsKeyword */, _a.import = 100 /* SyntaxKind.ImportKeyword */, _a.in = 101 /* SyntaxKind.InKeyword */, - _a.infer = 137 /* SyntaxKind.InferKeyword */, + _a.infer = 138 /* SyntaxKind.InferKeyword */, _a.instanceof = 102 /* SyntaxKind.InstanceOfKeyword */, _a.interface = 118 /* SyntaxKind.InterfaceKeyword */, - _a.intrinsic = 138 /* SyntaxKind.IntrinsicKeyword */, - _a.is = 139 /* SyntaxKind.IsKeyword */, - _a.keyof = 140 /* SyntaxKind.KeyOfKeyword */, + _a.intrinsic = 139 /* SyntaxKind.IntrinsicKeyword */, + _a.is = 140 /* SyntaxKind.IsKeyword */, + _a.keyof = 141 /* SyntaxKind.KeyOfKeyword */, _a.let = 119 /* SyntaxKind.LetKeyword */, - _a.module = 141 /* SyntaxKind.ModuleKeyword */, - _a.namespace = 142 /* SyntaxKind.NamespaceKeyword */, - _a.never = 143 /* SyntaxKind.NeverKeyword */, + _a.module = 142 /* SyntaxKind.ModuleKeyword */, + _a.namespace = 143 /* SyntaxKind.NamespaceKeyword */, + _a.never = 144 /* SyntaxKind.NeverKeyword */, _a.new = 103 /* SyntaxKind.NewKeyword */, _a.null = 104 /* SyntaxKind.NullKeyword */, - _a.number = 147 /* SyntaxKind.NumberKeyword */, - _a.object = 148 /* SyntaxKind.ObjectKeyword */, + _a.number = 148 /* SyntaxKind.NumberKeyword */, + _a.object = 149 /* SyntaxKind.ObjectKeyword */, _a.package = 120 /* SyntaxKind.PackageKeyword */, _a.private = 121 /* SyntaxKind.PrivateKeyword */, _a.protected = 122 /* SyntaxKind.ProtectedKeyword */, _a.public = 123 /* SyntaxKind.PublicKeyword */, - _a.override = 159 /* SyntaxKind.OverrideKeyword */, - _a.out = 144 /* SyntaxKind.OutKeyword */, - _a.readonly = 145 /* SyntaxKind.ReadonlyKeyword */, - _a.require = 146 /* SyntaxKind.RequireKeyword */, - _a.global = 157 /* SyntaxKind.GlobalKeyword */, + _a.override = 161 /* SyntaxKind.OverrideKeyword */, + _a.out = 145 /* SyntaxKind.OutKeyword */, + _a.readonly = 146 /* SyntaxKind.ReadonlyKeyword */, + _a.require = 147 /* SyntaxKind.RequireKeyword */, + _a.global = 159 /* SyntaxKind.GlobalKeyword */, _a.return = 105 /* SyntaxKind.ReturnKeyword */, - _a.set = 149 /* SyntaxKind.SetKeyword */, + _a.satisfies = 150 /* SyntaxKind.SatisfiesKeyword */, + _a.set = 151 /* SyntaxKind.SetKeyword */, _a.static = 124 /* SyntaxKind.StaticKeyword */, - _a.string = 150 /* SyntaxKind.StringKeyword */, + _a.string = 152 /* SyntaxKind.StringKeyword */, _a.super = 106 /* SyntaxKind.SuperKeyword */, _a.switch = 107 /* SyntaxKind.SwitchKeyword */, - _a.symbol = 151 /* SyntaxKind.SymbolKeyword */, + _a.symbol = 153 /* SyntaxKind.SymbolKeyword */, _a.this = 108 /* SyntaxKind.ThisKeyword */, _a.throw = 109 /* SyntaxKind.ThrowKeyword */, _a.true = 110 /* SyntaxKind.TrueKeyword */, _a.try = 111 /* SyntaxKind.TryKeyword */, - _a.type = 152 /* SyntaxKind.TypeKeyword */, + _a.type = 154 /* SyntaxKind.TypeKeyword */, _a.typeof = 112 /* SyntaxKind.TypeOfKeyword */, - _a.undefined = 153 /* SyntaxKind.UndefinedKeyword */, - _a.unique = 154 /* SyntaxKind.UniqueKeyword */, - _a.unknown = 155 /* SyntaxKind.UnknownKeyword */, + _a.undefined = 155 /* SyntaxKind.UndefinedKeyword */, + _a.unique = 156 /* SyntaxKind.UniqueKeyword */, + _a.unknown = 157 /* SyntaxKind.UnknownKeyword */, _a.var = 113 /* SyntaxKind.VarKeyword */, _a.void = 114 /* SyntaxKind.VoidKeyword */, _a.while = 115 /* SyntaxKind.WhileKeyword */, _a.with = 116 /* SyntaxKind.WithKeyword */, _a.yield = 125 /* SyntaxKind.YieldKeyword */, - _a.async = 131 /* SyntaxKind.AsyncKeyword */, - _a.await = 132 /* SyntaxKind.AwaitKeyword */, - _a.of = 160 /* SyntaxKind.OfKeyword */, + _a.async = 132 /* SyntaxKind.AsyncKeyword */, + _a.await = 133 /* SyntaxKind.AwaitKeyword */, + _a.of = 162 /* SyntaxKind.OfKeyword */, _a); var textToKeyword = new ts.Map(ts.getEntries(ts.textToKeywordObj)); var textToToken = new ts.Map(ts.getEntries(__assign(__assign({}, ts.textToKeywordObj), { "{": 18 /* SyntaxKind.OpenBraceToken */, "}": 19 /* SyntaxKind.CloseBraceToken */, "(": 20 /* SyntaxKind.OpenParenToken */, ")": 21 /* SyntaxKind.CloseParenToken */, "[": 22 /* SyntaxKind.OpenBracketToken */, "]": 23 /* SyntaxKind.CloseBracketToken */, ".": 24 /* SyntaxKind.DotToken */, "...": 25 /* SyntaxKind.DotDotDotToken */, ";": 26 /* SyntaxKind.SemicolonToken */, ",": 27 /* SyntaxKind.CommaToken */, "<": 29 /* SyntaxKind.LessThanToken */, ">": 31 /* SyntaxKind.GreaterThanToken */, "<=": 32 /* SyntaxKind.LessThanEqualsToken */, ">=": 33 /* SyntaxKind.GreaterThanEqualsToken */, "==": 34 /* SyntaxKind.EqualsEqualsToken */, "!=": 35 /* SyntaxKind.ExclamationEqualsToken */, "===": 36 /* SyntaxKind.EqualsEqualsEqualsToken */, "!==": 37 /* SyntaxKind.ExclamationEqualsEqualsToken */, "=>": 38 /* SyntaxKind.EqualsGreaterThanToken */, "+": 39 /* SyntaxKind.PlusToken */, "-": 40 /* SyntaxKind.MinusToken */, "**": 42 /* SyntaxKind.AsteriskAsteriskToken */, "*": 41 /* SyntaxKind.AsteriskToken */, "/": 43 /* SyntaxKind.SlashToken */, "%": 44 /* SyntaxKind.PercentToken */, "++": 45 /* SyntaxKind.PlusPlusToken */, "--": 46 /* SyntaxKind.MinusMinusToken */, "<<": 47 /* SyntaxKind.LessThanLessThanToken */, ">": 48 /* SyntaxKind.GreaterThanGreaterThanToken */, ">>>": 49 /* SyntaxKind.GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* SyntaxKind.AmpersandToken */, "|": 51 /* SyntaxKind.BarToken */, "^": 52 /* SyntaxKind.CaretToken */, "!": 53 /* SyntaxKind.ExclamationToken */, "~": 54 /* SyntaxKind.TildeToken */, "&&": 55 /* SyntaxKind.AmpersandAmpersandToken */, "||": 56 /* SyntaxKind.BarBarToken */, "?": 57 /* SyntaxKind.QuestionToken */, "??": 60 /* SyntaxKind.QuestionQuestionToken */, "?.": 28 /* SyntaxKind.QuestionDotToken */, ":": 58 /* SyntaxKind.ColonToken */, "=": 63 /* SyntaxKind.EqualsToken */, "+=": 64 /* SyntaxKind.PlusEqualsToken */, "-=": 65 /* SyntaxKind.MinusEqualsToken */, "*=": 66 /* SyntaxKind.AsteriskEqualsToken */, "**=": 67 /* SyntaxKind.AsteriskAsteriskEqualsToken */, "/=": 68 /* SyntaxKind.SlashEqualsToken */, "%=": 69 /* SyntaxKind.PercentEqualsToken */, "<<=": 70 /* SyntaxKind.LessThanLessThanEqualsToken */, ">>=": 71 /* SyntaxKind.GreaterThanGreaterThanEqualsToken */, ">>>=": 72 /* SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 73 /* SyntaxKind.AmpersandEqualsToken */, "|=": 74 /* SyntaxKind.BarEqualsToken */, "^=": 78 /* SyntaxKind.CaretEqualsToken */, "||=": 75 /* SyntaxKind.BarBarEqualsToken */, "&&=": 76 /* SyntaxKind.AmpersandAmpersandEqualsToken */, "??=": 77 /* SyntaxKind.QuestionQuestionEqualsToken */, "@": 59 /* SyntaxKind.AtToken */, "#": 62 /* SyntaxKind.HashToken */, "`": 61 /* SyntaxKind.BacktickToken */ }))); @@ -10471,7 +10347,7 @@ var ts; ts.stringToToken = stringToToken; /* @internal */ function computeLineStarts(text) { - var result = new Array(); + var result = []; var pos = 0; var lineStart = 0; while (pos < text.length) { @@ -11497,7 +11373,7 @@ var ts; return -1; } function peekExtendedUnicodeEscape() { - if (languageVersion >= 2 /* ScriptTarget.ES2015 */ && codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { + if (codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { var start_2 = pos; pos += 3; var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); @@ -12032,12 +11908,36 @@ var ts; pos++; return token = 0 /* SyntaxKind.Unknown */; } - if (isIdentifierStart(codePointAt(text, pos + 1), languageVersion)) { + var charAfterHash = codePointAt(text, pos + 1); + if (charAfterHash === 92 /* CharacterCodes.backslash */) { pos++; - scanIdentifier(codePointAt(text, pos), languageVersion); + var extendedCookedChar_1 = peekExtendedUnicodeEscape(); + if (extendedCookedChar_1 >= 0 && isIdentifierStart(extendedCookedChar_1, languageVersion)) { + pos += 3; + tokenFlags |= 8 /* TokenFlags.ExtendedUnicodeEscape */; + tokenValue = "#" + scanExtendedUnicodeEscape() + scanIdentifierParts(); + return token = 80 /* SyntaxKind.PrivateIdentifier */; + } + var cookedChar_1 = peekUnicodeEscape(); + if (cookedChar_1 >= 0 && isIdentifierStart(cookedChar_1, languageVersion)) { + pos += 6; + tokenFlags |= 1024 /* TokenFlags.UnicodeEscape */; + tokenValue = "#" + String.fromCharCode(cookedChar_1) + scanIdentifierParts(); + return token = 80 /* SyntaxKind.PrivateIdentifier */; + } + pos--; + } + if (isIdentifierStart(charAfterHash, languageVersion)) { + pos++; + // We're relying on scanIdentifier's behavior and adjusting the token kind after the fact. + // Notably absent from this block is the fact that calling a function named "scanIdentifier", + // but identifiers don't include '#', and that function doesn't deal with it at all. + // This works because 'scanIdentifier' tries to reuse source characters and builds up substrings; + // however, it starts at the 'tokenPos' which includes the '#', and will "accidentally" prepend the '#' for us. + scanIdentifier(charAfterHash, languageVersion); } else { - tokenValue = String.fromCharCode(codePointAt(text, pos)); + tokenValue = "#"; error(ts.Diagnostics.Invalid_character, pos++, charSize(ch)); } return token = 80 /* SyntaxKind.PrivateIdentifier */; @@ -12788,9 +12688,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 163 /* SyntaxKind.TypeParameter */) { + if (d && d.kind === 165 /* SyntaxKind.TypeParameter */) { for (var current = d; current; current = current.parent) { - if (isFunctionLike(current) || isClassLike(current) || current.kind === 258 /* SyntaxKind.InterfaceDeclaration */) { + if (isFunctionLike(current) || isClassLike(current) || current.kind === 261 /* SyntaxKind.InterfaceDeclaration */) { return current; } } @@ -12798,7 +12698,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 16476 /* ModifierFlags.ParameterPropertyModifier */) && parent.kind === 171 /* SyntaxKind.Constructor */; + return ts.hasSyntacticModifier(node, 16476 /* ModifierFlags.ParameterPropertyModifier */) && parent.kind === 173 /* SyntaxKind.Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -12828,14 +12728,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 254 /* SyntaxKind.VariableDeclaration */) { + if (node.kind === 257 /* SyntaxKind.VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (node && node.kind === 258 /* SyntaxKind.VariableDeclarationList */) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 237 /* SyntaxKind.VariableStatement */) { + if (node && node.kind === 240 /* SyntaxKind.VariableStatement */) { flags |= getFlags(node); } return flags; @@ -13008,30 +12908,30 @@ var ts; } // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } break; - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: var expr = hostNode.expression; - if (expr.kind === 221 /* SyntaxKind.BinaryExpression */ && expr.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { + if (expr.kind === 223 /* SyntaxKind.BinaryExpression */ && expr.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { expr = expr.left; } switch (expr.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return expr.name; - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } break; - case 212 /* SyntaxKind.ParenthesizedExpression */: { + case 214 /* SyntaxKind.ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 250 /* SyntaxKind.LabeledStatement */: { + case 253 /* SyntaxKind.LabeledStatement */: { if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -13068,16 +12968,16 @@ var ts; switch (declaration.kind) { case 79 /* SyntaxKind.Identifier */: return declaration; - case 347 /* SyntaxKind.JSDocPropertyTag */: - case 340 /* SyntaxKind.JSDocParameterTag */: { + case 350 /* SyntaxKind.JSDocPropertyTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 161 /* SyntaxKind.QualifiedName */) { + if (name.kind === 163 /* SyntaxKind.QualifiedName */) { return name.right; } break; } - case 208 /* SyntaxKind.CallExpression */: - case 221 /* SyntaxKind.BinaryExpression */: { + case 210 /* SyntaxKind.CallExpression */: + case 223 /* SyntaxKind.BinaryExpression */: { var expr_1 = declaration; switch (ts.getAssignmentDeclarationKind(expr_1)) { case 1 /* AssignmentDeclarationKind.ExportsProperty */: @@ -13093,15 +12993,15 @@ var ts; return undefined; } } - case 345 /* SyntaxKind.JSDocTypedefTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 339 /* SyntaxKind.JSDocEnumTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: return nameForNamelessJSDocTypedef(declaration); - case 271 /* SyntaxKind.ExportAssignment */: { + case 274 /* SyntaxKind.ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: var expr = declaration; if (ts.isBindableStaticElementAccessExpression(expr)) { return expr.argumentExpression; @@ -13145,7 +13045,7 @@ var ts; } ts.getDecorators = getDecorators; function getModifiers(node) { - if (ts.hasSyntacticModifier(node, 125951 /* ModifierFlags.Modifier */)) { + if (ts.hasSyntacticModifier(node, 126975 /* ModifierFlags.Modifier */)) { return ts.filter(node.modifiers, isModifier); } } @@ -13406,12 +13306,12 @@ var ts; /** Gets the text of a jsdoc comment, flattening links to their text. */ function getTextOfJSDocComment(comment) { return typeof comment === "string" ? comment - : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { return c.kind === 321 /* SyntaxKind.JSDocText */ ? c.text : formatJSDocLink(c); }).join(""); + : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { return c.kind === 324 /* SyntaxKind.JSDocText */ ? c.text : formatJSDocLink(c); }).join(""); } ts.getTextOfJSDocComment = getTextOfJSDocComment; function formatJSDocLink(link) { - var kind = link.kind === 324 /* SyntaxKind.JSDocLink */ ? "link" - : link.kind === 325 /* SyntaxKind.JSDocLinkCode */ ? "linkcode" + var kind = link.kind === 327 /* SyntaxKind.JSDocLink */ ? "link" + : link.kind === 328 /* SyntaxKind.JSDocLinkCode */ ? "linkcode" : "linkplain"; var name = link.name ? ts.entityNameToString(link.name) : ""; var space = link.name && link.text.startsWith("://") ? "" : " "; @@ -13432,7 +13332,7 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 320 /* SyntaxKind.JSDoc */); + ts.Debug.assert(node.parent.kind === 323 /* SyntaxKind.JSDoc */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } if (node.typeParameters) { @@ -13467,7 +13367,7 @@ var ts; ts.isMemberName = isMemberName; /* @internal */ function isGetOrSetAccessorDeclaration(node) { - return node.kind === 173 /* SyntaxKind.SetAccessor */ || node.kind === 172 /* SyntaxKind.GetAccessor */; + return node.kind === 175 /* SyntaxKind.SetAccessor */ || node.kind === 174 /* SyntaxKind.GetAccessor */; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; function isPropertyAccessChain(node) { @@ -13485,10 +13385,10 @@ var ts; function isOptionalChain(node) { var kind = node.kind; return !!(node.flags & 32 /* NodeFlags.OptionalChain */) && - (kind === 206 /* SyntaxKind.PropertyAccessExpression */ - || kind === 207 /* SyntaxKind.ElementAccessExpression */ - || kind === 208 /* SyntaxKind.CallExpression */ - || kind === 230 /* SyntaxKind.NonNullExpression */); + (kind === 208 /* SyntaxKind.PropertyAccessExpression */ + || kind === 209 /* SyntaxKind.ElementAccessExpression */ + || kind === 210 /* SyntaxKind.CallExpression */ + || kind === 232 /* SyntaxKind.NonNullExpression */); } ts.isOptionalChain = isOptionalChain; /* @internal */ @@ -13523,7 +13423,7 @@ var ts; } ts.isOutermostOptionalChain = isOutermostOptionalChain; function isNullishCoalesce(node) { - return node.kind === 221 /* SyntaxKind.BinaryExpression */ && node.operatorToken.kind === 60 /* SyntaxKind.QuestionQuestionToken */; + return node.kind === 223 /* SyntaxKind.BinaryExpression */ && node.operatorToken.kind === 60 /* SyntaxKind.QuestionQuestionToken */; } ts.isNullishCoalesce = isNullishCoalesce; function isConstTypeReference(node) { @@ -13540,17 +13440,17 @@ var ts; } ts.isNonNullChain = isNonNullChain; function isBreakOrContinueStatement(node) { - return node.kind === 246 /* SyntaxKind.BreakStatement */ || node.kind === 245 /* SyntaxKind.ContinueStatement */; + return node.kind === 249 /* SyntaxKind.BreakStatement */ || node.kind === 248 /* SyntaxKind.ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isNamedExportBindings(node) { - return node.kind === 274 /* SyntaxKind.NamespaceExport */ || node.kind === 273 /* SyntaxKind.NamedExports */; + return node.kind === 277 /* SyntaxKind.NamespaceExport */ || node.kind === 276 /* SyntaxKind.NamedExports */; } ts.isNamedExportBindings = isNamedExportBindings; function isUnparsedTextLike(node) { switch (node.kind) { - case 302 /* SyntaxKind.UnparsedText */: - case 303 /* SyntaxKind.UnparsedInternalText */: + case 305 /* SyntaxKind.UnparsedText */: + case 306 /* SyntaxKind.UnparsedInternalText */: return true; default: return false; @@ -13559,12 +13459,12 @@ var ts; ts.isUnparsedTextLike = isUnparsedTextLike; function isUnparsedNode(node) { return isUnparsedTextLike(node) || - node.kind === 300 /* SyntaxKind.UnparsedPrologue */ || - node.kind === 304 /* SyntaxKind.UnparsedSyntheticReference */; + node.kind === 303 /* SyntaxKind.UnparsedPrologue */ || + node.kind === 307 /* SyntaxKind.UnparsedSyntheticReference */; } ts.isUnparsedNode = isUnparsedNode; function isJSDocPropertyLikeTag(node) { - return node.kind === 347 /* SyntaxKind.JSDocPropertyTag */ || node.kind === 340 /* SyntaxKind.JSDocParameterTag */; + return node.kind === 350 /* SyntaxKind.JSDocPropertyTag */ || node.kind === 343 /* SyntaxKind.JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; // #endregion @@ -13580,7 +13480,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 161 /* SyntaxKind.FirstNode */; + return kind >= 163 /* SyntaxKind.FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -13589,7 +13489,7 @@ var ts; * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isTokenKind(kind) { - return kind >= 0 /* SyntaxKind.FirstToken */ && kind <= 160 /* SyntaxKind.LastToken */; + return kind >= 0 /* SyntaxKind.FirstToken */ && kind <= 162 /* SyntaxKind.LastToken */; } ts.isTokenKind = isTokenKind; /** @@ -13604,7 +13504,7 @@ var ts; // Node Arrays /* @internal */ function isNodeArray(array) { - return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); + return ts.hasProperty(array, "pos") && ts.hasProperty(array, "end"); } ts.isNodeArray = isNodeArray; // Literals @@ -13620,11 +13520,11 @@ var ts; /** @internal */ function isLiteralExpressionOfObject(node) { switch (node.kind) { - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: case 13 /* SyntaxKind.RegularExpressionLiteral */: - case 213 /* SyntaxKind.FunctionExpression */: - case 226 /* SyntaxKind.ClassExpression */: + case 215 /* SyntaxKind.FunctionExpression */: + case 228 /* SyntaxKind.ClassExpression */: return true; } return false; @@ -13652,13 +13552,13 @@ var ts; ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isTypeOnlyImportOrExportDeclaration(node) { switch (node.kind) { - case 270 /* SyntaxKind.ImportSpecifier */: - case 275 /* SyntaxKind.ExportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: return node.isTypeOnly || node.parent.parent.isTypeOnly; - case 268 /* SyntaxKind.NamespaceImport */: + case 271 /* SyntaxKind.NamespaceImport */: return node.parent.isTypeOnly; - case 267 /* SyntaxKind.ImportClause */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 270 /* SyntaxKind.ImportClause */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return node.isTypeOnly; default: return false; @@ -13679,6 +13579,11 @@ var ts; return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* GeneratedIdentifierFlags.KindMask */) > 0 /* GeneratedIdentifierFlags.None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; + /* @internal */ + function isGeneratedPrivateIdentifier(node) { + return ts.isPrivateIdentifier(node) && (node.autoGenerateFlags & 7 /* GeneratedIdentifierFlags.KindMask */) > 0 /* GeneratedIdentifierFlags.None */; + } + ts.isGeneratedPrivateIdentifier = isGeneratedPrivateIdentifier; // Private Identifiers /*@internal*/ function isPrivateIdentifierClassElementDeclaration(node) { @@ -13695,19 +13600,20 @@ var ts; function isModifierKind(token) { switch (token) { case 126 /* SyntaxKind.AbstractKeyword */: - case 131 /* SyntaxKind.AsyncKeyword */: + case 127 /* SyntaxKind.AccessorKeyword */: + case 132 /* SyntaxKind.AsyncKeyword */: case 85 /* SyntaxKind.ConstKeyword */: - case 135 /* SyntaxKind.DeclareKeyword */: + case 136 /* SyntaxKind.DeclareKeyword */: case 88 /* SyntaxKind.DefaultKeyword */: case 93 /* SyntaxKind.ExportKeyword */: case 101 /* SyntaxKind.InKeyword */: case 123 /* SyntaxKind.PublicKeyword */: case 121 /* SyntaxKind.PrivateKeyword */: case 122 /* SyntaxKind.ProtectedKeyword */: - case 145 /* SyntaxKind.ReadonlyKeyword */: + case 146 /* SyntaxKind.ReadonlyKeyword */: case 124 /* SyntaxKind.StaticKeyword */: - case 144 /* SyntaxKind.OutKeyword */: - case 159 /* SyntaxKind.OverrideKeyword */: + case 145 /* SyntaxKind.OutKeyword */: + case 161 /* SyntaxKind.OverrideKeyword */: return true; } return false; @@ -13720,7 +13626,10 @@ var ts; ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 124 /* SyntaxKind.StaticKeyword */ || idToken === 159 /* SyntaxKind.OverrideKeyword */; + return isParameterPropertyModifier(idToken) || + idToken === 124 /* SyntaxKind.StaticKeyword */ || + idToken === 161 /* SyntaxKind.OverrideKeyword */ || + idToken === 127 /* SyntaxKind.AccessorKeyword */; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -13729,7 +13638,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 161 /* SyntaxKind.QualifiedName */ + return kind === 163 /* SyntaxKind.QualifiedName */ || kind === 79 /* SyntaxKind.Identifier */; } ts.isEntityName = isEntityName; @@ -13739,14 +13648,14 @@ var ts; || kind === 80 /* SyntaxKind.PrivateIdentifier */ || kind === 10 /* SyntaxKind.StringLiteral */ || kind === 8 /* SyntaxKind.NumericLiteral */ - || kind === 162 /* SyntaxKind.ComputedPropertyName */; + || kind === 164 /* SyntaxKind.ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 79 /* SyntaxKind.Identifier */ - || kind === 201 /* SyntaxKind.ObjectBindingPattern */ - || kind === 202 /* SyntaxKind.ArrayBindingPattern */; + || kind === 203 /* SyntaxKind.ObjectBindingPattern */ + || kind === 204 /* SyntaxKind.ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions @@ -13771,13 +13680,13 @@ var ts; ts.isBooleanLiteral = isBooleanLiteral; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: return true; default: return false; @@ -13786,14 +13695,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 168 /* SyntaxKind.MethodSignature */: - case 174 /* SyntaxKind.CallSignature */: - case 323 /* SyntaxKind.JSDocSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 176 /* SyntaxKind.IndexSignature */: - case 179 /* SyntaxKind.FunctionType */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 180 /* SyntaxKind.ConstructorType */: + case 170 /* SyntaxKind.MethodSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 326 /* SyntaxKind.JSDocSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 178 /* SyntaxKind.IndexSignature */: + case 181 /* SyntaxKind.FunctionType */: + case 320 /* SyntaxKind.JSDocFunctionType */: + case 182 /* SyntaxKind.ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -13808,36 +13717,53 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 171 /* SyntaxKind.Constructor */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */ - || kind === 176 /* SyntaxKind.IndexSignature */ - || kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ - || kind === 234 /* SyntaxKind.SemicolonClassElement */; + return kind === 173 /* SyntaxKind.Constructor */ + || kind === 169 /* SyntaxKind.PropertyDeclaration */ + || kind === 171 /* SyntaxKind.MethodDeclaration */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 175 /* SyntaxKind.SetAccessor */ + || kind === 178 /* SyntaxKind.IndexSignature */ + || kind === 172 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 237 /* SyntaxKind.SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 257 /* SyntaxKind.ClassDeclaration */ || node.kind === 226 /* SyntaxKind.ClassExpression */); + return node && (node.kind === 260 /* SyntaxKind.ClassDeclaration */ || node.kind === 228 /* SyntaxKind.ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 172 /* SyntaxKind.GetAccessor */ || node.kind === 173 /* SyntaxKind.SetAccessor */); + return node && (node.kind === 174 /* SyntaxKind.GetAccessor */ || node.kind === 175 /* SyntaxKind.SetAccessor */); } ts.isAccessor = isAccessor; + function isAutoAccessorPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && ts.hasAccessorModifier(node); + } + ts.isAutoAccessorPropertyDeclaration = isAutoAccessorPropertyDeclaration; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return true; default: return false; } } ts.isMethodOrAccessor = isMethodOrAccessor; + /* @internal */ + function isNamedClassElement(node) { + switch (node.kind) { + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + return true; + default: + return false; + } + } + ts.isNamedClassElement = isNamedClassElement; // Type members function isModifierLike(node) { return isModifier(node) || ts.isDecorator(node); @@ -13845,13 +13771,13 @@ var ts; ts.isModifierLike = isModifierLike; function isTypeElement(node) { var kind = node.kind; - return kind === 175 /* SyntaxKind.ConstructSignature */ - || kind === 174 /* SyntaxKind.CallSignature */ - || kind === 166 /* SyntaxKind.PropertySignature */ - || kind === 168 /* SyntaxKind.MethodSignature */ - || kind === 176 /* SyntaxKind.IndexSignature */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */; + return kind === 177 /* SyntaxKind.ConstructSignature */ + || kind === 176 /* SyntaxKind.CallSignature */ + || kind === 168 /* SyntaxKind.PropertySignature */ + || kind === 170 /* SyntaxKind.MethodSignature */ + || kind === 178 /* SyntaxKind.IndexSignature */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 175 /* SyntaxKind.SetAccessor */; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -13860,12 +13786,12 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 296 /* SyntaxKind.PropertyAssignment */ - || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ - || kind === 298 /* SyntaxKind.SpreadAssignment */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */; + return kind === 299 /* SyntaxKind.PropertyAssignment */ + || kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 301 /* SyntaxKind.SpreadAssignment */ + || kind === 171 /* SyntaxKind.MethodDeclaration */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 175 /* SyntaxKind.SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type @@ -13880,8 +13806,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: return true; } return false; @@ -13892,8 +13818,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 202 /* SyntaxKind.ArrayBindingPattern */ - || kind === 201 /* SyntaxKind.ObjectBindingPattern */; + return kind === 204 /* SyntaxKind.ArrayBindingPattern */ + || kind === 203 /* SyntaxKind.ObjectBindingPattern */; } return false; } @@ -13901,15 +13827,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 204 /* SyntaxKind.ArrayLiteralExpression */ - || kind === 205 /* SyntaxKind.ObjectLiteralExpression */; + return kind === 206 /* SyntaxKind.ArrayLiteralExpression */ + || kind === 207 /* SyntaxKind.ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 203 /* SyntaxKind.BindingElement */ - || kind === 227 /* SyntaxKind.OmittedExpression */; + return kind === 205 /* SyntaxKind.BindingElement */ + || kind === 229 /* SyntaxKind.OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -13918,9 +13844,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: - case 164 /* SyntaxKind.Parameter */: - case 203 /* SyntaxKind.BindingElement */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 166 /* SyntaxKind.Parameter */: + case 205 /* SyntaxKind.BindingElement */: return true; } return false; @@ -13941,8 +13867,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return true; } return false; @@ -13951,10 +13877,10 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentElement(node) { switch (node.kind) { - case 203 /* SyntaxKind.BindingElement */: - case 296 /* SyntaxKind.PropertyAssignment */: // AssignmentProperty - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: // AssignmentProperty - case 298 /* SyntaxKind.SpreadAssignment */: // AssignmentRestProperty + case 205 /* SyntaxKind.BindingElement */: + case 299 /* SyntaxKind.PropertyAssignment */: // AssignmentProperty + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: // AssignmentProperty + case 301 /* SyntaxKind.SpreadAssignment */: // AssignmentRestProperty return true; } return false; @@ -13966,8 +13892,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 202 /* SyntaxKind.ArrayBindingPattern */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 204 /* SyntaxKind.ArrayBindingPattern */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return true; } return false; @@ -13976,26 +13902,26 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 206 /* SyntaxKind.PropertyAccessExpression */ - || kind === 161 /* SyntaxKind.QualifiedName */ - || kind === 200 /* SyntaxKind.ImportType */; + return kind === 208 /* SyntaxKind.PropertyAccessExpression */ + || kind === 163 /* SyntaxKind.QualifiedName */ + || kind === 202 /* SyntaxKind.ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 206 /* SyntaxKind.PropertyAccessExpression */ - || kind === 161 /* SyntaxKind.QualifiedName */; + return kind === 208 /* SyntaxKind.PropertyAccessExpression */ + || kind === 163 /* SyntaxKind.QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 280 /* SyntaxKind.JsxOpeningElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: - case 210 /* SyntaxKind.TaggedTemplateExpression */: - case 165 /* SyntaxKind.Decorator */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: + case 167 /* SyntaxKind.Decorator */: return true; default: return false; @@ -14003,12 +13929,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 208 /* SyntaxKind.CallExpression */ || node.kind === 209 /* SyntaxKind.NewExpression */; + return node.kind === 210 /* SyntaxKind.CallExpression */ || node.kind === 211 /* SyntaxKind.NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 223 /* SyntaxKind.TemplateExpression */ + return kind === 225 /* SyntaxKind.TemplateExpression */ || kind === 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; @@ -14019,19 +13945,19 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: - case 209 /* SyntaxKind.NewExpression */: - case 208 /* SyntaxKind.CallExpression */: - case 278 /* SyntaxKind.JsxElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 282 /* SyntaxKind.JsxFragment */: - case 210 /* SyntaxKind.TaggedTemplateExpression */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: - case 212 /* SyntaxKind.ParenthesizedExpression */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 226 /* SyntaxKind.ClassExpression */: - case 213 /* SyntaxKind.FunctionExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: + case 211 /* SyntaxKind.NewExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 281 /* SyntaxKind.JsxElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: + case 285 /* SyntaxKind.JsxFragment */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 228 /* SyntaxKind.ClassExpression */: + case 215 /* SyntaxKind.FunctionExpression */: case 79 /* SyntaxKind.Identifier */: case 80 /* SyntaxKind.PrivateIdentifier */: // technically this is only an Expression if it's in a `#field in expr` BinaryExpression case 13 /* SyntaxKind.RegularExpressionLiteral */: @@ -14039,15 +13965,15 @@ var ts; case 9 /* SyntaxKind.BigIntLiteral */: case 10 /* SyntaxKind.StringLiteral */: case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: - case 223 /* SyntaxKind.TemplateExpression */: + case 225 /* SyntaxKind.TemplateExpression */: case 95 /* SyntaxKind.FalseKeyword */: case 104 /* SyntaxKind.NullKeyword */: case 108 /* SyntaxKind.ThisKeyword */: case 110 /* SyntaxKind.TrueKeyword */: case 106 /* SyntaxKind.SuperKeyword */: - case 230 /* SyntaxKind.NonNullExpression */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: - case 231 /* SyntaxKind.MetaProperty */: + case 232 /* SyntaxKind.NonNullExpression */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: + case 233 /* SyntaxKind.MetaProperty */: case 100 /* SyntaxKind.ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: @@ -14061,13 +13987,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 220 /* SyntaxKind.PostfixUnaryExpression */: - case 215 /* SyntaxKind.DeleteExpression */: - case 216 /* SyntaxKind.TypeOfExpression */: - case 217 /* SyntaxKind.VoidExpression */: - case 218 /* SyntaxKind.AwaitExpression */: - case 211 /* SyntaxKind.TypeAssertionExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: + case 217 /* SyntaxKind.DeleteExpression */: + case 218 /* SyntaxKind.TypeOfExpression */: + case 219 /* SyntaxKind.VoidExpression */: + case 220 /* SyntaxKind.AwaitExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -14076,9 +14002,9 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: return true; - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: return expr.operator === 45 /* SyntaxKind.PlusPlusToken */ || expr.operator === 46 /* SyntaxKind.MinusMinusToken */; default: @@ -14097,15 +14023,16 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 222 /* SyntaxKind.ConditionalExpression */: - case 224 /* SyntaxKind.YieldExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 221 /* SyntaxKind.BinaryExpression */: - case 225 /* SyntaxKind.SpreadElement */: - case 229 /* SyntaxKind.AsExpression */: - case 227 /* SyntaxKind.OmittedExpression */: - case 351 /* SyntaxKind.CommaListExpression */: - case 350 /* SyntaxKind.PartiallyEmittedExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: + case 226 /* SyntaxKind.YieldExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 223 /* SyntaxKind.BinaryExpression */: + case 227 /* SyntaxKind.SpreadElement */: + case 231 /* SyntaxKind.AsExpression */: + case 229 /* SyntaxKind.OmittedExpression */: + case 354 /* SyntaxKind.CommaListExpression */: + case 353 /* SyntaxKind.PartiallyEmittedExpression */: + case 235 /* SyntaxKind.SatisfiesExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -14113,8 +14040,8 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 211 /* SyntaxKind.TypeAssertionExpression */ - || kind === 229 /* SyntaxKind.AsExpression */; + return kind === 213 /* SyntaxKind.TypeAssertionExpression */ + || kind === 231 /* SyntaxKind.AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ @@ -14125,13 +14052,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: return true; - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -14160,7 +14087,7 @@ var ts; ts.isExternalModuleIndicator = isExternalModuleIndicator; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 243 /* SyntaxKind.ForInStatement */ || node.kind === 244 /* SyntaxKind.ForOfStatement */; + return node.kind === 246 /* SyntaxKind.ForInStatement */ || node.kind === 247 /* SyntaxKind.ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -14184,115 +14111,115 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 262 /* SyntaxKind.ModuleBlock */ - || kind === 261 /* SyntaxKind.ModuleDeclaration */ + return kind === 265 /* SyntaxKind.ModuleBlock */ + || kind === 264 /* SyntaxKind.ModuleDeclaration */ || kind === 79 /* SyntaxKind.Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 262 /* SyntaxKind.ModuleBlock */ - || kind === 261 /* SyntaxKind.ModuleDeclaration */; + return kind === 265 /* SyntaxKind.ModuleBlock */ + || kind === 264 /* SyntaxKind.ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 79 /* SyntaxKind.Identifier */ - || kind === 261 /* SyntaxKind.ModuleDeclaration */; + || kind === 264 /* SyntaxKind.ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 269 /* SyntaxKind.NamedImports */ - || kind === 268 /* SyntaxKind.NamespaceImport */; + return kind === 272 /* SyntaxKind.NamedImports */ + || kind === 271 /* SyntaxKind.NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 261 /* SyntaxKind.ModuleDeclaration */ || node.kind === 260 /* SyntaxKind.EnumDeclaration */; + return node.kind === 264 /* SyntaxKind.ModuleDeclaration */ || node.kind === 263 /* SyntaxKind.EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 214 /* SyntaxKind.ArrowFunction */ - || kind === 203 /* SyntaxKind.BindingElement */ - || kind === 257 /* SyntaxKind.ClassDeclaration */ - || kind === 226 /* SyntaxKind.ClassExpression */ - || kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ - || kind === 260 /* SyntaxKind.EnumDeclaration */ - || kind === 299 /* SyntaxKind.EnumMember */ - || kind === 275 /* SyntaxKind.ExportSpecifier */ - || kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 213 /* SyntaxKind.FunctionExpression */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 267 /* SyntaxKind.ImportClause */ - || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ - || kind === 270 /* SyntaxKind.ImportSpecifier */ - || kind === 258 /* SyntaxKind.InterfaceDeclaration */ - || kind === 285 /* SyntaxKind.JsxAttribute */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 168 /* SyntaxKind.MethodSignature */ - || kind === 261 /* SyntaxKind.ModuleDeclaration */ - || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ - || kind === 268 /* SyntaxKind.NamespaceImport */ - || kind === 274 /* SyntaxKind.NamespaceExport */ - || kind === 164 /* SyntaxKind.Parameter */ - || kind === 296 /* SyntaxKind.PropertyAssignment */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */ - || kind === 166 /* SyntaxKind.PropertySignature */ - || kind === 173 /* SyntaxKind.SetAccessor */ - || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ - || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ - || kind === 163 /* SyntaxKind.TypeParameter */ - || kind === 254 /* SyntaxKind.VariableDeclaration */ - || kind === 345 /* SyntaxKind.JSDocTypedefTag */ - || kind === 338 /* SyntaxKind.JSDocCallbackTag */ - || kind === 347 /* SyntaxKind.JSDocPropertyTag */; + return kind === 216 /* SyntaxKind.ArrowFunction */ + || kind === 205 /* SyntaxKind.BindingElement */ + || kind === 260 /* SyntaxKind.ClassDeclaration */ + || kind === 228 /* SyntaxKind.ClassExpression */ + || kind === 172 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 173 /* SyntaxKind.Constructor */ + || kind === 263 /* SyntaxKind.EnumDeclaration */ + || kind === 302 /* SyntaxKind.EnumMember */ + || kind === 278 /* SyntaxKind.ExportSpecifier */ + || kind === 259 /* SyntaxKind.FunctionDeclaration */ + || kind === 215 /* SyntaxKind.FunctionExpression */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 270 /* SyntaxKind.ImportClause */ + || kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ + || kind === 273 /* SyntaxKind.ImportSpecifier */ + || kind === 261 /* SyntaxKind.InterfaceDeclaration */ + || kind === 288 /* SyntaxKind.JsxAttribute */ + || kind === 171 /* SyntaxKind.MethodDeclaration */ + || kind === 170 /* SyntaxKind.MethodSignature */ + || kind === 264 /* SyntaxKind.ModuleDeclaration */ + || kind === 267 /* SyntaxKind.NamespaceExportDeclaration */ + || kind === 271 /* SyntaxKind.NamespaceImport */ + || kind === 277 /* SyntaxKind.NamespaceExport */ + || kind === 166 /* SyntaxKind.Parameter */ + || kind === 299 /* SyntaxKind.PropertyAssignment */ + || kind === 169 /* SyntaxKind.PropertyDeclaration */ + || kind === 168 /* SyntaxKind.PropertySignature */ + || kind === 175 /* SyntaxKind.SetAccessor */ + || kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 262 /* SyntaxKind.TypeAliasDeclaration */ + || kind === 165 /* SyntaxKind.TypeParameter */ + || kind === 257 /* SyntaxKind.VariableDeclaration */ + || kind === 348 /* SyntaxKind.JSDocTypedefTag */ + || kind === 341 /* SyntaxKind.JSDocCallbackTag */ + || kind === 350 /* SyntaxKind.JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 276 /* SyntaxKind.MissingDeclaration */ - || kind === 257 /* SyntaxKind.ClassDeclaration */ - || kind === 258 /* SyntaxKind.InterfaceDeclaration */ - || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ - || kind === 260 /* SyntaxKind.EnumDeclaration */ - || kind === 261 /* SyntaxKind.ModuleDeclaration */ - || kind === 266 /* SyntaxKind.ImportDeclaration */ - || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ - || kind === 272 /* SyntaxKind.ExportDeclaration */ - || kind === 271 /* SyntaxKind.ExportAssignment */ - || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */; + return kind === 259 /* SyntaxKind.FunctionDeclaration */ + || kind === 279 /* SyntaxKind.MissingDeclaration */ + || kind === 260 /* SyntaxKind.ClassDeclaration */ + || kind === 261 /* SyntaxKind.InterfaceDeclaration */ + || kind === 262 /* SyntaxKind.TypeAliasDeclaration */ + || kind === 263 /* SyntaxKind.EnumDeclaration */ + || kind === 264 /* SyntaxKind.ModuleDeclaration */ + || kind === 269 /* SyntaxKind.ImportDeclaration */ + || kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ + || kind === 275 /* SyntaxKind.ExportDeclaration */ + || kind === 274 /* SyntaxKind.ExportAssignment */ + || kind === 267 /* SyntaxKind.NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 246 /* SyntaxKind.BreakStatement */ - || kind === 245 /* SyntaxKind.ContinueStatement */ - || kind === 253 /* SyntaxKind.DebuggerStatement */ - || kind === 240 /* SyntaxKind.DoStatement */ - || kind === 238 /* SyntaxKind.ExpressionStatement */ - || kind === 236 /* SyntaxKind.EmptyStatement */ - || kind === 243 /* SyntaxKind.ForInStatement */ - || kind === 244 /* SyntaxKind.ForOfStatement */ - || kind === 242 /* SyntaxKind.ForStatement */ - || kind === 239 /* SyntaxKind.IfStatement */ - || kind === 250 /* SyntaxKind.LabeledStatement */ - || kind === 247 /* SyntaxKind.ReturnStatement */ - || kind === 249 /* SyntaxKind.SwitchStatement */ - || kind === 251 /* SyntaxKind.ThrowStatement */ - || kind === 252 /* SyntaxKind.TryStatement */ - || kind === 237 /* SyntaxKind.VariableStatement */ - || kind === 241 /* SyntaxKind.WhileStatement */ - || kind === 248 /* SyntaxKind.WithStatement */ - || kind === 349 /* SyntaxKind.NotEmittedStatement */ - || kind === 353 /* SyntaxKind.EndOfDeclarationMarker */ - || kind === 352 /* SyntaxKind.MergeDeclarationMarker */; + return kind === 249 /* SyntaxKind.BreakStatement */ + || kind === 248 /* SyntaxKind.ContinueStatement */ + || kind === 256 /* SyntaxKind.DebuggerStatement */ + || kind === 243 /* SyntaxKind.DoStatement */ + || kind === 241 /* SyntaxKind.ExpressionStatement */ + || kind === 239 /* SyntaxKind.EmptyStatement */ + || kind === 246 /* SyntaxKind.ForInStatement */ + || kind === 247 /* SyntaxKind.ForOfStatement */ + || kind === 245 /* SyntaxKind.ForStatement */ + || kind === 242 /* SyntaxKind.IfStatement */ + || kind === 253 /* SyntaxKind.LabeledStatement */ + || kind === 250 /* SyntaxKind.ReturnStatement */ + || kind === 252 /* SyntaxKind.SwitchStatement */ + || kind === 254 /* SyntaxKind.ThrowStatement */ + || kind === 255 /* SyntaxKind.TryStatement */ + || kind === 240 /* SyntaxKind.VariableStatement */ + || kind === 244 /* SyntaxKind.WhileStatement */ + || kind === 251 /* SyntaxKind.WithStatement */ + || kind === 352 /* SyntaxKind.NotEmittedStatement */ + || kind === 356 /* SyntaxKind.EndOfDeclarationMarker */ + || kind === 355 /* SyntaxKind.MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 163 /* SyntaxKind.TypeParameter */) { - return (node.parent && node.parent.kind !== 344 /* SyntaxKind.JSDocTemplateTag */) || ts.isInJSFile(node); + if (node.kind === 165 /* SyntaxKind.TypeParameter */) { + return (node.parent && node.parent.kind !== 347 /* SyntaxKind.JSDocTemplateTag */) || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14319,10 +14246,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 235 /* SyntaxKind.Block */) + if (node.kind !== 238 /* SyntaxKind.Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 252 /* SyntaxKind.TryStatement */ || node.parent.kind === 292 /* SyntaxKind.CatchClause */) { + if (node.parent.kind === 255 /* SyntaxKind.TryStatement */ || node.parent.kind === 295 /* SyntaxKind.CatchClause */) { return false; } } @@ -14336,15 +14263,15 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 235 /* SyntaxKind.Block */; + || kind === 238 /* SyntaxKind.Block */; } ts.isStatementOrBlock = isStatementOrBlock; // Module references /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 277 /* SyntaxKind.ExternalModuleReference */ - || kind === 161 /* SyntaxKind.QualifiedName */ + return kind === 280 /* SyntaxKind.ExternalModuleReference */ + || kind === 163 /* SyntaxKind.QualifiedName */ || kind === 79 /* SyntaxKind.Identifier */; } ts.isModuleReference = isModuleReference; @@ -14354,58 +14281,58 @@ var ts; var kind = node.kind; return kind === 108 /* SyntaxKind.ThisKeyword */ || kind === 79 /* SyntaxKind.Identifier */ - || kind === 206 /* SyntaxKind.PropertyAccessExpression */; + || kind === 208 /* SyntaxKind.PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 278 /* SyntaxKind.JsxElement */ - || kind === 288 /* SyntaxKind.JsxExpression */ - || kind === 279 /* SyntaxKind.JsxSelfClosingElement */ + return kind === 281 /* SyntaxKind.JsxElement */ + || kind === 291 /* SyntaxKind.JsxExpression */ + || kind === 282 /* SyntaxKind.JsxSelfClosingElement */ || kind === 11 /* SyntaxKind.JsxText */ - || kind === 282 /* SyntaxKind.JsxFragment */; + || kind === 285 /* SyntaxKind.JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 285 /* SyntaxKind.JsxAttribute */ - || kind === 287 /* SyntaxKind.JsxSpreadAttribute */; + return kind === 288 /* SyntaxKind.JsxAttribute */ + || kind === 290 /* SyntaxKind.JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 10 /* SyntaxKind.StringLiteral */ - || kind === 288 /* SyntaxKind.JsxExpression */; + || kind === 291 /* SyntaxKind.JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 280 /* SyntaxKind.JsxOpeningElement */ - || kind === 279 /* SyntaxKind.JsxSelfClosingElement */; + return kind === 283 /* SyntaxKind.JsxOpeningElement */ + || kind === 282 /* SyntaxKind.JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 289 /* SyntaxKind.CaseClause */ - || kind === 290 /* SyntaxKind.DefaultClause */; + return kind === 292 /* SyntaxKind.CaseClause */ + || kind === 293 /* SyntaxKind.DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 309 /* SyntaxKind.FirstJSDocNode */ && node.kind <= 347 /* SyntaxKind.LastJSDocNode */; + return node.kind >= 312 /* SyntaxKind.FirstJSDocNode */ && node.kind <= 350 /* SyntaxKind.LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 320 /* SyntaxKind.JSDoc */ - || node.kind === 319 /* SyntaxKind.JSDocNamepathType */ - || node.kind === 321 /* SyntaxKind.JSDocText */ + return node.kind === 323 /* SyntaxKind.JSDoc */ + || node.kind === 322 /* SyntaxKind.JSDocNamepathType */ + || node.kind === 324 /* SyntaxKind.JSDocText */ || isJSDocLinkLike(node) || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) @@ -14415,15 +14342,15 @@ var ts; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 327 /* SyntaxKind.FirstJSDocTagNode */ && node.kind <= 347 /* SyntaxKind.LastJSDocTagNode */; + return node.kind >= 330 /* SyntaxKind.FirstJSDocTagNode */ && node.kind <= 350 /* SyntaxKind.LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 173 /* SyntaxKind.SetAccessor */; + return node.kind === 175 /* SyntaxKind.SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 172 /* SyntaxKind.GetAccessor */; + return node.kind === 174 /* SyntaxKind.GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ @@ -14449,12 +14376,12 @@ var ts; /** True if has initializer node attached to it. */ function hasOnlyExpressionInitializer(node) { switch (node.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: - case 164 /* SyntaxKind.Parameter */: - case 203 /* SyntaxKind.BindingElement */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 299 /* SyntaxKind.EnumMember */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 166 /* SyntaxKind.Parameter */: + case 205 /* SyntaxKind.BindingElement */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 302 /* SyntaxKind.EnumMember */: return true; default: return false; @@ -14462,12 +14389,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 285 /* SyntaxKind.JsxAttribute */ || node.kind === 287 /* SyntaxKind.JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 288 /* SyntaxKind.JsxAttribute */ || node.kind === 290 /* SyntaxKind.JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 178 /* SyntaxKind.TypeReference */ || node.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */; + return node.kind === 180 /* SyntaxKind.TypeReference */ || node.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -14500,7 +14427,7 @@ var ts; } ts.isStringLiteralLike = isStringLiteralLike; function isJSDocLinkLike(node) { - return node.kind === 324 /* SyntaxKind.JSDocLink */ || node.kind === 325 /* SyntaxKind.JSDocLinkCode */ || node.kind === 326 /* SyntaxKind.JSDocLinkPlain */; + return node.kind === 327 /* SyntaxKind.JSDocLink */ || node.kind === 328 /* SyntaxKind.JSDocLinkCode */ || node.kind === 329 /* SyntaxKind.JSDocLinkPlain */; } ts.isJSDocLinkLike = isJSDocLinkLike; function hasRestParameter(s) { @@ -14510,7 +14437,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 321 /* SyntaxKind.JSDocVariadicType */; } ts.isRestParameter = isRestParameter; // #endregion @@ -14768,7 +14695,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 305 /* SyntaxKind.SourceFile */) { + while (node && node.kind !== 308 /* SyntaxKind.SourceFile */) { node = node.parent; } return node; @@ -14784,11 +14711,11 @@ var ts; ts.isPlainJsFile = isPlainJsFile; function isStatementWithLocals(node) { switch (node.kind) { - case 235 /* SyntaxKind.Block */: - case 263 /* SyntaxKind.CaseBlock */: - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: + case 238 /* SyntaxKind.Block */: + case 266 /* SyntaxKind.CaseBlock */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return true; } return false; @@ -14984,7 +14911,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 348 /* SyntaxKind.SyntaxList */ && node._children.length > 0) { + if (node.kind === 351 /* SyntaxKind.SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, @@ -15049,7 +14976,6 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - ; function getScriptTargetFeatures() { return { es2015: { @@ -15222,7 +15148,7 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 254 /* SyntaxKind.VariableDeclaration */ && node.parent.kind === 292 /* SyntaxKind.CatchClause */; + return node.kind === 257 /* SyntaxKind.VariableDeclaration */ && node.parent.kind === 295 /* SyntaxKind.CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { @@ -15254,11 +15180,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return !!node && node.kind === 261 /* SyntaxKind.ModuleDeclaration */ && (!node.body); + return !!node && node.kind === 264 /* SyntaxKind.ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 305 /* SyntaxKind.SourceFile */ || - node.kind === 261 /* SyntaxKind.ModuleDeclaration */ || + return node.kind === 308 /* SyntaxKind.SourceFile */ || + node.kind === 264 /* SyntaxKind.ModuleDeclaration */ || ts.isFunctionLikeOrClassStaticBlockDeclaration(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -15275,9 +15201,9 @@ var ts; // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module switch (node.parent.kind) { - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: return ts.isExternalModule(node.parent); - case 262 /* SyntaxKind.ModuleBlock */: + case 265 /* SyntaxKind.ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; @@ -15332,26 +15258,30 @@ var ts; return false; } ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile; + function isAmbientPropertyDeclaration(node) { + return !!(node.flags & 16777216 /* NodeFlags.Ambient */) || hasSyntacticModifier(node, 2 /* ModifierFlags.Ambient */); + } + ts.isAmbientPropertyDeclaration = isAmbientPropertyDeclaration; function isBlockScope(node, parentNode) { switch (node.kind) { - case 305 /* SyntaxKind.SourceFile */: - case 263 /* SyntaxKind.CaseBlock */: - case 292 /* SyntaxKind.CatchClause */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 171 /* SyntaxKind.Constructor */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 308 /* SyntaxKind.SourceFile */: + case 266 /* SyntaxKind.CaseBlock */: + case 295 /* SyntaxKind.CatchClause */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 173 /* SyntaxKind.Constructor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: return true; - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLikeOrClassStaticBlockDeclaration(parentNode); @@ -15361,9 +15291,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 323 /* SyntaxKind.JSDocSignature */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 326 /* SyntaxKind.JSDocSignature */: return true; default: ts.assertType(node); @@ -15373,25 +15303,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 168 /* SyntaxKind.MethodSignature */: - case 176 /* SyntaxKind.IndexSignature */: - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 344 /* SyntaxKind.JSDocTemplateTag */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 170 /* SyntaxKind.MethodSignature */: + case 178 /* SyntaxKind.IndexSignature */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: + case 320 /* SyntaxKind.JSDocFunctionType */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 347 /* SyntaxKind.JSDocTemplateTag */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: return true; default: ts.assertType(node); @@ -15401,8 +15331,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return true; default: return false; @@ -15415,15 +15345,15 @@ var ts; ts.isAnyImportOrBareOrAccessedRequire = isAnyImportOrBareOrAccessedRequire; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 237 /* SyntaxKind.VariableStatement */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 240 /* SyntaxKind.VariableStatement */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return true; default: return false; @@ -15464,19 +15394,19 @@ var ts; } ts.getNameFromIndexInfo = getNameFromIndexInfo; function isComputedNonLiteralName(name) { - return name.kind === 162 /* SyntaxKind.ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + return name.kind === 164 /* SyntaxKind.ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); } ts.isComputedNonLiteralName = isComputedNonLiteralName; function tryGetTextOfPropertyName(name) { switch (name.kind) { case 79 /* SyntaxKind.Identifier */: case 80 /* SyntaxKind.PrivateIdentifier */: - return name.escapedText; + return name.autoGenerateFlags ? undefined : name.escapedText; case 10 /* SyntaxKind.StringLiteral */: case 8 /* SyntaxKind.NumericLiteral */: case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: if (isStringOrNumericLiteralLike(name.expression)) return ts.escapeLeadingUnderscores(name.expression.text); return undefined; @@ -15496,16 +15426,16 @@ var ts; case 80 /* SyntaxKind.PrivateIdentifier */: case 79 /* SyntaxKind.Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) { return entityNameToString(name.expression) + "." + entityNameToString(name.name); } else { return ts.Debug.assertNever(name.name); } - case 311 /* SyntaxKind.JSDocMemberName */: + case 314 /* SyntaxKind.JSDocMemberName */: return entityNameToString(name.left) + entityNameToString(name.right); default: return ts.Debug.assertNever(name); @@ -15595,7 +15525,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 235 /* SyntaxKind.Block */) { + if (node.body && node.body.kind === 238 /* SyntaxKind.Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -15609,7 +15539,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -15618,29 +15548,29 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 254 /* SyntaxKind.VariableDeclaration */: - case 203 /* SyntaxKind.BindingElement */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 299 /* SyntaxKind.EnumMember */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 268 /* SyntaxKind.NamespaceImport */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 205 /* SyntaxKind.BindingElement */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 302 /* SyntaxKind.EnumMember */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 271 /* SyntaxKind.NamespaceImport */: errorNode = node.name; break; - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: var start = ts.skipTrivia(sourceFile.text, node.pos); var end = node.statements.length > 0 ? node.statements[0].pos : node.end; return ts.createTextSpanFromBounds(start, end); @@ -15692,11 +15622,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 208 /* SyntaxKind.CallExpression */ && n.expression.kind === 106 /* SyntaxKind.SuperKeyword */; + return n.kind === 210 /* SyntaxKind.CallExpression */ && n.expression.kind === 106 /* SyntaxKind.SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 208 /* SyntaxKind.CallExpression */ && n.expression.kind === 100 /* SyntaxKind.ImportKeyword */; + return n.kind === 210 /* SyntaxKind.CallExpression */ && n.expression.kind === 100 /* SyntaxKind.ImportKeyword */; } ts.isImportCall = isImportCall; function isImportMeta(n) { @@ -15710,7 +15640,7 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 238 /* SyntaxKind.ExpressionStatement */ + return node.kind === 241 /* SyntaxKind.ExpressionStatement */ && node.expression.kind === 10 /* SyntaxKind.StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; @@ -15738,13 +15668,13 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 164 /* SyntaxKind.Parameter */ || - node.kind === 163 /* SyntaxKind.TypeParameter */ || - node.kind === 213 /* SyntaxKind.FunctionExpression */ || - node.kind === 214 /* SyntaxKind.ArrowFunction */ || - node.kind === 212 /* SyntaxKind.ParenthesizedExpression */ || - node.kind === 254 /* SyntaxKind.VariableDeclaration */ || - node.kind === 275 /* SyntaxKind.ExportSpecifier */) ? + var commentRanges = (node.kind === 166 /* SyntaxKind.Parameter */ || + node.kind === 165 /* SyntaxKind.TypeParameter */ || + node.kind === 215 /* SyntaxKind.FunctionExpression */ || + node.kind === 216 /* SyntaxKind.ArrowFunction */ || + node.kind === 214 /* SyntaxKind.ParenthesizedExpression */ || + node.kind === 257 /* SyntaxKind.VariableDeclaration */ || + node.kind === 278 /* SyntaxKind.ExportSpecifier */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -15760,48 +15690,48 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (177 /* SyntaxKind.FirstTypeNode */ <= node.kind && node.kind <= 200 /* SyntaxKind.LastTypeNode */) { + if (179 /* SyntaxKind.FirstTypeNode */ <= node.kind && node.kind <= 202 /* SyntaxKind.LastTypeNode */) { return true; } switch (node.kind) { - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 147 /* SyntaxKind.NumberKeyword */: - case 158 /* SyntaxKind.BigIntKeyword */: - case 150 /* SyntaxKind.StringKeyword */: - case 133 /* SyntaxKind.BooleanKeyword */: - case 151 /* SyntaxKind.SymbolKeyword */: - case 148 /* SyntaxKind.ObjectKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: + case 131 /* SyntaxKind.AnyKeyword */: + case 157 /* SyntaxKind.UnknownKeyword */: + case 148 /* SyntaxKind.NumberKeyword */: + case 160 /* SyntaxKind.BigIntKeyword */: + case 152 /* SyntaxKind.StringKeyword */: + case 134 /* SyntaxKind.BooleanKeyword */: + case 153 /* SyntaxKind.SymbolKeyword */: + case 149 /* SyntaxKind.ObjectKeyword */: + case 155 /* SyntaxKind.UndefinedKeyword */: + case 144 /* SyntaxKind.NeverKeyword */: return true; case 114 /* SyntaxKind.VoidKeyword */: - return node.parent.kind !== 217 /* SyntaxKind.VoidExpression */; - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + return node.parent.kind !== 219 /* SyntaxKind.VoidExpression */; + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return ts.isHeritageClause(node.parent) && !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 163 /* SyntaxKind.TypeParameter */: - return node.parent.kind === 195 /* SyntaxKind.MappedType */ || node.parent.kind === 190 /* SyntaxKind.InferType */; + case 165 /* SyntaxKind.TypeParameter */: + return node.parent.kind === 197 /* SyntaxKind.MappedType */ || node.parent.kind === 192 /* SyntaxKind.InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container case 79 /* SyntaxKind.Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 161 /* SyntaxKind.QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 163 /* SyntaxKind.QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 79 /* SyntaxKind.Identifier */ || node.kind === 161 /* SyntaxKind.QualifiedName */ || node.kind === 206 /* SyntaxKind.PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 79 /* SyntaxKind.Identifier */ || node.kind === 163 /* SyntaxKind.QualifiedName */ || node.kind === 208 /* SyntaxKind.PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 161 /* SyntaxKind.QualifiedName */: - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 163 /* SyntaxKind.QualifiedName */: + case 208 /* SyntaxKind.PropertyAccessExpression */: case 108 /* SyntaxKind.ThisKeyword */: { var parent = node.parent; - if (parent.kind === 181 /* SyntaxKind.TypeQuery */) { + if (parent.kind === 183 /* SyntaxKind.TypeQuery */) { return false; } - if (parent.kind === 200 /* SyntaxKind.ImportType */) { + if (parent.kind === 202 /* SyntaxKind.ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -15810,40 +15740,40 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (177 /* SyntaxKind.FirstTypeNode */ <= parent.kind && parent.kind <= 200 /* SyntaxKind.LastTypeNode */) { + if (179 /* SyntaxKind.FirstTypeNode */ <= parent.kind && parent.kind <= 202 /* SyntaxKind.LastTypeNode */) { return true; } switch (parent.kind) { - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return ts.isHeritageClause(parent.parent) && !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 163 /* SyntaxKind.TypeParameter */: + case 165 /* SyntaxKind.TypeParameter */: return node === parent.constraint; - case 344 /* SyntaxKind.JSDocTemplateTag */: + case 347 /* SyntaxKind.JSDocTemplateTag */: return node === parent.constraint; - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 164 /* SyntaxKind.Parameter */: - case 254 /* SyntaxKind.VariableDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 166 /* SyntaxKind.Parameter */: + case 257 /* SyntaxKind.VariableDeclaration */: return node === parent.type; - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 171 /* SyntaxKind.Constructor */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 173 /* SyntaxKind.Constructor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return node === parent.type; - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 176 /* SyntaxKind.IndexSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 178 /* SyntaxKind.IndexSignature */: return node === parent.type; - case 211 /* SyntaxKind.TypeAssertionExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: return node === parent.type; - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: return ts.contains(parent.typeArguments, node); - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -15868,23 +15798,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 247 /* SyntaxKind.ReturnStatement */: + case 250 /* SyntaxKind.ReturnStatement */: return visitor(node); - case 263 /* SyntaxKind.CaseBlock */: - case 235 /* SyntaxKind.Block */: - case 239 /* SyntaxKind.IfStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 248 /* SyntaxKind.WithStatement */: - case 249 /* SyntaxKind.SwitchStatement */: - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: - case 250 /* SyntaxKind.LabeledStatement */: - case 252 /* SyntaxKind.TryStatement */: - case 292 /* SyntaxKind.CatchClause */: + case 266 /* SyntaxKind.CaseBlock */: + case 238 /* SyntaxKind.Block */: + case 242 /* SyntaxKind.IfStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 251 /* SyntaxKind.WithStatement */: + case 252 /* SyntaxKind.SwitchStatement */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: + case 253 /* SyntaxKind.LabeledStatement */: + case 255 /* SyntaxKind.TryStatement */: + case 295 /* SyntaxKind.CatchClause */: return ts.forEachChild(node, traverse); } } @@ -15894,23 +15824,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 224 /* SyntaxKind.YieldExpression */: + case 226 /* SyntaxKind.YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 260 /* SyntaxKind.EnumDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, skip them to avoid the work. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (node.name && node.name.kind === 164 /* SyntaxKind.ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(node.name.expression); @@ -15933,10 +15863,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 183 /* SyntaxKind.ArrayType */) { + if (node && node.kind === 185 /* SyntaxKind.ArrayType */) { return node.elementType; } - else if (node && node.kind === 178 /* SyntaxKind.TypeReference */) { + else if (node && node.kind === 180 /* SyntaxKind.TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -15946,12 +15876,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 182 /* SyntaxKind.TypeLiteral */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 184 /* SyntaxKind.TypeLiteral */: return node.members; - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return node.properties; } } @@ -15959,14 +15889,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 203 /* SyntaxKind.BindingElement */: - case 299 /* SyntaxKind.EnumMember */: - case 164 /* SyntaxKind.Parameter */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 254 /* SyntaxKind.VariableDeclaration */: + case 205 /* SyntaxKind.BindingElement */: + case 302 /* SyntaxKind.EnumMember */: + case 166 /* SyntaxKind.Parameter */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 257 /* SyntaxKind.VariableDeclaration */: return true; } } @@ -15978,8 +15908,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 255 /* SyntaxKind.VariableDeclarationList */ - && node.parent.parent.kind === 237 /* SyntaxKind.VariableStatement */; + return node.parent.kind === 258 /* SyntaxKind.VariableDeclarationList */ + && node.parent.parent.kind === 240 /* SyntaxKind.VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isCommonJsExportedExpression(node) { @@ -16003,13 +15933,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: return true; } return false; @@ -16020,7 +15950,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 250 /* SyntaxKind.LabeledStatement */) { + if (node.statement.kind !== 253 /* SyntaxKind.LabeledStatement */) { return node.statement; } node = node.statement; @@ -16028,17 +15958,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 235 /* SyntaxKind.Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 238 /* SyntaxKind.Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 169 /* SyntaxKind.MethodDeclaration */ && node.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */; + return node && node.kind === 171 /* SyntaxKind.MethodDeclaration */ && node.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethodOrAccessor(node) { - return (node.kind === 169 /* SyntaxKind.MethodDeclaration */ || node.kind === 172 /* SyntaxKind.GetAccessor */ || node.kind === 173 /* SyntaxKind.SetAccessor */) && - (node.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */ || - node.parent.kind === 226 /* SyntaxKind.ClassExpression */); + return (node.kind === 171 /* SyntaxKind.MethodDeclaration */ || node.kind === 174 /* SyntaxKind.GetAccessor */ || node.kind === 175 /* SyntaxKind.SetAccessor */) && + (node.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */ || + node.parent.kind === 228 /* SyntaxKind.ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethodOrAccessor = isObjectLiteralOrClassExpressionMethodOrAccessor; function isIdentifierTypePredicate(predicate) { @@ -16051,7 +15981,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 296 /* SyntaxKind.PropertyAssignment */) { + if (property.kind === 299 /* SyntaxKind.PropertyAssignment */) { var propName = tryGetTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -16113,14 +16043,14 @@ var ts; } ts.getContainingFunctionOrClassStaticBlock = getContainingFunctionOrClassStaticBlock; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 305 /* SyntaxKind.SourceFile */); + ts.Debug.assert(node.kind !== 308 /* SyntaxKind.SourceFile */); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -16135,9 +16065,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 165 /* SyntaxKind.Decorator */: + case 167 /* SyntaxKind.Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 164 /* SyntaxKind.Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 166 /* SyntaxKind.Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -16148,27 +16078,27 @@ var ts; node = node.parent; } break; - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 176 /* SyntaxKind.IndexSignature */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 305 /* SyntaxKind.SourceFile */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 178 /* SyntaxKind.IndexSignature */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 308 /* SyntaxKind.SourceFile */: return node; } } @@ -16181,17 +16111,17 @@ var ts; switch (node.kind) { // Arrow functions use the same scope, but may do so in a "delayed" manner // For example, `const getThis = () => this` may be before a super() call in a derived constructor - case 214 /* SyntaxKind.ArrowFunction */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 167 /* SyntaxKind.PropertyDeclaration */: + case 216 /* SyntaxKind.ArrowFunction */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 169 /* SyntaxKind.PropertyDeclaration */: return true; - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: switch (node.parent.kind) { - case 171 /* SyntaxKind.Constructor */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 173 /* SyntaxKind.Constructor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: // Object properties can have computed names; only method-like bodies start a new scope return true; default: @@ -16215,9 +16145,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 171 /* SyntaxKind.Constructor */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: + case 173 /* SyntaxKind.Constructor */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: return container; } } @@ -16239,28 +16169,28 @@ var ts; return node; } switch (node.kind) { - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: node = node.parent; break; - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: return node; - case 165 /* SyntaxKind.Decorator */: + case 167 /* SyntaxKind.Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 164 /* SyntaxKind.Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 166 /* SyntaxKind.Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -16276,14 +16206,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 213 /* SyntaxKind.FunctionExpression */ || func.kind === 214 /* SyntaxKind.ArrowFunction */) { + if (func.kind === 215 /* SyntaxKind.FunctionExpression */ || func.kind === 216 /* SyntaxKind.ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */) { + while (parent.kind === 214 /* SyntaxKind.ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 208 /* SyntaxKind.CallExpression */ && parent.expression === prev) { + if (parent.kind === 210 /* SyntaxKind.CallExpression */ && parent.expression === prev) { return parent; } } @@ -16299,7 +16229,7 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 206 /* SyntaxKind.PropertyAccessExpression */ || kind === 207 /* SyntaxKind.ElementAccessExpression */) + return (kind === 208 /* SyntaxKind.PropertyAccessExpression */ || kind === 209 /* SyntaxKind.ElementAccessExpression */) && node.expression.kind === 106 /* SyntaxKind.SuperKeyword */; } ts.isSuperProperty = isSuperProperty; @@ -16308,7 +16238,7 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 206 /* SyntaxKind.PropertyAccessExpression */ || kind === 207 /* SyntaxKind.ElementAccessExpression */) + return (kind === 208 /* SyntaxKind.PropertyAccessExpression */ || kind === 209 /* SyntaxKind.ElementAccessExpression */) && node.expression.kind === 108 /* SyntaxKind.ThisKeyword */; } ts.isThisProperty = isThisProperty; @@ -16327,15 +16257,15 @@ var ts; ts.isThisInitializedObjectBindingExpression = isThisInitializedObjectBindingExpression; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return node.typeName; - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 79 /* SyntaxKind.Identifier */: - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: return node; } return undefined; @@ -16343,10 +16273,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: return node.tag; - case 280 /* SyntaxKind.JsxOpeningElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -16359,25 +16289,25 @@ var ts; return false; } switch (node.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: // classes are valid targets return true; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 257 /* SyntaxKind.ClassDeclaration */; - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 169 /* SyntaxKind.MethodDeclaration */: + return parent.kind === 260 /* SyntaxKind.ClassDeclaration */; + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 257 /* SyntaxKind.ClassDeclaration */; - case 164 /* SyntaxKind.Parameter */: + && parent.kind === 260 /* SyntaxKind.ClassDeclaration */; + case 166 /* SyntaxKind.Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 171 /* SyntaxKind.Constructor */ - || parent.kind === 169 /* SyntaxKind.MethodDeclaration */ - || parent.kind === 173 /* SyntaxKind.SetAccessor */) - && grandparent.kind === 257 /* SyntaxKind.ClassDeclaration */; + && (parent.kind === 173 /* SyntaxKind.Constructor */ + || parent.kind === 171 /* SyntaxKind.MethodDeclaration */ + || parent.kind === 175 /* SyntaxKind.SetAccessor */) + && grandparent.kind === 260 /* SyntaxKind.ClassDeclaration */; } return false; } @@ -16393,11 +16323,11 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 - case 169 /* SyntaxKind.MethodDeclaration */: - case 173 /* SyntaxKind.SetAccessor */: - case 171 /* SyntaxKind.Constructor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 175 /* SyntaxKind.SetAccessor */: + case 173 /* SyntaxKind.Constructor */: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 default: return false; @@ -16413,9 +16343,9 @@ var ts; ts.classOrConstructorParameterIsDecorated = classOrConstructorParameterIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 280 /* SyntaxKind.JsxOpeningElement */ || - parent.kind === 279 /* SyntaxKind.JsxSelfClosingElement */ || - parent.kind === 281 /* SyntaxKind.JsxClosingElement */) { + if (parent.kind === 283 /* SyntaxKind.JsxOpeningElement */ || + parent.kind === 282 /* SyntaxKind.JsxSelfClosingElement */ || + parent.kind === 284 /* SyntaxKind.JsxClosingElement */) { return parent.tagName === node; } return false; @@ -16428,53 +16358,54 @@ var ts; case 110 /* SyntaxKind.TrueKeyword */: case 95 /* SyntaxKind.FalseKeyword */: case 13 /* SyntaxKind.RegularExpressionLiteral */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: - case 210 /* SyntaxKind.TaggedTemplateExpression */: - case 229 /* SyntaxKind.AsExpression */: - case 211 /* SyntaxKind.TypeAssertionExpression */: - case 230 /* SyntaxKind.NonNullExpression */: - case 212 /* SyntaxKind.ParenthesizedExpression */: - case 213 /* SyntaxKind.FunctionExpression */: - case 226 /* SyntaxKind.ClassExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 217 /* SyntaxKind.VoidExpression */: - case 215 /* SyntaxKind.DeleteExpression */: - case 216 /* SyntaxKind.TypeOfExpression */: - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 220 /* SyntaxKind.PostfixUnaryExpression */: - case 221 /* SyntaxKind.BinaryExpression */: - case 222 /* SyntaxKind.ConditionalExpression */: - case 225 /* SyntaxKind.SpreadElement */: - case 223 /* SyntaxKind.TemplateExpression */: - case 227 /* SyntaxKind.OmittedExpression */: - case 278 /* SyntaxKind.JsxElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 282 /* SyntaxKind.JsxFragment */: - case 224 /* SyntaxKind.YieldExpression */: - case 218 /* SyntaxKind.AwaitExpression */: - case 231 /* SyntaxKind.MetaProperty */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: + case 231 /* SyntaxKind.AsExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: + case 235 /* SyntaxKind.SatisfiesExpression */: + case 232 /* SyntaxKind.NonNullExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: + case 215 /* SyntaxKind.FunctionExpression */: + case 228 /* SyntaxKind.ClassExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 219 /* SyntaxKind.VoidExpression */: + case 217 /* SyntaxKind.DeleteExpression */: + case 218 /* SyntaxKind.TypeOfExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: + case 227 /* SyntaxKind.SpreadElement */: + case 225 /* SyntaxKind.TemplateExpression */: + case 229 /* SyntaxKind.OmittedExpression */: + case 281 /* SyntaxKind.JsxElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: + case 285 /* SyntaxKind.JsxFragment */: + case 226 /* SyntaxKind.YieldExpression */: + case 220 /* SyntaxKind.AwaitExpression */: + case 233 /* SyntaxKind.MetaProperty */: return true; - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return !ts.isHeritageClause(node.parent); - case 161 /* SyntaxKind.QualifiedName */: - while (node.parent.kind === 161 /* SyntaxKind.QualifiedName */) { + case 163 /* SyntaxKind.QualifiedName */: + while (node.parent.kind === 163 /* SyntaxKind.QualifiedName */) { node = node.parent; } - return node.parent.kind === 181 /* SyntaxKind.TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node); - case 311 /* SyntaxKind.JSDocMemberName */: + return node.parent.kind === 183 /* SyntaxKind.TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node); + case 314 /* SyntaxKind.JSDocMemberName */: while (ts.isJSDocMemberName(node.parent)) { node = node.parent; } - return node.parent.kind === 181 /* SyntaxKind.TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node); + return node.parent.kind === 183 /* SyntaxKind.TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node); case 80 /* SyntaxKind.PrivateIdentifier */: return ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 101 /* SyntaxKind.InKeyword */; case 79 /* SyntaxKind.Identifier */: - if (node.parent.kind === 181 /* SyntaxKind.TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node)) { + if (node.parent.kind === 183 /* SyntaxKind.TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node)) { return true; } // falls through @@ -16492,60 +16423,62 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: - case 164 /* SyntaxKind.Parameter */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 299 /* SyntaxKind.EnumMember */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 203 /* SyntaxKind.BindingElement */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 166 /* SyntaxKind.Parameter */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 302 /* SyntaxKind.EnumMember */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 205 /* SyntaxKind.BindingElement */: return parent.initializer === node; - case 238 /* SyntaxKind.ExpressionStatement */: - case 239 /* SyntaxKind.IfStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 247 /* SyntaxKind.ReturnStatement */: - case 248 /* SyntaxKind.WithStatement */: - case 249 /* SyntaxKind.SwitchStatement */: - case 289 /* SyntaxKind.CaseClause */: - case 251 /* SyntaxKind.ThrowStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: + case 242 /* SyntaxKind.IfStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 250 /* SyntaxKind.ReturnStatement */: + case 251 /* SyntaxKind.WithStatement */: + case 252 /* SyntaxKind.SwitchStatement */: + case 292 /* SyntaxKind.CaseClause */: + case 254 /* SyntaxKind.ThrowStatement */: return parent.expression === node; - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 255 /* SyntaxKind.VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 258 /* SyntaxKind.VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 255 /* SyntaxKind.VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 258 /* SyntaxKind.VariableDeclarationList */) || forInStatement.expression === node; - case 211 /* SyntaxKind.TypeAssertionExpression */: - case 229 /* SyntaxKind.AsExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: + case 231 /* SyntaxKind.AsExpression */: return node === parent.expression; - case 233 /* SyntaxKind.TemplateSpan */: + case 236 /* SyntaxKind.TemplateSpan */: return node === parent.expression; - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: return node === parent.expression; - case 165 /* SyntaxKind.Decorator */: - case 288 /* SyntaxKind.JsxExpression */: - case 287 /* SyntaxKind.JsxSpreadAttribute */: - case 298 /* SyntaxKind.SpreadAssignment */: + case 167 /* SyntaxKind.Decorator */: + case 291 /* SyntaxKind.JsxExpression */: + case 290 /* SyntaxKind.JsxSpreadAttribute */: + case 301 /* SyntaxKind.SpreadAssignment */: return true; - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return parent.expression === node && !isPartOfTypeNode(parent); - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return parent.objectAssignmentInitializer === node; + case 235 /* SyntaxKind.SatisfiesExpression */: + return node === parent.expression; default: return isExpressionNode(parent); } } ts.isInExpressionContext = isInExpressionContext; function isPartOfTypeQuery(node) { - while (node.kind === 161 /* SyntaxKind.QualifiedName */ || node.kind === 79 /* SyntaxKind.Identifier */) { + while (node.kind === 163 /* SyntaxKind.QualifiedName */ || node.kind === 79 /* SyntaxKind.Identifier */) { node = node.parent; } - return node.kind === 181 /* SyntaxKind.TypeQuery */; + return node.kind === 183 /* SyntaxKind.TypeQuery */; } ts.isPartOfTypeQuery = isPartOfTypeQuery; function isNamespaceReexportDeclaration(node) { @@ -16553,7 +16486,7 @@ var ts; } ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ && node.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */; + return node.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ && node.moduleReference.kind === 280 /* SyntaxKind.ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -16566,7 +16499,7 @@ var ts; } ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ && node.moduleReference.kind !== 277 /* SyntaxKind.ExternalModuleReference */; + return node.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ && node.moduleReference.kind !== 280 /* SyntaxKind.ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJS(file) { @@ -16598,11 +16531,11 @@ var ts; ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && node.typeArguments && node.typeArguments.length === 2 && - (node.typeArguments[0].kind === 150 /* SyntaxKind.StringKeyword */ || node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */); + (node.typeArguments[0].kind === 152 /* SyntaxKind.StringKeyword */ || node.typeArguments[0].kind === 148 /* SyntaxKind.NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, requireStringLiteralLikeArgument) { - if (callExpression.kind !== 208 /* SyntaxKind.CallExpression */) { + if (callExpression.kind !== 210 /* SyntaxKind.CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -16711,11 +16644,11 @@ var ts; function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 213 /* SyntaxKind.FunctionExpression */ || e.kind === 214 /* SyntaxKind.ArrowFunction */ ? initializer : undefined; + return e.kind === 215 /* SyntaxKind.FunctionExpression */ || e.kind === 216 /* SyntaxKind.ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 213 /* SyntaxKind.FunctionExpression */ || - initializer.kind === 226 /* SyntaxKind.ClassExpression */ || - initializer.kind === 214 /* SyntaxKind.ArrowFunction */) { + if (initializer.kind === 215 /* SyntaxKind.FunctionExpression */ || + initializer.kind === 228 /* SyntaxKind.ClassExpression */ || + initializer.kind === 216 /* SyntaxKind.ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { @@ -16961,7 +16894,7 @@ var ts; ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJSFile(expr) && - expr.parent && expr.parent.kind === 238 /* SyntaxKind.ExpressionStatement */ && + expr.parent && expr.parent.kind === 241 /* SyntaxKind.ExpressionStatement */ && (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) && !!ts.getJSDocTypeTag(expr.parent); } @@ -16982,17 +16915,17 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 256 /* SyntaxKind.FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 259 /* SyntaxKind.FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; function tryGetModuleSpecifierFromDeclaration(node) { var _a, _b; switch (node.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return (_a = ts.findAncestor(node.initializer, function (node) { return isRequireCall(node, /*requireStringLiteralLikeArgument*/ true); })) === null || _a === void 0 ? void 0 : _a.arguments[0]; - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return ts.tryCast(node.moduleSpecifier, ts.isStringLiteralLike); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return ts.tryCast((_b = ts.tryCast(node.moduleReference, ts.isExternalModuleReference)) === null || _b === void 0 ? void 0 : _b.expression, ts.isStringLiteralLike); default: ts.Debug.assertNever(node); @@ -17005,14 +16938,14 @@ var ts; ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: - case 272 /* SyntaxKind.ExportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: return node.parent; - case 277 /* SyntaxKind.ExternalModuleReference */: + case 280 /* SyntaxKind.ExternalModuleReference */: return node.parent.parent; - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; - case 196 /* SyntaxKind.LiteralType */: + case 198 /* SyntaxKind.LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -17022,16 +16955,16 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: - case 272 /* SyntaxKind.ExportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: return node.moduleSpecifier; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return node.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 200 /* SyntaxKind.ImportType */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + return node.moduleReference.kind === 280 /* SyntaxKind.ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 202 /* SyntaxKind.ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return node.arguments[0]; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return node.name.kind === 10 /* SyntaxKind.StringLiteral */ ? node.name : undefined; default: return ts.Debug.assertNever(node); @@ -17040,11 +16973,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return node; - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport); default: return ts.Debug.assertNever(node); @@ -17052,7 +16985,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 266 /* SyntaxKind.ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 269 /* SyntaxKind.ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function forEachImportClauseDeclaration(node, action) { @@ -17073,13 +17006,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 164 /* SyntaxKind.Parameter */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: + case 166 /* SyntaxKind.Parameter */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: return node.questionToken !== undefined; } } @@ -17093,7 +17026,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 345 /* SyntaxKind.JSDocTypedefTag */ || node.kind === 338 /* SyntaxKind.JSDocCallbackTag */ || node.kind === 339 /* SyntaxKind.JSDocEnumTag */; + return node.kind === 348 /* SyntaxKind.JSDocTypedefTag */ || node.kind === 341 /* SyntaxKind.JSDocCallbackTag */ || node.kind === 342 /* SyntaxKind.JSDocEnumTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -17118,12 +17051,12 @@ var ts; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: return node.initializer; - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: return node.initializer; } } @@ -17135,7 +17068,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 261 /* SyntaxKind.ModuleDeclaration */ + node.body.kind === 264 /* SyntaxKind.ModuleDeclaration */ ? node.body : undefined; } @@ -17150,11 +17083,11 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.addRange(result, filterOwnedJSDocTags(hostNode, ts.last(node.jsDoc))); } - if (node.kind === 164 /* SyntaxKind.Parameter */) { + if (node.kind === 166 /* SyntaxKind.Parameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node)); break; } - if (node.kind === 163 /* SyntaxKind.TypeParameter */) { + if (node.kind === 165 /* SyntaxKind.TypeParameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node)); break; } @@ -17183,11 +17116,11 @@ var ts; } function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 296 /* SyntaxKind.PropertyAssignment */ || - parent.kind === 271 /* SyntaxKind.ExportAssignment */ || - parent.kind === 167 /* SyntaxKind.PropertyDeclaration */ || - parent.kind === 238 /* SyntaxKind.ExpressionStatement */ && node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ || - parent.kind === 247 /* SyntaxKind.ReturnStatement */ || + if (parent.kind === 299 /* SyntaxKind.PropertyAssignment */ || + parent.kind === 274 /* SyntaxKind.ExportAssignment */ || + parent.kind === 169 /* SyntaxKind.PropertyDeclaration */ || + parent.kind === 241 /* SyntaxKind.ExpressionStatement */ && node.kind === 208 /* SyntaxKind.PropertyAccessExpression */ || + parent.kind === 250 /* SyntaxKind.ReturnStatement */ || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { return parent; @@ -17297,34 +17230,34 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 63 /* SyntaxKind.EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* AssignmentKind.Definite */ : 2 /* AssignmentKind.Compound */ : 0 /* AssignmentKind.None */; - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: var unaryOperator = parent.operator; return unaryOperator === 45 /* SyntaxKind.PlusPlusToken */ || unaryOperator === 46 /* SyntaxKind.MinusMinusToken */ ? 2 /* AssignmentKind.Compound */ : 0 /* AssignmentKind.None */; - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return parent.initializer === node ? 1 /* AssignmentKind.Definite */ : 0 /* AssignmentKind.None */; - case 212 /* SyntaxKind.ParenthesizedExpression */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: - case 225 /* SyntaxKind.SpreadElement */: - case 230 /* SyntaxKind.NonNullExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: + case 227 /* SyntaxKind.SpreadElement */: + case 232 /* SyntaxKind.NonNullExpression */: node = parent; break; - case 298 /* SyntaxKind.SpreadAssignment */: + case 301 /* SyntaxKind.SpreadAssignment */: node = parent.parent; break; - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* AssignmentKind.None */; } node = parent.parent; break; - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: if (parent.name === node) { return 0 /* AssignmentKind.None */; } @@ -17351,22 +17284,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 235 /* SyntaxKind.Block */: - case 237 /* SyntaxKind.VariableStatement */: - case 248 /* SyntaxKind.WithStatement */: - case 239 /* SyntaxKind.IfStatement */: - case 249 /* SyntaxKind.SwitchStatement */: - case 263 /* SyntaxKind.CaseBlock */: - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: - case 250 /* SyntaxKind.LabeledStatement */: - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 252 /* SyntaxKind.TryStatement */: - case 292 /* SyntaxKind.CatchClause */: + case 238 /* SyntaxKind.Block */: + case 240 /* SyntaxKind.VariableStatement */: + case 251 /* SyntaxKind.WithStatement */: + case 242 /* SyntaxKind.IfStatement */: + case 252 /* SyntaxKind.SwitchStatement */: + case 266 /* SyntaxKind.CaseBlock */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: + case 253 /* SyntaxKind.LabeledStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 255 /* SyntaxKind.TryStatement */: + case 295 /* SyntaxKind.CatchClause */: return true; } return false; @@ -17383,11 +17316,11 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 191 /* SyntaxKind.ParenthesizedType */); + return walkUp(node, 193 /* SyntaxKind.ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 212 /* SyntaxKind.ParenthesizedExpression */); + return walkUp(node, 214 /* SyntaxKind.ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; /** @@ -17397,7 +17330,7 @@ var ts; */ function walkUpParenthesizedTypesAndGetParentAndChild(node) { var child; - while (node && node.kind === 191 /* SyntaxKind.ParenthesizedType */) { + while (node && node.kind === 193 /* SyntaxKind.ParenthesizedType */) { child = node; node = node.parent; } @@ -17419,11 +17352,11 @@ var ts; ts.skipParentheses = skipParentheses; // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 206 /* SyntaxKind.PropertyAccessExpression */ && node.kind !== 207 /* SyntaxKind.ElementAccessExpression */) { + if (node.kind !== 208 /* SyntaxKind.PropertyAccessExpression */ && node.kind !== 209 /* SyntaxKind.ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 215 /* SyntaxKind.DeleteExpression */; + return node && node.kind === 217 /* SyntaxKind.DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -17476,7 +17409,7 @@ var ts; ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return isStringOrNumericLiteralLike(node) && - node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */ && + node.parent.kind === 164 /* SyntaxKind.ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -17484,29 +17417,29 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 299 /* SyntaxKind.EnumMember */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 302 /* SyntaxKind.EnumMember */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 208 /* SyntaxKind.PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: // Name on right hand side of dot in a type query or type reference return parent.right === node; - case 203 /* SyntaxKind.BindingElement */: - case 270 /* SyntaxKind.ImportSpecifier */: + case 205 /* SyntaxKind.BindingElement */: + case 273 /* SyntaxKind.ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 275 /* SyntaxKind.ExportSpecifier */: - case 285 /* SyntaxKind.JsxAttribute */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 280 /* SyntaxKind.JsxOpeningElement */: - case 281 /* SyntaxKind.JsxClosingElement */: + case 278 /* SyntaxKind.ExportSpecifier */: + case 288 /* SyntaxKind.JsxAttribute */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 284 /* SyntaxKind.JsxClosingElement */: // Any name in an export specifier or JSX Attribute or Jsx Element return true; } @@ -17529,14 +17462,14 @@ var ts; // const x = require("...").y // const { x } = require("...").y function isAliasSymbolDeclaration(node) { - if (node.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ || - node.kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ || - node.kind === 267 /* SyntaxKind.ImportClause */ && !!node.name || - node.kind === 268 /* SyntaxKind.NamespaceImport */ || - node.kind === 274 /* SyntaxKind.NamespaceExport */ || - node.kind === 270 /* SyntaxKind.ImportSpecifier */ || - node.kind === 275 /* SyntaxKind.ExportSpecifier */ || - node.kind === 271 /* SyntaxKind.ExportAssignment */ && exportAssignmentIsAlias(node)) { + if (node.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ || + node.kind === 267 /* SyntaxKind.NamespaceExportDeclaration */ || + node.kind === 270 /* SyntaxKind.ImportClause */ && !!node.name || + node.kind === 271 /* SyntaxKind.NamespaceImport */ || + node.kind === 277 /* SyntaxKind.NamespaceExport */ || + node.kind === 273 /* SyntaxKind.ImportSpecifier */ || + node.kind === 278 /* SyntaxKind.ExportSpecifier */ || + node.kind === 274 /* SyntaxKind.ExportAssignment */ && exportAssignmentIsAlias(node)) { return true; } return isInJSFile(node) && (ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* AssignmentDeclarationKind.ModuleExports */ && exportAssignmentIsAlias(node) || @@ -17549,18 +17482,18 @@ var ts; ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getAliasDeclarationFromName(node) { switch (node.parent.kind) { - case 267 /* SyntaxKind.ImportClause */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 268 /* SyntaxKind.NamespaceImport */: - case 275 /* SyntaxKind.ExportSpecifier */: - case 271 /* SyntaxKind.ExportAssignment */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 274 /* SyntaxKind.NamespaceExport */: + case 270 /* SyntaxKind.ImportClause */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 271 /* SyntaxKind.NamespaceImport */: + case 278 /* SyntaxKind.ExportSpecifier */: + case 274 /* SyntaxKind.ExportAssignment */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 277 /* SyntaxKind.NamespaceExport */: return node.parent; - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: do { node = node.parent; - } while (node.parent.kind === 161 /* SyntaxKind.QualifiedName */); + } while (node.parent.kind === 163 /* SyntaxKind.QualifiedName */); return getAliasDeclarationFromName(node); } } @@ -17579,7 +17512,7 @@ var ts; } ts.getExportAssignmentExpression = getExportAssignmentExpression; function getPropertyAssignmentAliasLikeExpression(node) { - return node.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ ? node.name : node.kind === 296 /* SyntaxKind.PropertyAssignment */ ? node.initializer : + return node.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */ ? node.name : node.kind === 299 /* SyntaxKind.PropertyAssignment */ ? node.initializer : node.parent.right; } ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression; @@ -17645,11 +17578,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 81 /* SyntaxKind.FirstKeyword */ <= token && token <= 160 /* SyntaxKind.LastKeyword */; + return 81 /* SyntaxKind.FirstKeyword */ <= token && token <= 162 /* SyntaxKind.LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 126 /* SyntaxKind.FirstContextualKeyword */ <= token && token <= 160 /* SyntaxKind.LastContextualKeyword */; + return 126 /* SyntaxKind.FirstContextualKeyword */ <= token && token <= 162 /* SyntaxKind.LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -17693,15 +17626,15 @@ var ts; } var flags = 0 /* FunctionFlags.Normal */; switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* FunctionFlags.Generator */; } // falls through - case 214 /* SyntaxKind.ArrowFunction */: - if (hasSyntacticModifier(node, 256 /* ModifierFlags.Async */)) { + case 216 /* SyntaxKind.ArrowFunction */: + if (hasSyntacticModifier(node, 512 /* ModifierFlags.Async */)) { flags |= 2 /* FunctionFlags.Async */; } break; @@ -17714,13 +17647,13 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 169 /* SyntaxKind.MethodDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 171 /* SyntaxKind.MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined - && hasSyntacticModifier(node, 256 /* ModifierFlags.Async */); + && hasSyntacticModifier(node, 512 /* ModifierFlags.Async */); } return false; } @@ -17747,7 +17680,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - if (!(name.kind === 162 /* SyntaxKind.ComputedPropertyName */ || name.kind === 207 /* SyntaxKind.ElementAccessExpression */)) { + if (!(name.kind === 164 /* SyntaxKind.ComputedPropertyName */ || name.kind === 209 /* SyntaxKind.ElementAccessExpression */)) { return false; } var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression; @@ -17763,7 +17696,7 @@ var ts; case 10 /* SyntaxKind.StringLiteral */: case 8 /* SyntaxKind.NumericLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: var nameExpression = name.expression; if (isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); @@ -17829,11 +17762,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 164 /* SyntaxKind.Parameter */; + return root.kind === 166 /* SyntaxKind.Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 203 /* SyntaxKind.BindingElement */) { + while (node.kind === 205 /* SyntaxKind.BindingElement */) { node = node.parent.parent; } return node; @@ -17841,15 +17774,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 171 /* SyntaxKind.Constructor */ - || kind === 213 /* SyntaxKind.FunctionExpression */ - || kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 214 /* SyntaxKind.ArrowFunction */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */ - || kind === 261 /* SyntaxKind.ModuleDeclaration */ - || kind === 305 /* SyntaxKind.SourceFile */; + return kind === 173 /* SyntaxKind.Constructor */ + || kind === 215 /* SyntaxKind.FunctionExpression */ + || kind === 259 /* SyntaxKind.FunctionDeclaration */ + || kind === 216 /* SyntaxKind.ArrowFunction */ + || kind === 171 /* SyntaxKind.MethodDeclaration */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 175 /* SyntaxKind.SetAccessor */ + || kind === 264 /* SyntaxKind.ModuleDeclaration */ + || kind === 308 /* SyntaxKind.SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -17868,23 +17801,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 209 /* SyntaxKind.NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 211 /* SyntaxKind.NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: return hasArguments ? 0 /* Associativity.Left */ : 1 /* Associativity.Right */; - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 216 /* SyntaxKind.TypeOfExpression */: - case 217 /* SyntaxKind.VoidExpression */: - case 215 /* SyntaxKind.DeleteExpression */: - case 218 /* SyntaxKind.AwaitExpression */: - case 222 /* SyntaxKind.ConditionalExpression */: - case 224 /* SyntaxKind.YieldExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: + case 218 /* SyntaxKind.TypeOfExpression */: + case 219 /* SyntaxKind.VoidExpression */: + case 217 /* SyntaxKind.DeleteExpression */: + case 220 /* SyntaxKind.AwaitExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: + case 226 /* SyntaxKind.YieldExpression */: return 1 /* Associativity.Right */; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: switch (operator) { case 42 /* SyntaxKind.AsteriskAsteriskToken */: case 63 /* SyntaxKind.EqualsToken */: @@ -17911,15 +17844,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 209 /* SyntaxKind.NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 211 /* SyntaxKind.NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 221 /* SyntaxKind.BinaryExpression */) { + if (expression.kind === 223 /* SyntaxKind.BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 219 /* SyntaxKind.PrefixUnaryExpression */ || expression.kind === 220 /* SyntaxKind.PostfixUnaryExpression */) { + else if (expression.kind === 221 /* SyntaxKind.PrefixUnaryExpression */ || expression.kind === 222 /* SyntaxKind.PostfixUnaryExpression */) { return expression.operator; } else { @@ -18098,15 +18031,15 @@ var ts; })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {})); function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 351 /* SyntaxKind.CommaListExpression */: + case 354 /* SyntaxKind.CommaListExpression */: return 0 /* OperatorPrecedence.Comma */; - case 225 /* SyntaxKind.SpreadElement */: + case 227 /* SyntaxKind.SpreadElement */: return 1 /* OperatorPrecedence.Spread */; - case 224 /* SyntaxKind.YieldExpression */: + case 226 /* SyntaxKind.YieldExpression */: return 2 /* OperatorPrecedence.Yield */; - case 222 /* SyntaxKind.ConditionalExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: return 4 /* OperatorPrecedence.Conditional */; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: switch (operatorKind) { case 27 /* SyntaxKind.CommaToken */: return 0 /* OperatorPrecedence.Comma */; @@ -18131,26 +18064,27 @@ var ts; return getBinaryOperatorPrecedence(operatorKind); } // TODO: Should prefix `++` and `--` be moved to the `Update` precedence? - case 211 /* SyntaxKind.TypeAssertionExpression */: - case 230 /* SyntaxKind.NonNullExpression */: - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 216 /* SyntaxKind.TypeOfExpression */: - case 217 /* SyntaxKind.VoidExpression */: - case 215 /* SyntaxKind.DeleteExpression */: - case 218 /* SyntaxKind.AwaitExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: + case 232 /* SyntaxKind.NonNullExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: + case 218 /* SyntaxKind.TypeOfExpression */: + case 219 /* SyntaxKind.VoidExpression */: + case 217 /* SyntaxKind.DeleteExpression */: + case 220 /* SyntaxKind.AwaitExpression */: return 16 /* OperatorPrecedence.Unary */; - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: return 17 /* OperatorPrecedence.Update */; - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return 18 /* OperatorPrecedence.LeftHandSide */; - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: return hasArguments ? 19 /* OperatorPrecedence.Member */ : 18 /* OperatorPrecedence.LeftHandSide */; - case 210 /* SyntaxKind.TaggedTemplateExpression */: - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: - case 231 /* SyntaxKind.MetaProperty */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: + case 233 /* SyntaxKind.MetaProperty */: return 19 /* OperatorPrecedence.Member */; - case 229 /* SyntaxKind.AsExpression */: + case 231 /* SyntaxKind.AsExpression */: + case 235 /* SyntaxKind.SatisfiesExpression */: return 11 /* OperatorPrecedence.Relational */; case 108 /* SyntaxKind.ThisKeyword */: case 106 /* SyntaxKind.SuperKeyword */: @@ -18162,19 +18096,19 @@ var ts; case 8 /* SyntaxKind.NumericLiteral */: case 9 /* SyntaxKind.BigIntLiteral */: case 10 /* SyntaxKind.StringLiteral */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 226 /* SyntaxKind.ClassExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 228 /* SyntaxKind.ClassExpression */: case 13 /* SyntaxKind.RegularExpressionLiteral */: case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: - case 223 /* SyntaxKind.TemplateExpression */: - case 212 /* SyntaxKind.ParenthesizedExpression */: - case 227 /* SyntaxKind.OmittedExpression */: - case 278 /* SyntaxKind.JsxElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 282 /* SyntaxKind.JsxFragment */: + case 225 /* SyntaxKind.TemplateExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: + case 229 /* SyntaxKind.OmittedExpression */: + case 281 /* SyntaxKind.JsxElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: + case 285 /* SyntaxKind.JsxFragment */: return 20 /* OperatorPrecedence.Primary */; default: return -1 /* OperatorPrecedence.Invalid */; @@ -18206,7 +18140,8 @@ var ts; case 33 /* SyntaxKind.GreaterThanEqualsToken */: case 102 /* SyntaxKind.InstanceOfKeyword */: case 101 /* SyntaxKind.InKeyword */: - case 127 /* SyntaxKind.AsKeyword */: + case 128 /* SyntaxKind.AsKeyword */: + case 150 /* SyntaxKind.SatisfiesKeyword */: return 11 /* OperatorPrecedence.Relational */; case 47 /* SyntaxKind.LessThanLessThanToken */: case 48 /* SyntaxKind.GreaterThanGreaterThanToken */: @@ -18230,7 +18165,7 @@ var ts; function getSemanticJsxChildren(children) { return ts.filter(children, function (i) { switch (i.kind) { - case 288 /* SyntaxKind.JsxExpression */: + case 291 /* SyntaxKind.JsxExpression */: return !!i.expression; case 11 /* SyntaxKind.JsxText */: return !i.containsOnlyTriviaWhiteSpaces; @@ -18286,7 +18221,7 @@ var ts; } diagnostics = nonFileDiagnostics; } - ts.insertSorted(diagnostics, diagnostic, compareDiagnostics); + ts.insertSorted(diagnostics, diagnostic, compareDiagnosticsSkipRelatedInformation); } function getGlobalDiagnostics() { hasReadNonFileDiagnostics = true; @@ -18822,7 +18757,7 @@ var ts; while (ts.isQualifiedName(node.parent) && node.parent.left === node) { node = node.parent; } - return node.parent.kind === 181 /* SyntaxKind.TypeQuery */; + return node.parent.kind === 183 /* SyntaxKind.TypeQuery */; } ts.isThisInTypeQuery = isThisInTypeQuery; function identifierIsThisKeyword(id) { @@ -18837,10 +18772,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 172 /* SyntaxKind.GetAccessor */) { + if (accessor.kind === 174 /* SyntaxKind.GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 173 /* SyntaxKind.SetAccessor */) { + else if (accessor.kind === 175 /* SyntaxKind.SetAccessor */) { setAccessor = accessor; } else { @@ -18860,10 +18795,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 172 /* SyntaxKind.GetAccessor */ && !getAccessor) { + if (member.kind === 174 /* SyntaxKind.GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 173 /* SyntaxKind.SetAccessor */ && !setAccessor) { + if (member.kind === 175 /* SyntaxKind.SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -18912,7 +18847,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 320 /* SyntaxKind.JSDoc */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 323 /* SyntaxKind.JSDoc */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -19145,13 +19080,17 @@ var ts; } ts.hasOverrideModifier = hasOverrideModifier; function hasAbstractModifier(node) { - return hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */); + return hasSyntacticModifier(node, 256 /* ModifierFlags.Abstract */); } ts.hasAbstractModifier = hasAbstractModifier; function hasAmbientModifier(node) { return hasSyntacticModifier(node, 2 /* ModifierFlags.Ambient */); } ts.hasAmbientModifier = hasAmbientModifier; + function hasAccessorModifier(node) { + return hasSyntacticModifier(node, 128 /* ModifierFlags.Accessor */); + } + ts.hasAccessorModifier = hasAccessorModifier; function hasEffectiveReadonlyModifier(node) { return hasEffectiveModifier(node, 64 /* ModifierFlags.Readonly */); } @@ -19169,7 +19108,7 @@ var ts; } ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags; function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) { - if (node.kind >= 0 /* SyntaxKind.FirstToken */ && node.kind <= 160 /* SyntaxKind.LastToken */) { + if (node.kind >= 0 /* SyntaxKind.FirstToken */ && node.kind <= 162 /* SyntaxKind.LastToken */) { return 0 /* ModifierFlags.None */; } if (!(node.modifierFlagsCache & 536870912 /* ModifierFlags.HasComputedFlags */)) { @@ -19261,25 +19200,22 @@ var ts; case 123 /* SyntaxKind.PublicKeyword */: return 4 /* ModifierFlags.Public */; case 122 /* SyntaxKind.ProtectedKeyword */: return 16 /* ModifierFlags.Protected */; case 121 /* SyntaxKind.PrivateKeyword */: return 8 /* ModifierFlags.Private */; - case 126 /* SyntaxKind.AbstractKeyword */: return 128 /* ModifierFlags.Abstract */; + case 126 /* SyntaxKind.AbstractKeyword */: return 256 /* ModifierFlags.Abstract */; + case 127 /* SyntaxKind.AccessorKeyword */: return 128 /* ModifierFlags.Accessor */; case 93 /* SyntaxKind.ExportKeyword */: return 1 /* ModifierFlags.Export */; - case 135 /* SyntaxKind.DeclareKeyword */: return 2 /* ModifierFlags.Ambient */; + case 136 /* SyntaxKind.DeclareKeyword */: return 2 /* ModifierFlags.Ambient */; case 85 /* SyntaxKind.ConstKeyword */: return 2048 /* ModifierFlags.Const */; - case 88 /* SyntaxKind.DefaultKeyword */: return 512 /* ModifierFlags.Default */; - case 131 /* SyntaxKind.AsyncKeyword */: return 256 /* ModifierFlags.Async */; - case 145 /* SyntaxKind.ReadonlyKeyword */: return 64 /* ModifierFlags.Readonly */; - case 159 /* SyntaxKind.OverrideKeyword */: return 16384 /* ModifierFlags.Override */; + case 88 /* SyntaxKind.DefaultKeyword */: return 1024 /* ModifierFlags.Default */; + case 132 /* SyntaxKind.AsyncKeyword */: return 512 /* ModifierFlags.Async */; + case 146 /* SyntaxKind.ReadonlyKeyword */: return 64 /* ModifierFlags.Readonly */; + case 161 /* SyntaxKind.OverrideKeyword */: return 16384 /* ModifierFlags.Override */; case 101 /* SyntaxKind.InKeyword */: return 32768 /* ModifierFlags.In */; - case 144 /* SyntaxKind.OutKeyword */: return 65536 /* ModifierFlags.Out */; - case 165 /* SyntaxKind.Decorator */: return 131072 /* ModifierFlags.Decorator */; + case 145 /* SyntaxKind.OutKeyword */: return 65536 /* ModifierFlags.Out */; + case 167 /* SyntaxKind.Decorator */: return 131072 /* ModifierFlags.Decorator */; } return 0 /* ModifierFlags.None */; } ts.modifierToFlag = modifierToFlag; - function createModifiers(modifierFlags) { - return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; - } - ts.createModifiers = createModifiers; function isLogicalOperator(token) { return token === 56 /* SyntaxKind.BarBarToken */ || token === 55 /* SyntaxKind.AmpersandAmpersandToken */ @@ -19329,8 +19265,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 205 /* SyntaxKind.ObjectLiteralExpression */ - || kind === 204 /* SyntaxKind.ArrayLiteralExpression */; + return kind === 207 /* SyntaxKind.ObjectLiteralExpression */ + || kind === 206 /* SyntaxKind.ArrayLiteralExpression */; } return false; } @@ -19347,12 +19283,12 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: return node; - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: do { node = node.left; } while (node.kind !== 79 /* SyntaxKind.Identifier */); return node; - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: do { node = node.expression; } while (node.kind !== 79 /* SyntaxKind.Identifier */); @@ -19364,9 +19300,9 @@ var ts; return node.kind === 79 /* SyntaxKind.Identifier */ || node.kind === 108 /* SyntaxKind.ThisKeyword */ || node.kind === 106 /* SyntaxKind.SuperKeyword */ - || node.kind === 231 /* SyntaxKind.MetaProperty */ - || node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && isDottedName(node.expression) - || node.kind === 212 /* SyntaxKind.ParenthesizedExpression */ && isDottedName(node.expression); + || node.kind === 233 /* SyntaxKind.MetaProperty */ + || node.kind === 208 /* SyntaxKind.PropertyAccessExpression */ && isDottedName(node.expression) + || node.kind === 214 /* SyntaxKind.ParenthesizedExpression */ && isDottedName(node.expression); } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { @@ -19397,8 +19333,8 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 161 /* SyntaxKind.QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 163 /* SyntaxKind.QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isRightSideOfAccessExpression(node) { @@ -19413,12 +19349,12 @@ var ts; } ts.isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName = isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName; function isEmptyObjectLiteral(expression) { - return expression.kind === 205 /* SyntaxKind.ObjectLiteralExpression */ && + return expression.kind === 207 /* SyntaxKind.ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 204 /* SyntaxKind.ArrayLiteralExpression */ && + return expression.kind === 206 /* SyntaxKind.ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -19434,7 +19370,7 @@ var ts; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function isExportDefaultSymbol(symbol) { - return symbol && ts.length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 512 /* ModifierFlags.Default */); + return symbol && ts.length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 1024 /* ModifierFlags.Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ function tryExtractTSExtension(fileName) { @@ -19579,21 +19515,17 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJsonOrUndefined(path, hostOrText) { + var jsonText = ts.isString(hostOrText) ? hostOrText : hostOrText.readFile(path); + if (!jsonText) + return undefined; + // gracefully handle if readFile fails or returns not JSON + var result = ts.parseConfigFileTextToJson(path, jsonText); + return !result.error ? result.config : undefined; + } + ts.readJsonOrUndefined = readJsonOrUndefined; function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; - } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } + return readJsonOrUndefined(path, host) || {}; } ts.readJson = readJson; function directoryProbablyExists(directoryName, host) { @@ -19752,8 +19684,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 260 /* SyntaxKind.EnumDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -19769,7 +19701,7 @@ var ts; } function isWatchSet(options) { // Firefox has Object.prototype.watch - return options.watch && options.hasOwnProperty("watch"); + return options.watch && ts.hasProperty(options, "watch"); } ts.isWatchSet = isWatchSet; function closeFileWatcher(watcher) { @@ -19833,35 +19765,35 @@ var ts; if (!parent) return 0 /* AccessKind.Read */; switch (parent.kind) { - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return accessKind(parent); - case 220 /* SyntaxKind.PostfixUnaryExpression */: - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: var operator = parent.operator; return operator === 45 /* SyntaxKind.PlusPlusToken */ || operator === 46 /* SyntaxKind.MinusMinusToken */ ? writeOrReadWrite() : 0 /* AccessKind.Read */; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === 63 /* SyntaxKind.EqualsToken */ ? 1 /* AccessKind.Write */ : writeOrReadWrite() : 0 /* AccessKind.Read */; - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return parent.name !== node ? 0 /* AccessKind.Read */ : accessKind(parent); - case 296 /* SyntaxKind.PropertyAssignment */: { + case 299 /* SyntaxKind.PropertyAssignment */: { var parentAccess = accessKind(parent.parent); // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; } - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. return node === parent.objectAssignmentInitializer ? 0 /* AccessKind.Read */ : accessKind(parent.parent); - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return accessKind(parent); default: return 0 /* AccessKind.Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && walkUpParenthesizedExpressions(parent.parent).kind === 238 /* SyntaxKind.ExpressionStatement */ ? 1 /* AccessKind.Write */ : 2 /* AccessKind.ReadWrite */; + return parent.parent && walkUpParenthesizedExpressions(parent.parent).kind === 241 /* SyntaxKind.ExpressionStatement */ ? 1 /* AccessKind.Write */ : 2 /* AccessKind.ReadWrite */; } } function reverseAccessKind(a) { @@ -19943,7 +19875,7 @@ var ts; function isAbstractConstructorSymbol(symbol) { if (symbol.flags & 32 /* SymbolFlags.Class */) { var declaration = getClassLikeDeclarationOfSymbol(symbol); - return !!declaration && hasSyntacticModifier(declaration, 128 /* ModifierFlags.Abstract */); + return !!declaration && hasSyntacticModifier(declaration, 256 /* ModifierFlags.Abstract */); } return false; } @@ -20005,37 +19937,37 @@ var ts; } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; function isTypeNodeKind(kind) { - return (kind >= 177 /* SyntaxKind.FirstTypeNode */ && kind <= 200 /* SyntaxKind.LastTypeNode */) - || kind === 130 /* SyntaxKind.AnyKeyword */ - || kind === 155 /* SyntaxKind.UnknownKeyword */ - || kind === 147 /* SyntaxKind.NumberKeyword */ - || kind === 158 /* SyntaxKind.BigIntKeyword */ - || kind === 148 /* SyntaxKind.ObjectKeyword */ - || kind === 133 /* SyntaxKind.BooleanKeyword */ - || kind === 150 /* SyntaxKind.StringKeyword */ - || kind === 151 /* SyntaxKind.SymbolKeyword */ + return (kind >= 179 /* SyntaxKind.FirstTypeNode */ && kind <= 202 /* SyntaxKind.LastTypeNode */) + || kind === 131 /* SyntaxKind.AnyKeyword */ + || kind === 157 /* SyntaxKind.UnknownKeyword */ + || kind === 148 /* SyntaxKind.NumberKeyword */ + || kind === 160 /* SyntaxKind.BigIntKeyword */ + || kind === 149 /* SyntaxKind.ObjectKeyword */ + || kind === 134 /* SyntaxKind.BooleanKeyword */ + || kind === 152 /* SyntaxKind.StringKeyword */ + || kind === 153 /* SyntaxKind.SymbolKeyword */ || kind === 114 /* SyntaxKind.VoidKeyword */ - || kind === 153 /* SyntaxKind.UndefinedKeyword */ - || kind === 143 /* SyntaxKind.NeverKeyword */ - || kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */ - || kind === 312 /* SyntaxKind.JSDocAllType */ - || kind === 313 /* SyntaxKind.JSDocUnknownType */ - || kind === 314 /* SyntaxKind.JSDocNullableType */ - || kind === 315 /* SyntaxKind.JSDocNonNullableType */ - || kind === 316 /* SyntaxKind.JSDocOptionalType */ - || kind === 317 /* SyntaxKind.JSDocFunctionType */ - || kind === 318 /* SyntaxKind.JSDocVariadicType */; + || kind === 155 /* SyntaxKind.UndefinedKeyword */ + || kind === 144 /* SyntaxKind.NeverKeyword */ + || kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */ + || kind === 315 /* SyntaxKind.JSDocAllType */ + || kind === 316 /* SyntaxKind.JSDocUnknownType */ + || kind === 317 /* SyntaxKind.JSDocNullableType */ + || kind === 318 /* SyntaxKind.JSDocNonNullableType */ + || kind === 319 /* SyntaxKind.JSDocOptionalType */ + || kind === 320 /* SyntaxKind.JSDocFunctionType */ + || kind === 321 /* SyntaxKind.JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; function isAccessExpression(node) { - return node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ || node.kind === 207 /* SyntaxKind.ElementAccessExpression */; + return node.kind === 208 /* SyntaxKind.PropertyAccessExpression */ || node.kind === 209 /* SyntaxKind.ElementAccessExpression */; } ts.isAccessExpression = isAccessExpression; function getNameOfAccessExpression(node) { - if (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + if (node.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { return node.name; } - ts.Debug.assert(node.kind === 207 /* SyntaxKind.ElementAccessExpression */); + ts.Debug.assert(node.kind === 209 /* SyntaxKind.ElementAccessExpression */); return node.argumentExpression; } ts.getNameOfAccessExpression = getNameOfAccessExpression; @@ -20050,7 +19982,7 @@ var ts; } ts.isBundleFileTextLike = isBundleFileTextLike; function isNamedImportsOrExports(node) { - return node.kind === 269 /* SyntaxKind.NamedImports */ || node.kind === 273 /* SyntaxKind.NamedExports */; + return node.kind === 272 /* SyntaxKind.NamedImports */ || node.kind === 276 /* SyntaxKind.NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function getLeftmostAccessExpression(expr) { @@ -20065,13 +19997,13 @@ var ts; return walkAccessExpression(name.parent); } function walkAccessExpression(access) { - if (access.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + if (access.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { var res = action(access.name); if (res !== undefined) { return res; } } - else if (access.kind === 207 /* SyntaxKind.ElementAccessExpression */) { + else if (access.kind === 209 /* SyntaxKind.ElementAccessExpression */) { if (ts.isIdentifier(access.argumentExpression) || ts.isStringLiteralLike(access.argumentExpression)) { var res = action(access.argumentExpression); if (res !== undefined) { @@ -20098,28 +20030,29 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: node = node.operand; continue; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: node = node.left; continue; - case 222 /* SyntaxKind.ConditionalExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: node = node.condition; continue; - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: node = node.tag; continue; - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 229 /* SyntaxKind.AsExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 230 /* SyntaxKind.NonNullExpression */: - case 350 /* SyntaxKind.PartiallyEmittedExpression */: + case 231 /* SyntaxKind.AsExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 232 /* SyntaxKind.NonNullExpression */: + case 353 /* SyntaxKind.PartiallyEmittedExpression */: + case 235 /* SyntaxKind.SatisfiesExpression */: node = node.expression; continue; } @@ -21355,17 +21288,17 @@ var ts; return ts.isIdentifier(useSite) && ts.isShorthandPropertyAssignment(useSite.parent) && useSite.parent.name === useSite; } function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { - while (node.kind === 79 /* SyntaxKind.Identifier */ || node.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + while (node.kind === 79 /* SyntaxKind.Identifier */ || node.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { node = node.parent; } - if (node.kind !== 162 /* SyntaxKind.ComputedPropertyName */) { + if (node.kind !== 164 /* SyntaxKind.ComputedPropertyName */) { return false; } - if (hasSyntacticModifier(node.parent, 128 /* ModifierFlags.Abstract */)) { + if (hasSyntacticModifier(node.parent, 256 /* ModifierFlags.Abstract */)) { return true; } var containerKind = node.parent.parent.kind; - return containerKind === 258 /* SyntaxKind.InterfaceDeclaration */ || containerKind === 182 /* SyntaxKind.TypeLiteral */; + return containerKind === 261 /* SyntaxKind.InterfaceDeclaration */ || containerKind === 184 /* SyntaxKind.TypeLiteral */; } /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */ function isIdentifierInNonEmittingHeritageClause(node) { @@ -21373,16 +21306,16 @@ var ts; return false; var heritageClause = ts.findAncestor(node.parent, function (parent) { switch (parent.kind) { - case 291 /* SyntaxKind.HeritageClause */: + case 294 /* SyntaxKind.HeritageClause */: return true; - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return false; default: return "quit"; } }); - return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 117 /* SyntaxKind.ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 258 /* SyntaxKind.InterfaceDeclaration */; + return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 117 /* SyntaxKind.ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 261 /* SyntaxKind.InterfaceDeclaration */; } function isIdentifierTypeReference(node) { return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); @@ -21543,22 +21476,22 @@ var ts; if (!node.parent) return undefined; switch (node.kind) { - case 163 /* SyntaxKind.TypeParameter */: + case 165 /* SyntaxKind.TypeParameter */: var parent_1 = node.parent; - return parent_1.kind === 190 /* SyntaxKind.InferType */ ? undefined : parent_1.typeParameters; - case 164 /* SyntaxKind.Parameter */: + return parent_1.kind === 192 /* SyntaxKind.InferType */ ? undefined : parent_1.typeParameters; + case 166 /* SyntaxKind.Parameter */: return node.parent.parameters; - case 199 /* SyntaxKind.TemplateLiteralTypeSpan */: + case 201 /* SyntaxKind.TemplateLiteralTypeSpan */: return node.parent.templateSpans; - case 233 /* SyntaxKind.TemplateSpan */: + case 236 /* SyntaxKind.TemplateSpan */: return node.parent.templateSpans; - case 165 /* SyntaxKind.Decorator */: { + case 167 /* SyntaxKind.Decorator */: { var parent_2 = node.parent; return ts.canHaveDecorators(parent_2) ? parent_2.modifiers : ts.canHaveIllegalDecorators(parent_2) ? parent_2.illegalDecorators : undefined; } - case 291 /* SyntaxKind.HeritageClause */: + case 294 /* SyntaxKind.HeritageClause */: return node.parent.heritageClauses; } var parent = node.parent; @@ -21566,45 +21499,45 @@ var ts; return ts.isJSDocTypeLiteral(node.parent) ? undefined : node.parent.tags; } switch (parent.kind) { - case 182 /* SyntaxKind.TypeLiteral */: - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 184 /* SyntaxKind.TypeLiteral */: + case 261 /* SyntaxKind.InterfaceDeclaration */: return ts.isTypeElement(node) ? parent.members : undefined; - case 187 /* SyntaxKind.UnionType */: - case 188 /* SyntaxKind.IntersectionType */: + case 189 /* SyntaxKind.UnionType */: + case 190 /* SyntaxKind.IntersectionType */: return parent.types; - case 184 /* SyntaxKind.TupleType */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: - case 351 /* SyntaxKind.CommaListExpression */: - case 269 /* SyntaxKind.NamedImports */: - case 273 /* SyntaxKind.NamedExports */: + case 186 /* SyntaxKind.TupleType */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: + case 354 /* SyntaxKind.CommaListExpression */: + case 272 /* SyntaxKind.NamedImports */: + case 276 /* SyntaxKind.NamedExports */: return parent.elements; - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 286 /* SyntaxKind.JsxAttributes */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 289 /* SyntaxKind.JsxAttributes */: return parent.properties; - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: return ts.isTypeNode(node) ? parent.typeArguments : parent.expression === node ? undefined : parent.arguments; - case 278 /* SyntaxKind.JsxElement */: - case 282 /* SyntaxKind.JsxFragment */: + case 281 /* SyntaxKind.JsxElement */: + case 285 /* SyntaxKind.JsxFragment */: return ts.isJsxChild(node) ? parent.children : undefined; - case 280 /* SyntaxKind.JsxOpeningElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: return ts.isTypeNode(node) ? parent.typeArguments : undefined; - case 235 /* SyntaxKind.Block */: - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: - case 262 /* SyntaxKind.ModuleBlock */: + case 238 /* SyntaxKind.Block */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: + case 265 /* SyntaxKind.ModuleBlock */: return parent.statements; - case 263 /* SyntaxKind.CaseBlock */: + case 266 /* SyntaxKind.CaseBlock */: return parent.clauses; - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: return ts.isClassElement(node) ? parent.members : undefined; - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return ts.isEnumMember(node) ? parent.members : undefined; - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: return parent.statements; } } @@ -21616,7 +21549,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 214 /* SyntaxKind.ArrowFunction */) { + if (node.kind !== 216 /* SyntaxKind.ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -21634,7 +21567,7 @@ var ts; } ts.isInfinityOrNaNString = isInfinityOrNaNString; function isCatchClauseVariableDeclaration(node) { - return node.kind === 254 /* SyntaxKind.VariableDeclaration */ && node.parent.kind === 292 /* SyntaxKind.CatchClause */; + return node.kind === 257 /* SyntaxKind.VariableDeclaration */ && node.parent.kind === 295 /* SyntaxKind.CatchClause */; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; function isParameterOrCatchClauseVariable(symbol) { @@ -21643,7 +21576,7 @@ var ts; } ts.isParameterOrCatchClauseVariable = isParameterOrCatchClauseVariable; function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 213 /* SyntaxKind.FunctionExpression */ || node.kind === 214 /* SyntaxKind.ArrowFunction */; + return node.kind === 215 /* SyntaxKind.FunctionExpression */ || node.kind === 216 /* SyntaxKind.ArrowFunction */; } ts.isFunctionExpressionOrArrowFunction = isFunctionExpressionOrArrowFunction; function escapeSnippetText(text) { @@ -21740,9 +21673,35 @@ var ts; ts.getNodeModulePathParts = getNodeModulePathParts; function getParameterTypeNode(parameter) { var _a; - return parameter.kind === 340 /* SyntaxKind.JSDocParameterTag */ ? (_a = parameter.typeExpression) === null || _a === void 0 ? void 0 : _a.type : parameter.type; + return parameter.kind === 343 /* SyntaxKind.JSDocParameterTag */ ? (_a = parameter.typeExpression) === null || _a === void 0 ? void 0 : _a.type : parameter.type; } ts.getParameterTypeNode = getParameterTypeNode; + function isTypeDeclaration(node) { + switch (node.kind) { + case 165 /* SyntaxKind.TypeParameter */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: + return true; + case 270 /* SyntaxKind.ImportClause */: + return node.isTypeOnly; + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: + return node.parent.parent.isTypeOnly; + default: + return false; + } + } + ts.isTypeDeclaration = isTypeDeclaration; + function canHaveExportModifier(node) { + return ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) || isTypeDeclaration(node) || (ts.isModuleDeclaration(node) && !isExternalModuleAugmentation(node) && !isGlobalScopeAugmentation(node)); + } + ts.canHaveExportModifier = canHaveExportModifier; })(ts || (ts = {})); /* @internal */ var ts; @@ -21751,13 +21710,11 @@ var ts; * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator. */ function createBaseNodeFactory() { - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name return { createBaseSourceFileNode: createBaseSourceFileNode, createBaseIdentifierNode: createBaseIdentifierNode, @@ -21865,10 +21822,10 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(221 /* SyntaxKind.BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(221 /* SyntaxKind.BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(223 /* SyntaxKind.BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(223 /* SyntaxKind.BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 214 /* SyntaxKind.ArrowFunction */ && binaryOperatorPrecedence > 3 /* OperatorPrecedence.Assignment */) { + if (!isLeftSideOfBinary && operand.kind === 216 /* SyntaxKind.ArrowFunction */ && binaryOperatorPrecedence > 3 /* OperatorPrecedence.Assignment */) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -21880,7 +21837,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Associativity.Right */ - && operand.kind === 224 /* SyntaxKind.YieldExpression */) { + && operand.kind === 226 /* SyntaxKind.YieldExpression */) { return false; } return true; @@ -21949,13 +21906,15 @@ var ts; // (a|b)|c -> a|(b|c) -> a|b|c // (a&b)&c -> a&(b&c) -> a&b&c // (a^b)^c -> a^(b^c) -> a^b^c + // (a,b),c -> a,(b,c) -> a,b,c // // While addition is associative in mathematics, JavaScript's `+` is not // guaranteed to be associative as it is overloaded with string concatenation. return binaryOperator === 41 /* SyntaxKind.AsteriskToken */ || binaryOperator === 51 /* SyntaxKind.BarToken */ || binaryOperator === 50 /* SyntaxKind.AmpersandToken */ - || binaryOperator === 52 /* SyntaxKind.CaretToken */; + || binaryOperator === 52 /* SyntaxKind.CaretToken */ + || binaryOperator === 27 /* SyntaxKind.CommaToken */; } /** * This function determines whether an expression consists of a homogeneous set of @@ -21968,7 +21927,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 221 /* SyntaxKind.BinaryExpression */ && node.operatorToken.kind === 39 /* SyntaxKind.PlusToken */) { + if (node.kind === 223 /* SyntaxKind.BinaryExpression */ && node.operatorToken.kind === 39 /* SyntaxKind.PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -21994,7 +21953,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 212 /* SyntaxKind.ParenthesizedExpression */) { + if (skipped.kind === 214 /* SyntaxKind.ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -22011,7 +21970,7 @@ var ts; return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression; } function parenthesizeConditionOfConditionalExpression(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(222 /* SyntaxKind.ConditionalExpression */, 57 /* SyntaxKind.QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(224 /* SyntaxKind.ConditionalExpression */, 57 /* SyntaxKind.QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* Comparison.GreaterThan */) { @@ -22044,8 +22003,8 @@ var ts; var needsParens = ts.isCommaSequence(check); if (!needsParens) { switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { - case 226 /* SyntaxKind.ClassExpression */: - case 213 /* SyntaxKind.FunctionExpression */: + case 228 /* SyntaxKind.ClassExpression */: + case 215 /* SyntaxKind.FunctionExpression */: needsParens = true; } } @@ -22058,9 +22017,9 @@ var ts; function parenthesizeExpressionOfNew(expression) { var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return factory.createParenthesizedExpression(expression); - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: return !leftmostExpr.arguments ? factory.createParenthesizedExpression(expression) : expression; // TODO(rbuckton): Verify this assertion holds @@ -22080,7 +22039,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments) + && (emittedExpression.kind !== 211 /* SyntaxKind.NewExpression */ || emittedExpression.arguments) && (optionalChain || !ts.isOptionalChain(emittedExpression))) { // TODO(rbuckton): Verify whether this assertion holds. return expression; @@ -22103,7 +22062,7 @@ var ts; function parenthesizeExpressionForDisallowedComma(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(221 /* SyntaxKind.BinaryExpression */, 27 /* SyntaxKind.CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(223 /* SyntaxKind.BinaryExpression */, 27 /* SyntaxKind.CommaToken */); // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } @@ -22112,21 +22071,21 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 213 /* SyntaxKind.FunctionExpression */ || kind === 214 /* SyntaxKind.ArrowFunction */) { + if (kind === 215 /* SyntaxKind.FunctionExpression */ || kind === 216 /* SyntaxKind.ArrowFunction */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments); return factory.restoreOuterExpressions(expression, updated, 8 /* OuterExpressionKinds.PartiallyEmittedExpressions */); } } var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 205 /* SyntaxKind.ObjectLiteralExpression */ || leftmostExpressionKind === 213 /* SyntaxKind.FunctionExpression */) { + if (leftmostExpressionKind === 207 /* SyntaxKind.ObjectLiteralExpression */ || leftmostExpressionKind === 215 /* SyntaxKind.FunctionExpression */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } return expression; } function parenthesizeConciseBodyOfArrowFunction(body) { - if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 205 /* SyntaxKind.ObjectLiteralExpression */)) { + if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 207 /* SyntaxKind.ObjectLiteralExpression */)) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(body), body); } @@ -22144,16 +22103,16 @@ var ts; // - The true and false branch types (the second and third `Type` non-terminals, above) allow any type function parenthesizeCheckTypeOfConditionalType(checkType) { switch (checkType.kind) { - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 189 /* SyntaxKind.ConditionalType */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: + case 191 /* SyntaxKind.ConditionalType */: return factory.createParenthesizedType(checkType); } return checkType; } function parenthesizeExtendsTypeOfConditionalType(extendsType) { switch (extendsType.kind) { - case 189 /* SyntaxKind.ConditionalType */: + case 191 /* SyntaxKind.ConditionalType */: return factory.createParenthesizedType(extendsType); } return extendsType; @@ -22165,8 +22124,8 @@ var ts; // - A union type constituent has the same precedence as the check type of a conditional type function parenthesizeConstituentTypeOfUnionType(type) { switch (type.kind) { - case 187 /* SyntaxKind.UnionType */: // Not strictly necessary, but a union containing a union should have been flattened - case 188 /* SyntaxKind.IntersectionType */: // Not strictly necessary, but makes generated output more readable and avoids breaks in DT tests + case 189 /* SyntaxKind.UnionType */: // Not strictly necessary, but a union containing a union should have been flattened + case 190 /* SyntaxKind.IntersectionType */: // Not strictly necessary, but makes generated output more readable and avoids breaks in DT tests return factory.createParenthesizedType(type); } return parenthesizeCheckTypeOfConditionalType(type); @@ -22181,8 +22140,8 @@ var ts; // - An intersection type constituent does not allow function, constructor, conditional, or union types (they must be parenthesized) function parenthesizeConstituentTypeOfIntersectionType(type) { switch (type.kind) { - case 187 /* SyntaxKind.UnionType */: - case 188 /* SyntaxKind.IntersectionType */: // Not strictly necessary, but an intersection containing an intersection should have been flattened + case 189 /* SyntaxKind.UnionType */: + case 190 /* SyntaxKind.IntersectionType */: // Not strictly necessary, but an intersection containing an intersection should have been flattened return factory.createParenthesizedType(type); } return parenthesizeConstituentTypeOfUnionType(type); @@ -22199,14 +22158,14 @@ var ts; // function parenthesizeOperandOfTypeOperator(type) { switch (type.kind) { - case 188 /* SyntaxKind.IntersectionType */: + case 190 /* SyntaxKind.IntersectionType */: return factory.createParenthesizedType(type); } return parenthesizeConstituentTypeOfIntersectionType(type); } function parenthesizeOperandOfReadonlyTypeOperator(type) { switch (type.kind) { - case 193 /* SyntaxKind.TypeOperator */: + case 195 /* SyntaxKind.TypeOperator */: return factory.createParenthesizedType(type); } return parenthesizeOperandOfTypeOperator(type); @@ -22226,9 +22185,9 @@ var ts; // function parenthesizeNonArrayTypeOfPostfixType(type) { switch (type.kind) { - case 190 /* SyntaxKind.InferType */: - case 193 /* SyntaxKind.TypeOperator */: - case 181 /* SyntaxKind.TypeQuery */: // Not strictly necessary, but makes generated output more readable and avoids breaks in DT tests + case 192 /* SyntaxKind.InferType */: + case 195 /* SyntaxKind.TypeOperator */: + case 183 /* SyntaxKind.TypeQuery */: // Not strictly necessary, but makes generated output more readable and avoids breaks in DT tests return factory.createParenthesizedType(type); } return parenthesizeOperandOfTypeOperator(type); @@ -22422,11 +22381,11 @@ var ts; } function convertToAssignmentPattern(node) { switch (node.kind) { - case 202 /* SyntaxKind.ArrayBindingPattern */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 204 /* SyntaxKind.ArrayBindingPattern */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -22520,6 +22479,8 @@ var ts; createUniqueName: createUniqueName, getGeneratedNameForNode: getGeneratedNameForNode, createPrivateIdentifier: createPrivateIdentifier, + createUniquePrivateName: createUniquePrivateName, + getGeneratedPrivateNameForNode: getGeneratedPrivateNameForNode, createToken: createToken, createSuper: createSuper, createThis: createThis, @@ -22682,6 +22643,8 @@ var ts; updateAsExpression: updateAsExpression, createNonNullExpression: createNonNullExpression, updateNonNullExpression: updateNonNullExpression, + createSatisfiesExpression: createSatisfiesExpression, + updateSatisfiesExpression: updateSatisfiesExpression, createNonNullChain: createNonNullChain, updateNonNullChain: updateNonNullChain, createMetaProperty: createMetaProperty, @@ -22779,18 +22742,18 @@ var ts; createExternalModuleReference: createExternalModuleReference, updateExternalModuleReference: updateExternalModuleReference, // lazily load factory members for JSDoc types with similar structure - get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(312 /* SyntaxKind.JSDocAllType */); }, - get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(313 /* SyntaxKind.JSDocUnknownType */); }, - get createJSDocNonNullableType() { return getJSDocPrePostfixUnaryTypeCreateFunction(315 /* SyntaxKind.JSDocNonNullableType */); }, - get updateJSDocNonNullableType() { return getJSDocPrePostfixUnaryTypeUpdateFunction(315 /* SyntaxKind.JSDocNonNullableType */); }, - get createJSDocNullableType() { return getJSDocPrePostfixUnaryTypeCreateFunction(314 /* SyntaxKind.JSDocNullableType */); }, - get updateJSDocNullableType() { return getJSDocPrePostfixUnaryTypeUpdateFunction(314 /* SyntaxKind.JSDocNullableType */); }, - get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(316 /* SyntaxKind.JSDocOptionalType */); }, - get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(316 /* SyntaxKind.JSDocOptionalType */); }, - get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(318 /* SyntaxKind.JSDocVariadicType */); }, - get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(318 /* SyntaxKind.JSDocVariadicType */); }, - get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(319 /* SyntaxKind.JSDocNamepathType */); }, - get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(319 /* SyntaxKind.JSDocNamepathType */); }, + get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(315 /* SyntaxKind.JSDocAllType */); }, + get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(316 /* SyntaxKind.JSDocUnknownType */); }, + get createJSDocNonNullableType() { return getJSDocPrePostfixUnaryTypeCreateFunction(318 /* SyntaxKind.JSDocNonNullableType */); }, + get updateJSDocNonNullableType() { return getJSDocPrePostfixUnaryTypeUpdateFunction(318 /* SyntaxKind.JSDocNonNullableType */); }, + get createJSDocNullableType() { return getJSDocPrePostfixUnaryTypeCreateFunction(317 /* SyntaxKind.JSDocNullableType */); }, + get updateJSDocNullableType() { return getJSDocPrePostfixUnaryTypeUpdateFunction(317 /* SyntaxKind.JSDocNullableType */); }, + get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(319 /* SyntaxKind.JSDocOptionalType */); }, + get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(319 /* SyntaxKind.JSDocOptionalType */); }, + get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(321 /* SyntaxKind.JSDocVariadicType */); }, + get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(321 /* SyntaxKind.JSDocVariadicType */); }, + get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(322 /* SyntaxKind.JSDocNamepathType */); }, + get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(322 /* SyntaxKind.JSDocNamepathType */); }, createJSDocFunctionType: createJSDocFunctionType, updateJSDocFunctionType: updateJSDocFunctionType, createJSDocTypeLiteral: createJSDocTypeLiteral, @@ -22826,30 +22789,30 @@ var ts; createJSDocLinkPlain: createJSDocLinkPlain, updateJSDocLinkPlain: updateJSDocLinkPlain, // lazily load factory members for JSDoc tags with similar structure - get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(343 /* SyntaxKind.JSDocTypeTag */); }, - get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(343 /* SyntaxKind.JSDocTypeTag */); }, - get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(341 /* SyntaxKind.JSDocReturnTag */); }, - get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(341 /* SyntaxKind.JSDocReturnTag */); }, - get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(342 /* SyntaxKind.JSDocThisTag */); }, - get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(342 /* SyntaxKind.JSDocThisTag */); }, - get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(339 /* SyntaxKind.JSDocEnumTag */); }, - get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(339 /* SyntaxKind.JSDocEnumTag */); }, - get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(330 /* SyntaxKind.JSDocAuthorTag */); }, - get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(330 /* SyntaxKind.JSDocAuthorTag */); }, - get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(332 /* SyntaxKind.JSDocClassTag */); }, - get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(332 /* SyntaxKind.JSDocClassTag */); }, - get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(333 /* SyntaxKind.JSDocPublicTag */); }, - get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(333 /* SyntaxKind.JSDocPublicTag */); }, - get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(334 /* SyntaxKind.JSDocPrivateTag */); }, - get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(334 /* SyntaxKind.JSDocPrivateTag */); }, - get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(335 /* SyntaxKind.JSDocProtectedTag */); }, - get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(335 /* SyntaxKind.JSDocProtectedTag */); }, - get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(336 /* SyntaxKind.JSDocReadonlyTag */); }, - get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(336 /* SyntaxKind.JSDocReadonlyTag */); }, - get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(337 /* SyntaxKind.JSDocOverrideTag */); }, - get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(337 /* SyntaxKind.JSDocOverrideTag */); }, - get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(331 /* SyntaxKind.JSDocDeprecatedTag */); }, - get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(331 /* SyntaxKind.JSDocDeprecatedTag */); }, + get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(346 /* SyntaxKind.JSDocTypeTag */); }, + get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(346 /* SyntaxKind.JSDocTypeTag */); }, + get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(344 /* SyntaxKind.JSDocReturnTag */); }, + get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(344 /* SyntaxKind.JSDocReturnTag */); }, + get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(345 /* SyntaxKind.JSDocThisTag */); }, + get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(345 /* SyntaxKind.JSDocThisTag */); }, + get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(342 /* SyntaxKind.JSDocEnumTag */); }, + get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(342 /* SyntaxKind.JSDocEnumTag */); }, + get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(333 /* SyntaxKind.JSDocAuthorTag */); }, + get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(333 /* SyntaxKind.JSDocAuthorTag */); }, + get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(335 /* SyntaxKind.JSDocClassTag */); }, + get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(335 /* SyntaxKind.JSDocClassTag */); }, + get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(336 /* SyntaxKind.JSDocPublicTag */); }, + get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(336 /* SyntaxKind.JSDocPublicTag */); }, + get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(337 /* SyntaxKind.JSDocPrivateTag */); }, + get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(337 /* SyntaxKind.JSDocPrivateTag */); }, + get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(338 /* SyntaxKind.JSDocProtectedTag */); }, + get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(338 /* SyntaxKind.JSDocProtectedTag */); }, + get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(339 /* SyntaxKind.JSDocReadonlyTag */); }, + get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(339 /* SyntaxKind.JSDocReadonlyTag */); }, + get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(340 /* SyntaxKind.JSDocOverrideTag */); }, + get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(340 /* SyntaxKind.JSDocOverrideTag */); }, + get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(334 /* SyntaxKind.JSDocDeprecatedTag */); }, + get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(334 /* SyntaxKind.JSDocDeprecatedTag */); }, createJSDocUnknownTag: createJSDocUnknownTag, updateJSDocUnknownTag: updateJSDocUnknownTag, createJSDocText: createJSDocText, @@ -23052,11 +23015,11 @@ var ts; // don't propagate child flags. if (name) { switch (node.kind) { - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 296 /* SyntaxKind.PropertyAssignment */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 299 /* SyntaxKind.PropertyAssignment */: if (ts.isIdentifier(name)) { node.transformFlags |= propagateIdentifierNameFlags(name); break; @@ -23205,23 +23168,29 @@ var ts; node.escapedText = ts.escapeLeadingUnderscores(text); return node; } - function createBaseGeneratedIdentifier(text, autoGenerateFlags) { + function createBaseGeneratedIdentifier(text, autoGenerateFlags, prefix, suffix) { var node = createBaseIdentifier(text, /*originalKeywordKind*/ undefined); node.autoGenerateFlags = autoGenerateFlags; node.autoGenerateId = nextAutoGenerateId; + node.autoGeneratePrefix = prefix; + node.autoGenerateSuffix = suffix; nextAutoGenerateId++; return node; } // @api - function createIdentifier(text, typeArguments, originalKeywordKind) { + function createIdentifier(text, typeArguments, originalKeywordKind, hasExtendedUnicodeEscape) { var node = createBaseIdentifier(text, originalKeywordKind); if (typeArguments) { // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations node.typeArguments = createNodeArray(typeArguments); } - if (node.originalKeywordKind === 132 /* SyntaxKind.AwaitKeyword */) { + if (node.originalKeywordKind === 133 /* SyntaxKind.AwaitKeyword */) { node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } + if (hasExtendedUnicodeEscape) { + node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + } return node; } // @api @@ -23231,11 +23200,11 @@ var ts; : node; } // @api - function createTempVariable(recordTempVariable, reservedInNestedScopes) { + function createTempVariable(recordTempVariable, reservedInNestedScopes, prefix, suffix) { var flags = 1 /* GeneratedIdentifierFlags.Auto */; if (reservedInNestedScopes) flags |= 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */; - var name = createBaseGeneratedIdentifier("", flags); + var name = createBaseGeneratedIdentifier("", flags, prefix, suffix); if (recordTempVariable) { recordTempVariable(name); } @@ -23247,34 +23216,69 @@ var ts; var flags = 2 /* GeneratedIdentifierFlags.Loop */; if (reservedInNestedScopes) flags |= 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */; - return createBaseGeneratedIdentifier("", flags); + return createBaseGeneratedIdentifier("", flags, /*prefix*/ undefined, /*suffix*/ undefined); } /** Create a unique name based on the supplied text. */ // @api - function createUniqueName(text, flags) { + function createUniqueName(text, flags, prefix, suffix) { if (flags === void 0) { flags = 0 /* GeneratedIdentifierFlags.None */; } ts.Debug.assert(!(flags & 7 /* GeneratedIdentifierFlags.KindMask */), "Argument out of range: flags"); ts.Debug.assert((flags & (16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */)) !== 32 /* GeneratedIdentifierFlags.FileLevel */, "GeneratedIdentifierFlags.FileLevel cannot be set without also setting GeneratedIdentifierFlags.Optimistic"); - return createBaseGeneratedIdentifier(text, 3 /* GeneratedIdentifierFlags.Unique */ | flags); + return createBaseGeneratedIdentifier(text, 3 /* GeneratedIdentifierFlags.Unique */ | flags, prefix, suffix); } /** Create a unique name generated for a node. */ // @api - function getGeneratedNameForNode(node, flags) { + function getGeneratedNameForNode(node, flags, prefix, suffix) { if (flags === void 0) { flags = 0; } ts.Debug.assert(!(flags & 7 /* GeneratedIdentifierFlags.KindMask */), "Argument out of range: flags"); - var name = createBaseGeneratedIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "", 4 /* GeneratedIdentifierFlags.Node */ | flags); + var text = !node ? "" : + ts.isMemberName(node) ? ts.formatGeneratedName(/*privateName*/ false, prefix, node, suffix, ts.idText) : + "generated@".concat(ts.getNodeId(node)); + if (prefix || suffix) + flags |= 16 /* GeneratedIdentifierFlags.Optimistic */; + var name = createBaseGeneratedIdentifier(text, 4 /* GeneratedIdentifierFlags.Node */ | flags, prefix, suffix); name.original = node; return name; } + function createBasePrivateIdentifier(text) { + var node = baseFactory.createBasePrivateIdentifierNode(80 /* SyntaxKind.PrivateIdentifier */); + node.escapedText = ts.escapeLeadingUnderscores(text); + node.transformFlags |= 16777216 /* TransformFlags.ContainsClassFields */; + return node; + } // @api function createPrivateIdentifier(text) { if (!ts.startsWith(text, "#")) ts.Debug.fail("First character of private identifier must be #: " + text); - var node = baseFactory.createBasePrivateIdentifierNode(80 /* SyntaxKind.PrivateIdentifier */); - node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 16777216 /* TransformFlags.ContainsClassFields */; + return createBasePrivateIdentifier(text); + } + function createBaseGeneratedPrivateIdentifier(text, autoGenerateFlags, prefix, suffix) { + var node = createBasePrivateIdentifier(text); + node.autoGenerateFlags = autoGenerateFlags; + node.autoGenerateId = nextAutoGenerateId; + node.autoGeneratePrefix = prefix; + node.autoGenerateSuffix = suffix; + nextAutoGenerateId++; return node; } + /** Create a unique name based on the supplied text. */ + // @api + function createUniquePrivateName(text, prefix, suffix) { + if (text && !ts.startsWith(text, "#")) + ts.Debug.fail("First character of private identifier must be #: " + text); + var autoGenerateFlags = 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */ | + (text ? 3 /* GeneratedIdentifierFlags.Unique */ : 1 /* GeneratedIdentifierFlags.Auto */); + return createBaseGeneratedPrivateIdentifier(text !== null && text !== void 0 ? text : "", autoGenerateFlags, prefix, suffix); + } + // @api + function getGeneratedPrivateNameForNode(node, prefix, suffix) { + var text = ts.isMemberName(node) ? ts.formatGeneratedName(/*privateName*/ true, prefix, node, suffix, ts.idText) : + "#generated@".concat(ts.getNodeId(node)); + var flags = prefix || suffix ? 16 /* GeneratedIdentifierFlags.Optimistic */ : 0 /* GeneratedIdentifierFlags.None */; + var name = createBaseGeneratedPrivateIdentifier(text, 4 /* GeneratedIdentifierFlags.Node */ | flags, prefix, suffix); + name.original = node; + return name; + } // // Punctuation // @@ -23282,14 +23286,14 @@ var ts; return baseFactory.createBaseTokenNode(kind); } function createToken(token) { - ts.Debug.assert(token >= 0 /* SyntaxKind.FirstToken */ && token <= 160 /* SyntaxKind.LastToken */, "Invalid token"); + ts.Debug.assert(token >= 0 /* SyntaxKind.FirstToken */ && token <= 162 /* SyntaxKind.LastToken */, "Invalid token"); ts.Debug.assert(token <= 14 /* SyntaxKind.FirstTemplateToken */ || token >= 17 /* SyntaxKind.LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals."); ts.Debug.assert(token <= 8 /* SyntaxKind.FirstLiteralToken */ || token >= 14 /* SyntaxKind.LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals."); ts.Debug.assert(token !== 79 /* SyntaxKind.Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers"); var node = createBaseToken(token); var transformFlags = 0 /* TransformFlags.None */; switch (token) { - case 131 /* SyntaxKind.AsyncKeyword */: + case 132 /* SyntaxKind.AsyncKeyword */: // 'async' modifier is ES2017 (async functions) or ES2018 (async generators) transformFlags = 256 /* TransformFlags.ContainsES2017 */ | @@ -23298,24 +23302,24 @@ var ts; case 123 /* SyntaxKind.PublicKeyword */: case 121 /* SyntaxKind.PrivateKeyword */: case 122 /* SyntaxKind.ProtectedKeyword */: - case 145 /* SyntaxKind.ReadonlyKeyword */: + case 146 /* SyntaxKind.ReadonlyKeyword */: case 126 /* SyntaxKind.AbstractKeyword */: - case 135 /* SyntaxKind.DeclareKeyword */: + case 136 /* SyntaxKind.DeclareKeyword */: case 85 /* SyntaxKind.ConstKeyword */: - case 130 /* SyntaxKind.AnyKeyword */: - case 147 /* SyntaxKind.NumberKeyword */: - case 158 /* SyntaxKind.BigIntKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: - case 148 /* SyntaxKind.ObjectKeyword */: + case 131 /* SyntaxKind.AnyKeyword */: + case 148 /* SyntaxKind.NumberKeyword */: + case 160 /* SyntaxKind.BigIntKeyword */: + case 144 /* SyntaxKind.NeverKeyword */: + case 149 /* SyntaxKind.ObjectKeyword */: case 101 /* SyntaxKind.InKeyword */: - case 144 /* SyntaxKind.OutKeyword */: - case 159 /* SyntaxKind.OverrideKeyword */: - case 150 /* SyntaxKind.StringKeyword */: - case 133 /* SyntaxKind.BooleanKeyword */: - case 151 /* SyntaxKind.SymbolKeyword */: + case 145 /* SyntaxKind.OutKeyword */: + case 161 /* SyntaxKind.OverrideKeyword */: + case 152 /* SyntaxKind.StringKeyword */: + case 134 /* SyntaxKind.BooleanKeyword */: + case 153 /* SyntaxKind.SymbolKeyword */: case 114 /* SyntaxKind.VoidKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: // `undefined` is an Identifier in the expression case. + case 157 /* SyntaxKind.UnknownKeyword */: + case 155 /* SyntaxKind.UndefinedKeyword */: // `undefined` is an Identifier in the expression case. transformFlags = 1 /* TransformFlags.ContainsTypeScript */; break; case 106 /* SyntaxKind.SuperKeyword */: @@ -23324,6 +23328,9 @@ var ts; case 124 /* SyntaxKind.StaticKeyword */: transformFlags = 1024 /* TransformFlags.ContainsES2015 */; break; + case 127 /* SyntaxKind.AccessorKeyword */: + transformFlags = 16777216 /* TransformFlags.ContainsClassFields */; + break; case 108 /* SyntaxKind.ThisKeyword */: // 'this' indicates a lexical 'this' transformFlags = 16384 /* TransformFlags.ContainsLexicalThis */; @@ -23370,8 +23377,8 @@ var ts; if (flags & 1 /* ModifierFlags.Export */) result.push(createModifier(93 /* SyntaxKind.ExportKeyword */)); if (flags & 2 /* ModifierFlags.Ambient */) - result.push(createModifier(135 /* SyntaxKind.DeclareKeyword */)); - if (flags & 512 /* ModifierFlags.Default */) + result.push(createModifier(136 /* SyntaxKind.DeclareKeyword */)); + if (flags & 1024 /* ModifierFlags.Default */) result.push(createModifier(88 /* SyntaxKind.DefaultKeyword */)); if (flags & 2048 /* ModifierFlags.Const */) result.push(createModifier(85 /* SyntaxKind.ConstKeyword */)); @@ -23381,20 +23388,22 @@ var ts; result.push(createModifier(121 /* SyntaxKind.PrivateKeyword */)); if (flags & 16 /* ModifierFlags.Protected */) result.push(createModifier(122 /* SyntaxKind.ProtectedKeyword */)); - if (flags & 128 /* ModifierFlags.Abstract */) + if (flags & 256 /* ModifierFlags.Abstract */) result.push(createModifier(126 /* SyntaxKind.AbstractKeyword */)); if (flags & 32 /* ModifierFlags.Static */) result.push(createModifier(124 /* SyntaxKind.StaticKeyword */)); if (flags & 16384 /* ModifierFlags.Override */) - result.push(createModifier(159 /* SyntaxKind.OverrideKeyword */)); + result.push(createModifier(161 /* SyntaxKind.OverrideKeyword */)); if (flags & 64 /* ModifierFlags.Readonly */) - result.push(createModifier(145 /* SyntaxKind.ReadonlyKeyword */)); - if (flags & 256 /* ModifierFlags.Async */) - result.push(createModifier(131 /* SyntaxKind.AsyncKeyword */)); + result.push(createModifier(146 /* SyntaxKind.ReadonlyKeyword */)); + if (flags & 128 /* ModifierFlags.Accessor */) + result.push(createModifier(127 /* SyntaxKind.AccessorKeyword */)); + if (flags & 512 /* ModifierFlags.Async */) + result.push(createModifier(132 /* SyntaxKind.AsyncKeyword */)); if (flags & 32768 /* ModifierFlags.In */) result.push(createModifier(101 /* SyntaxKind.InKeyword */)); if (flags & 65536 /* ModifierFlags.Out */) - result.push(createModifier(144 /* SyntaxKind.OutKeyword */)); + result.push(createModifier(145 /* SyntaxKind.OutKeyword */)); return result.length ? result : undefined; } // @@ -23402,7 +23411,7 @@ var ts; // // @api function createQualifiedName(left, right) { - var node = createBaseNode(161 /* SyntaxKind.QualifiedName */); + var node = createBaseNode(163 /* SyntaxKind.QualifiedName */); node.left = left; node.right = asName(right); node.transformFlags |= @@ -23419,7 +23428,7 @@ var ts; } // @api function createComputedPropertyName(expression) { - var node = createBaseNode(162 /* SyntaxKind.ComputedPropertyName */); + var node = createBaseNode(164 /* SyntaxKind.ComputedPropertyName */); node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); node.transformFlags |= propagateChildFlags(node.expression) | @@ -23438,7 +23447,7 @@ var ts; // // @api function createTypeParameterDeclaration(modifiers, name, constraint, defaultType) { - var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, modifiers, name); + var node = createBaseNamedDeclaration(165 /* SyntaxKind.TypeParameter */, modifiers, name); node.constraint = constraint; node.default = defaultType; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23455,7 +23464,7 @@ var ts; } // @api function createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + var node = createBaseVariableLikeDeclaration(166 /* SyntaxKind.Parameter */, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -23487,7 +23496,7 @@ var ts; } // @api function createDecorator(expression) { - var node = createBaseNode(165 /* SyntaxKind.Decorator */); + var node = createBaseNode(167 /* SyntaxKind.Decorator */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | @@ -23507,7 +23516,7 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, modifiers, name); + var node = createBaseNamedDeclaration(168 /* SyntaxKind.PropertySignature */, modifiers, name); node.type = type; node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23533,7 +23542,7 @@ var ts; } // @api function createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, modifiers, name, type, initializer); + var node = createBaseVariableLikeDeclaration(169 /* SyntaxKind.PropertyDeclaration */, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= @@ -23561,7 +23570,7 @@ var ts; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, modifiers, name, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(170 /* SyntaxKind.MethodSignature */, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23579,7 +23588,7 @@ var ts; } // @api function createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.MethodDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= @@ -23589,7 +23598,7 @@ var ts; if (questionToken) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } - if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { + if (ts.modifiersToFlags(node.modifiers) & 512 /* ModifierFlags.Async */) { if (asteriskToken) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */; } @@ -23625,7 +23634,7 @@ var ts; } // @api function createClassStaticBlockDeclaration(body) { - var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, + var node = createBaseGenericNamedDeclaration(172 /* SyntaxKind.ClassStaticBlockDeclaration */, /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined); @@ -23651,7 +23660,7 @@ var ts; } // @api function createConstructorDeclaration(modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, modifiers, + var node = createBaseFunctionLikeDeclaration(173 /* SyntaxKind.Constructor */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); @@ -23680,7 +23689,7 @@ var ts; } // @api function createGetAccessorDeclaration(modifiers, name, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, modifiers, name, + var node = createBaseFunctionLikeDeclaration(174 /* SyntaxKind.GetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); // The following properties are used only to report grammar errors node.typeParameters = undefined; @@ -23704,7 +23713,7 @@ var ts; } // @api function createSetAccessorDeclaration(modifiers, name, parameters, body) { - var node = createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, modifiers, name, + var node = createBaseFunctionLikeDeclaration(175 /* SyntaxKind.SetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); // The following properties are used only to report grammar errors @@ -23730,7 +23739,7 @@ var ts; } // @api function createCallSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(174 /* SyntaxKind.CallSignature */, + var node = createBaseSignatureDeclaration(176 /* SyntaxKind.CallSignature */, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23746,7 +23755,7 @@ var ts; } // @api function createConstructSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(175 /* SyntaxKind.ConstructSignature */, + var node = createBaseSignatureDeclaration(177 /* SyntaxKind.ConstructSignature */, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23762,7 +23771,7 @@ var ts; } // @api function createIndexSignature(modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, modifiers, + var node = createBaseSignatureDeclaration(178 /* SyntaxKind.IndexSignature */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23778,7 +23787,7 @@ var ts; } // @api function createTemplateLiteralTypeSpan(type, literal) { - var node = createBaseNode(199 /* SyntaxKind.TemplateLiteralTypeSpan */); + var node = createBaseNode(201 /* SyntaxKind.TemplateLiteralTypeSpan */); node.type = type; node.literal = literal; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23800,7 +23809,7 @@ var ts; } // @api function createTypePredicateNode(assertsModifier, parameterName, type) { - var node = createBaseNode(177 /* SyntaxKind.TypePredicate */); + var node = createBaseNode(179 /* SyntaxKind.TypePredicate */); node.assertsModifier = assertsModifier; node.parameterName = asName(parameterName); node.type = type; @@ -23817,7 +23826,7 @@ var ts; } // @api function createTypeReferenceNode(typeName, typeArguments) { - var node = createBaseNode(178 /* SyntaxKind.TypeReference */); + var node = createBaseNode(180 /* SyntaxKind.TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments)); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23832,7 +23841,7 @@ var ts; } // @api function createFunctionTypeNode(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(179 /* SyntaxKind.FunctionType */, + var node = createBaseSignatureDeclaration(181 /* SyntaxKind.FunctionType */, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23865,7 +23874,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, modifiers, + var node = createBaseSignatureDeclaration(182 /* SyntaxKind.ConstructorType */, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23898,7 +23907,7 @@ var ts; } // @api function createTypeQueryNode(exprName, typeArguments) { - var node = createBaseNode(181 /* SyntaxKind.TypeQuery */); + var node = createBaseNode(183 /* SyntaxKind.TypeQuery */); node.exprName = exprName; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23913,7 +23922,7 @@ var ts; } // @api function createTypeLiteralNode(members) { - var node = createBaseNode(182 /* SyntaxKind.TypeLiteral */); + var node = createBaseNode(184 /* SyntaxKind.TypeLiteral */); node.members = createNodeArray(members); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23926,7 +23935,7 @@ var ts; } // @api function createArrayTypeNode(elementType) { - var node = createBaseNode(183 /* SyntaxKind.ArrayType */); + var node = createBaseNode(185 /* SyntaxKind.ArrayType */); node.elementType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(elementType); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23939,7 +23948,7 @@ var ts; } // @api function createTupleTypeNode(elements) { - var node = createBaseNode(184 /* SyntaxKind.TupleType */); + var node = createBaseNode(186 /* SyntaxKind.TupleType */); node.elements = createNodeArray(parenthesizerRules().parenthesizeElementTypesOfTupleType(elements)); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23952,7 +23961,7 @@ var ts; } // @api function createNamedTupleMember(dotDotDotToken, name, questionToken, type) { - var node = createBaseNode(197 /* SyntaxKind.NamedTupleMember */); + var node = createBaseNode(199 /* SyntaxKind.NamedTupleMember */); node.dotDotDotToken = dotDotDotToken; node.name = name; node.questionToken = questionToken; @@ -23971,7 +23980,7 @@ var ts; } // @api function createOptionalTypeNode(type) { - var node = createBaseNode(185 /* SyntaxKind.OptionalType */); + var node = createBaseNode(187 /* SyntaxKind.OptionalType */); node.type = parenthesizerRules().parenthesizeTypeOfOptionalType(type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23984,7 +23993,7 @@ var ts; } // @api function createRestTypeNode(type) { - var node = createBaseNode(186 /* SyntaxKind.RestType */); + var node = createBaseNode(188 /* SyntaxKind.RestType */); node.type = type; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -24008,7 +24017,7 @@ var ts; } // @api function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(187 /* SyntaxKind.UnionType */, types, parenthesizerRules().parenthesizeConstituentTypesOfUnionType); + return createUnionOrIntersectionTypeNode(189 /* SyntaxKind.UnionType */, types, parenthesizerRules().parenthesizeConstituentTypesOfUnionType); } // @api function updateUnionTypeNode(node, types) { @@ -24016,7 +24025,7 @@ var ts; } // @api function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(188 /* SyntaxKind.IntersectionType */, types, parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType); + return createUnionOrIntersectionTypeNode(190 /* SyntaxKind.IntersectionType */, types, parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType); } // @api function updateIntersectionTypeNode(node, types) { @@ -24024,7 +24033,7 @@ var ts; } // @api function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createBaseNode(189 /* SyntaxKind.ConditionalType */); + var node = createBaseNode(191 /* SyntaxKind.ConditionalType */); node.checkType = parenthesizerRules().parenthesizeCheckTypeOfConditionalType(checkType); node.extendsType = parenthesizerRules().parenthesizeExtendsTypeOfConditionalType(extendsType); node.trueType = trueType; @@ -24043,7 +24052,7 @@ var ts; } // @api function createInferTypeNode(typeParameter) { - var node = createBaseNode(190 /* SyntaxKind.InferType */); + var node = createBaseNode(192 /* SyntaxKind.InferType */); node.typeParameter = typeParameter; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -24056,7 +24065,7 @@ var ts; } // @api function createTemplateLiteralType(head, templateSpans) { - var node = createBaseNode(198 /* SyntaxKind.TemplateLiteralType */); + var node = createBaseNode(200 /* SyntaxKind.TemplateLiteralType */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -24072,7 +24081,7 @@ var ts; // @api function createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf) { if (isTypeOf === void 0) { isTypeOf = false; } - var node = createBaseNode(200 /* SyntaxKind.ImportType */); + var node = createBaseNode(202 /* SyntaxKind.ImportType */); node.argument = argument; node.assertions = assertions; node.qualifier = qualifier; @@ -24094,7 +24103,7 @@ var ts; } // @api function createParenthesizedType(type) { - var node = createBaseNode(191 /* SyntaxKind.ParenthesizedType */); + var node = createBaseNode(193 /* SyntaxKind.ParenthesizedType */); node.type = type; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -24107,15 +24116,15 @@ var ts; } // @api function createThisTypeNode() { - var node = createBaseNode(192 /* SyntaxKind.ThisType */); + var node = createBaseNode(194 /* SyntaxKind.ThisType */); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } // @api function createTypeOperatorNode(operator, type) { - var node = createBaseNode(193 /* SyntaxKind.TypeOperator */); + var node = createBaseNode(195 /* SyntaxKind.TypeOperator */); node.operator = operator; - node.type = operator === 145 /* SyntaxKind.ReadonlyKeyword */ ? + node.type = operator === 146 /* SyntaxKind.ReadonlyKeyword */ ? parenthesizerRules().parenthesizeOperandOfReadonlyTypeOperator(type) : parenthesizerRules().parenthesizeOperandOfTypeOperator(type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -24129,7 +24138,7 @@ var ts; } // @api function createIndexedAccessTypeNode(objectType, indexType) { - var node = createBaseNode(194 /* SyntaxKind.IndexedAccessType */); + var node = createBaseNode(196 /* SyntaxKind.IndexedAccessType */); node.objectType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(objectType); node.indexType = indexType; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -24144,7 +24153,7 @@ var ts; } // @api function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) { - var node = createBaseNode(195 /* SyntaxKind.MappedType */); + var node = createBaseNode(197 /* SyntaxKind.MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; @@ -24167,7 +24176,7 @@ var ts; } // @api function createLiteralTypeNode(literal) { - var node = createBaseNode(196 /* SyntaxKind.LiteralType */); + var node = createBaseNode(198 /* SyntaxKind.LiteralType */); node.literal = literal; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -24183,7 +24192,7 @@ var ts; // // @api function createObjectBindingPattern(elements) { - var node = createBaseNode(201 /* SyntaxKind.ObjectBindingPattern */); + var node = createBaseNode(203 /* SyntaxKind.ObjectBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | @@ -24204,7 +24213,7 @@ var ts; } // @api function createArrayBindingPattern(elements) { - var node = createBaseNode(202 /* SyntaxKind.ArrayBindingPattern */); + var node = createBaseNode(204 /* SyntaxKind.ArrayBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | @@ -24220,7 +24229,7 @@ var ts; } // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createBaseBindingLikeDeclaration(203 /* SyntaxKind.BindingElement */, + var node = createBaseBindingLikeDeclaration(205 /* SyntaxKind.BindingElement */, /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; @@ -24255,7 +24264,7 @@ var ts; } // @api function createArrayLiteralExpression(elements, multiLine) { - var node = createBaseExpression(204 /* SyntaxKind.ArrayLiteralExpression */); + var node = createBaseExpression(206 /* SyntaxKind.ArrayLiteralExpression */); // Ensure we add a trailing comma for something like `[NumericLiteral(1), NumericLiteral(2), OmittedExpresion]` so that // we end up with `[1, 2, ,]` instead of `[1, 2, ]` otherwise the `OmittedExpression` will just end up being treated like // a trailing comma. @@ -24274,7 +24283,7 @@ var ts; } // @api function createObjectLiteralExpression(properties, multiLine) { - var node = createBaseExpression(205 /* SyntaxKind.ObjectLiteralExpression */); + var node = createBaseExpression(207 /* SyntaxKind.ObjectLiteralExpression */); node.properties = createNodeArray(properties); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.properties); @@ -24288,7 +24297,7 @@ var ts; } // @api function createPropertyAccessExpression(expression, name) { - var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); + var node = createBaseExpression(208 /* SyntaxKind.PropertyAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.name = asName(name); node.transformFlags = @@ -24317,7 +24326,7 @@ var ts; } // @api function createPropertyAccessChain(expression, questionDotToken, name) { - var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); + var node = createBaseExpression(208 /* SyntaxKind.PropertyAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; @@ -24344,7 +24353,7 @@ var ts; } // @api function createElementAccessExpression(expression, index) { - var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); + var node = createBaseExpression(209 /* SyntaxKind.ElementAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.argumentExpression = asExpression(index); node.transformFlags |= @@ -24371,7 +24380,7 @@ var ts; } // @api function createElementAccessChain(expression, questionDotToken, index) { - var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); + var node = createBaseExpression(209 /* SyntaxKind.ElementAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; @@ -24396,7 +24405,7 @@ var ts; } // @api function createCallExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); + var node = createBaseExpression(210 /* SyntaxKind.CallExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -24428,7 +24437,7 @@ var ts; } // @api function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { - var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); + var node = createBaseExpression(210 /* SyntaxKind.CallExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; @@ -24460,7 +24469,7 @@ var ts; } // @api function createNewExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(209 /* SyntaxKind.NewExpression */); + var node = createBaseExpression(211 /* SyntaxKind.NewExpression */); node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined; @@ -24484,7 +24493,7 @@ var ts; } // @api function createTaggedTemplateExpression(tag, typeArguments, template) { - var node = createBaseExpression(210 /* SyntaxKind.TaggedTemplateExpression */); + var node = createBaseExpression(212 /* SyntaxKind.TaggedTemplateExpression */); node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.template = template; @@ -24511,7 +24520,7 @@ var ts; } // @api function createTypeAssertion(type, expression) { - var node = createBaseExpression(211 /* SyntaxKind.TypeAssertionExpression */); + var node = createBaseExpression(213 /* SyntaxKind.TypeAssertionExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.type = type; node.transformFlags |= @@ -24529,7 +24538,7 @@ var ts; } // @api function createParenthesizedExpression(expression) { - var node = createBaseExpression(212 /* SyntaxKind.ParenthesizedExpression */); + var node = createBaseExpression(214 /* SyntaxKind.ParenthesizedExpression */); node.expression = expression; node.transformFlags = propagateChildFlags(node.expression); return node; @@ -24542,13 +24551,13 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(215 /* SyntaxKind.FunctionExpression */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); if (node.typeParameters) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } - if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { + if (ts.modifiersToFlags(node.modifiers) & 512 /* ModifierFlags.Async */) { if (node.asteriskToken) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */; } @@ -24575,13 +24584,13 @@ var ts; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, modifiers, + var node = createBaseFunctionLikeDeclaration(216 /* SyntaxKind.ArrowFunction */, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* SyntaxKind.EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | 1024 /* TransformFlags.ContainsES2015 */; - if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { + if (ts.modifiersToFlags(node.modifiers) & 512 /* ModifierFlags.Async */) { node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 16384 /* TransformFlags.ContainsLexicalThis */; } return node; @@ -24599,7 +24608,7 @@ var ts; } // @api function createDeleteExpression(expression) { - var node = createBaseExpression(215 /* SyntaxKind.DeleteExpression */); + var node = createBaseExpression(217 /* SyntaxKind.DeleteExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -24612,7 +24621,7 @@ var ts; } // @api function createTypeOfExpression(expression) { - var node = createBaseExpression(216 /* SyntaxKind.TypeOfExpression */); + var node = createBaseExpression(218 /* SyntaxKind.TypeOfExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -24625,7 +24634,7 @@ var ts; } // @api function createVoidExpression(expression) { - var node = createBaseExpression(217 /* SyntaxKind.VoidExpression */); + var node = createBaseExpression(219 /* SyntaxKind.VoidExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -24638,7 +24647,7 @@ var ts; } // @api function createAwaitExpression(expression) { - var node = createBaseExpression(218 /* SyntaxKind.AwaitExpression */); + var node = createBaseExpression(220 /* SyntaxKind.AwaitExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression) | @@ -24655,7 +24664,7 @@ var ts; } // @api function createPrefixUnaryExpression(operator, operand) { - var node = createBaseExpression(219 /* SyntaxKind.PrefixUnaryExpression */); + var node = createBaseExpression(221 /* SyntaxKind.PrefixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); @@ -24677,7 +24686,7 @@ var ts; } // @api function createPostfixUnaryExpression(operand, operator) { - var node = createBaseExpression(220 /* SyntaxKind.PostfixUnaryExpression */); + var node = createBaseExpression(222 /* SyntaxKind.PostfixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); @@ -24698,7 +24707,7 @@ var ts; } // @api function createBinaryExpression(left, operator, right) { - var node = createBaseExpression(221 /* SyntaxKind.BinaryExpression */); + var node = createBaseExpression(223 /* SyntaxKind.BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left); @@ -24770,7 +24779,7 @@ var ts; } // @api function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) { - var node = createBaseExpression(222 /* SyntaxKind.ConditionalExpression */); + var node = createBaseExpression(224 /* SyntaxKind.ConditionalExpression */); node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition); node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* SyntaxKind.QuestionToken */); node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); @@ -24796,7 +24805,7 @@ var ts; } // @api function createTemplateExpression(head, templateSpans) { - var node = createBaseExpression(223 /* SyntaxKind.TemplateExpression */); + var node = createBaseExpression(225 /* SyntaxKind.TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags |= @@ -24866,7 +24875,7 @@ var ts; // @api function createYieldExpression(asteriskToken, expression) { ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression."); - var node = createBaseExpression(224 /* SyntaxKind.YieldExpression */); + var node = createBaseExpression(226 /* SyntaxKind.YieldExpression */); node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.asteriskToken = asteriskToken; node.transformFlags |= @@ -24886,7 +24895,7 @@ var ts; } // @api function createSpreadElement(expression) { - var node = createBaseExpression(225 /* SyntaxKind.SpreadElement */); + var node = createBaseExpression(227 /* SyntaxKind.SpreadElement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | @@ -24902,7 +24911,7 @@ var ts; } // @api function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, modifiers, name, typeParameters, heritageClauses, members); + var node = createBaseClassLikeDeclaration(228 /* SyntaxKind.ClassExpression */, modifiers, name, typeParameters, heritageClauses, members); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; return node; } @@ -24918,11 +24927,11 @@ var ts; } // @api function createOmittedExpression() { - return createBaseExpression(227 /* SyntaxKind.OmittedExpression */); + return createBaseExpression(229 /* SyntaxKind.OmittedExpression */); } // @api function createExpressionWithTypeArguments(expression, typeArguments) { - var node = createBaseNode(228 /* SyntaxKind.ExpressionWithTypeArguments */); + var node = createBaseNode(230 /* SyntaxKind.ExpressionWithTypeArguments */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= @@ -24940,7 +24949,7 @@ var ts; } // @api function createAsExpression(expression, type) { - var node = createBaseExpression(229 /* SyntaxKind.AsExpression */); + var node = createBaseExpression(231 /* SyntaxKind.AsExpression */); node.expression = expression; node.type = type; node.transformFlags |= @@ -24958,7 +24967,7 @@ var ts; } // @api function createNonNullExpression(expression) { - var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); + var node = createBaseExpression(232 /* SyntaxKind.NonNullExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | @@ -24975,8 +24984,26 @@ var ts; : node; } // @api + function createSatisfiesExpression(expression, type) { + var node = createBaseExpression(235 /* SyntaxKind.SatisfiesExpression */); + node.expression = expression; + node.type = type; + node.transformFlags |= + propagateChildFlags(node.expression) | + propagateChildFlags(node.type) | + 1 /* TransformFlags.ContainsTypeScript */; + return node; + } + // @api + function updateSatisfiesExpression(node, expression, type) { + return node.expression !== expression + || node.type !== type + ? update(createSatisfiesExpression(expression, type), node) + : node; + } + // @api function createNonNullChain(expression) { - var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); + var node = createBaseExpression(232 /* SyntaxKind.NonNullExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.transformFlags |= @@ -24993,7 +25020,7 @@ var ts; } // @api function createMetaProperty(keywordToken, name) { - var node = createBaseExpression(231 /* SyntaxKind.MetaProperty */); + var node = createBaseExpression(233 /* SyntaxKind.MetaProperty */); node.keywordToken = keywordToken; node.name = name; node.transformFlags |= propagateChildFlags(node.name); @@ -25020,7 +25047,7 @@ var ts; // // @api function createTemplateSpan(expression, literal) { - var node = createBaseNode(233 /* SyntaxKind.TemplateSpan */); + var node = createBaseNode(236 /* SyntaxKind.TemplateSpan */); node.expression = expression; node.literal = literal; node.transformFlags |= @@ -25038,7 +25065,7 @@ var ts; } // @api function createSemicolonClassElement() { - var node = createBaseNode(234 /* SyntaxKind.SemicolonClassElement */); + var node = createBaseNode(237 /* SyntaxKind.SemicolonClassElement */); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; return node; } @@ -25047,7 +25074,7 @@ var ts; // // @api function createBlock(statements, multiLine) { - var node = createBaseNode(235 /* SyntaxKind.Block */); + var node = createBaseNode(238 /* SyntaxKind.Block */); node.statements = createNodeArray(statements); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.statements); @@ -25061,7 +25088,7 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */); + var node = createBaseDeclaration(240 /* SyntaxKind.VariableStatement */); node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= @@ -25081,11 +25108,11 @@ var ts; } // @api function createEmptyStatement() { - return createBaseNode(236 /* SyntaxKind.EmptyStatement */); + return createBaseNode(239 /* SyntaxKind.EmptyStatement */); } // @api function createExpressionStatement(expression) { - var node = createBaseNode(238 /* SyntaxKind.ExpressionStatement */); + var node = createBaseNode(241 /* SyntaxKind.ExpressionStatement */); node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -25098,7 +25125,7 @@ var ts; } // @api function createIfStatement(expression, thenStatement, elseStatement) { - var node = createBaseNode(239 /* SyntaxKind.IfStatement */); + var node = createBaseNode(242 /* SyntaxKind.IfStatement */); node.expression = expression; node.thenStatement = asEmbeddedStatement(thenStatement); node.elseStatement = asEmbeddedStatement(elseStatement); @@ -25118,7 +25145,7 @@ var ts; } // @api function createDoStatement(statement, expression) { - var node = createBaseNode(240 /* SyntaxKind.DoStatement */); + var node = createBaseNode(243 /* SyntaxKind.DoStatement */); node.statement = asEmbeddedStatement(statement); node.expression = expression; node.transformFlags |= @@ -25135,7 +25162,7 @@ var ts; } // @api function createWhileStatement(expression, statement) { - var node = createBaseNode(241 /* SyntaxKind.WhileStatement */); + var node = createBaseNode(244 /* SyntaxKind.WhileStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -25152,7 +25179,7 @@ var ts; } // @api function createForStatement(initializer, condition, incrementor, statement) { - var node = createBaseNode(242 /* SyntaxKind.ForStatement */); + var node = createBaseNode(245 /* SyntaxKind.ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -25175,7 +25202,7 @@ var ts; } // @api function createForInStatement(initializer, expression, statement) { - var node = createBaseNode(243 /* SyntaxKind.ForInStatement */); + var node = createBaseNode(246 /* SyntaxKind.ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = asEmbeddedStatement(statement); @@ -25195,7 +25222,7 @@ var ts; } // @api function createForOfStatement(awaitModifier, initializer, expression, statement) { - var node = createBaseNode(244 /* SyntaxKind.ForOfStatement */); + var node = createBaseNode(247 /* SyntaxKind.ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); @@ -25221,7 +25248,7 @@ var ts; } // @api function createContinueStatement(label) { - var node = createBaseNode(245 /* SyntaxKind.ContinueStatement */); + var node = createBaseNode(248 /* SyntaxKind.ContinueStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | @@ -25236,7 +25263,7 @@ var ts; } // @api function createBreakStatement(label) { - var node = createBaseNode(246 /* SyntaxKind.BreakStatement */); + var node = createBaseNode(249 /* SyntaxKind.BreakStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | @@ -25251,7 +25278,7 @@ var ts; } // @api function createReturnStatement(expression) { - var node = createBaseNode(247 /* SyntaxKind.ReturnStatement */); + var node = createBaseNode(250 /* SyntaxKind.ReturnStatement */); node.expression = expression; // return in an ES2018 async generator must be awaited node.transformFlags |= @@ -25268,7 +25295,7 @@ var ts; } // @api function createWithStatement(expression, statement) { - var node = createBaseNode(248 /* SyntaxKind.WithStatement */); + var node = createBaseNode(251 /* SyntaxKind.WithStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -25285,7 +25312,7 @@ var ts; } // @api function createSwitchStatement(expression, caseBlock) { - var node = createBaseNode(249 /* SyntaxKind.SwitchStatement */); + var node = createBaseNode(252 /* SyntaxKind.SwitchStatement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.caseBlock = caseBlock; node.transformFlags |= @@ -25302,7 +25329,7 @@ var ts; } // @api function createLabeledStatement(label, statement) { - var node = createBaseNode(250 /* SyntaxKind.LabeledStatement */); + var node = createBaseNode(253 /* SyntaxKind.LabeledStatement */); node.label = asName(label); node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -25319,7 +25346,7 @@ var ts; } // @api function createThrowStatement(expression) { - var node = createBaseNode(251 /* SyntaxKind.ThrowStatement */); + var node = createBaseNode(254 /* SyntaxKind.ThrowStatement */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -25332,7 +25359,7 @@ var ts; } // @api function createTryStatement(tryBlock, catchClause, finallyBlock) { - var node = createBaseNode(252 /* SyntaxKind.TryStatement */); + var node = createBaseNode(255 /* SyntaxKind.TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -25352,11 +25379,11 @@ var ts; } // @api function createDebuggerStatement() { - return createBaseNode(253 /* SyntaxKind.DebuggerStatement */); + return createBaseNode(256 /* SyntaxKind.DebuggerStatement */); } // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(254 /* SyntaxKind.VariableDeclaration */, + var node = createBaseVariableLikeDeclaration(257 /* SyntaxKind.VariableDeclaration */, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; node.transformFlags |= propagateChildFlags(node.exclamationToken); @@ -25377,7 +25404,7 @@ var ts; // @api function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* NodeFlags.None */; } - var node = createBaseNode(255 /* SyntaxKind.VariableDeclarationList */); + var node = createBaseNode(258 /* SyntaxKind.VariableDeclarationList */); node.flags |= flags & 3 /* NodeFlags.BlockScoped */; node.declarations = createNodeArray(declarations); node.transformFlags |= @@ -25398,7 +25425,7 @@ var ts; } // @api function createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(259 /* SyntaxKind.FunctionDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -25407,7 +25434,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.asteriskToken) | 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; - if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { + if (ts.modifiersToFlags(node.modifiers) & 512 /* ModifierFlags.Async */) { if (node.asteriskToken) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */; } @@ -25444,7 +25471,7 @@ var ts; } // @api function createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, modifiers, name, typeParameters, heritageClauses, members); + var node = createBaseClassLikeDeclaration(260 /* SyntaxKind.ClassDeclaration */, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } @@ -25468,7 +25495,7 @@ var ts; } // @api function createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, modifiers, name, typeParameters, heritageClauses); + var node = createBaseInterfaceOrClassLikeDeclaration(261 /* SyntaxKind.InterfaceDeclaration */, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; // The following properties are used only to report grammar errors @@ -25493,7 +25520,7 @@ var ts; } // @api function createTypeAliasDeclaration(modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, modifiers, name, typeParameters); + var node = createBaseGenericNamedDeclaration(262 /* SyntaxKind.TypeAliasDeclaration */, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; // The following properties are used only to report grammar errors @@ -25517,7 +25544,7 @@ var ts; } // @api function createEnumDeclaration(modifiers, name, members) { - var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, modifiers, name); + var node = createBaseNamedDeclaration(263 /* SyntaxKind.EnumDeclaration */, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | @@ -25544,7 +25571,7 @@ var ts; // @api function createModuleDeclaration(modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* NodeFlags.None */; } - var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */); + var node = createBaseDeclaration(264 /* SyntaxKind.ModuleDeclaration */); node.modifiers = asNodeArray(modifiers); node.flags |= flags & (16 /* NodeFlags.Namespace */ | 4 /* NodeFlags.NestedNamespace */ | 1024 /* NodeFlags.GlobalAugmentation */); node.name = name; @@ -25580,7 +25607,7 @@ var ts; } // @api function createModuleBlock(statements) { - var node = createBaseNode(262 /* SyntaxKind.ModuleBlock */); + var node = createBaseNode(265 /* SyntaxKind.ModuleBlock */); node.statements = createNodeArray(statements); node.transformFlags |= propagateChildrenFlags(node.statements); return node; @@ -25593,7 +25620,7 @@ var ts; } // @api function createCaseBlock(clauses) { - var node = createBaseNode(263 /* SyntaxKind.CaseBlock */); + var node = createBaseNode(266 /* SyntaxKind.CaseBlock */); node.clauses = createNodeArray(clauses); node.transformFlags |= propagateChildrenFlags(node.clauses); return node; @@ -25606,7 +25633,7 @@ var ts; } // @api function createNamespaceExportDeclaration(name) { - var node = createBaseNamedDeclaration(264 /* SyntaxKind.NamespaceExportDeclaration */, + var node = createBaseNamedDeclaration(267 /* SyntaxKind.NamespaceExportDeclaration */, /*modifiers*/ undefined, name); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; // The following properties are used only to report grammar errors @@ -25629,7 +25656,7 @@ var ts; } // @api function createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, modifiers, name); + var node = createBaseNamedDeclaration(268 /* SyntaxKind.ImportEqualsDeclaration */, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); @@ -25657,7 +25684,7 @@ var ts; } // @api function createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */); + var node = createBaseDeclaration(269 /* SyntaxKind.ImportDeclaration */); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; @@ -25687,7 +25714,7 @@ var ts; } // @api function createImportClause(isTypeOnly, name, namedBindings) { - var node = createBaseNode(267 /* SyntaxKind.ImportClause */); + var node = createBaseNode(270 /* SyntaxKind.ImportClause */); node.isTypeOnly = isTypeOnly; node.name = name; node.namedBindings = namedBindings; @@ -25710,7 +25737,7 @@ var ts; } // @api function createAssertClause(elements, multiLine) { - var node = createBaseNode(293 /* SyntaxKind.AssertClause */); + var node = createBaseNode(296 /* SyntaxKind.AssertClause */); node.elements = createNodeArray(elements); node.multiLine = multiLine; node.transformFlags |= 4 /* TransformFlags.ContainsESNext */; @@ -25725,7 +25752,7 @@ var ts; } // @api function createAssertEntry(name, value) { - var node = createBaseNode(294 /* SyntaxKind.AssertEntry */); + var node = createBaseNode(297 /* SyntaxKind.AssertEntry */); node.name = name; node.value = value; node.transformFlags |= 4 /* TransformFlags.ContainsESNext */; @@ -25740,7 +25767,7 @@ var ts; } // @api function createImportTypeAssertionContainer(clause, multiLine) { - var node = createBaseNode(295 /* SyntaxKind.ImportTypeAssertionContainer */); + var node = createBaseNode(298 /* SyntaxKind.ImportTypeAssertionContainer */); node.assertClause = clause; node.multiLine = multiLine; return node; @@ -25754,7 +25781,7 @@ var ts; } // @api function createNamespaceImport(name) { - var node = createBaseNode(268 /* SyntaxKind.NamespaceImport */); + var node = createBaseNode(271 /* SyntaxKind.NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context @@ -25768,7 +25795,7 @@ var ts; } // @api function createNamespaceExport(name) { - var node = createBaseNode(274 /* SyntaxKind.NamespaceExport */); + var node = createBaseNode(277 /* SyntaxKind.NamespaceExport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name) | @@ -25784,7 +25811,7 @@ var ts; } // @api function createNamedImports(elements) { - var node = createBaseNode(269 /* SyntaxKind.NamedImports */); + var node = createBaseNode(272 /* SyntaxKind.NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context @@ -25798,7 +25825,7 @@ var ts; } // @api function createImportSpecifier(isTypeOnly, propertyName, name) { - var node = createBaseNode(270 /* SyntaxKind.ImportSpecifier */); + var node = createBaseNode(273 /* SyntaxKind.ImportSpecifier */); node.isTypeOnly = isTypeOnly; node.propertyName = propertyName; node.name = name; @@ -25818,7 +25845,7 @@ var ts; } // @api function createExportAssignment(modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */); + var node = createBaseDeclaration(274 /* SyntaxKind.ExportAssignment */); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals @@ -25845,7 +25872,7 @@ var ts; } // @api function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */); + var node = createBaseDeclaration(275 /* SyntaxKind.ExportDeclaration */); node.modifiers = asNodeArray(modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; @@ -25878,7 +25905,7 @@ var ts; } // @api function createNamedExports(elements) { - var node = createBaseNode(273 /* SyntaxKind.NamedExports */); + var node = createBaseNode(276 /* SyntaxKind.NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context @@ -25892,7 +25919,7 @@ var ts; } // @api function createExportSpecifier(isTypeOnly, propertyName, name) { - var node = createBaseNode(275 /* SyntaxKind.ExportSpecifier */); + var node = createBaseNode(278 /* SyntaxKind.ExportSpecifier */); node.isTypeOnly = isTypeOnly; node.propertyName = asName(propertyName); node.name = asName(name); @@ -25912,7 +25939,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */); + var node = createBaseDeclaration(279 /* SyntaxKind.MissingDeclaration */); return node; } // @@ -25920,7 +25947,7 @@ var ts; // // @api function createExternalModuleReference(expression) { - var node = createBaseNode(277 /* SyntaxKind.ExternalModuleReference */); + var node = createBaseNode(280 /* SyntaxKind.ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context @@ -25978,7 +26005,7 @@ var ts; } // @api function createJSDocFunctionType(parameters, type) { - var node = createBaseSignatureDeclaration(317 /* SyntaxKind.JSDocFunctionType */, + var node = createBaseSignatureDeclaration(320 /* SyntaxKind.JSDocFunctionType */, /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); @@ -25994,7 +26021,7 @@ var ts; // @api function createJSDocTypeLiteral(propertyTags, isArrayType) { if (isArrayType === void 0) { isArrayType = false; } - var node = createBaseNode(322 /* SyntaxKind.JSDocTypeLiteral */); + var node = createBaseNode(325 /* SyntaxKind.JSDocTypeLiteral */); node.jsDocPropertyTags = asNodeArray(propertyTags); node.isArrayType = isArrayType; return node; @@ -26008,7 +26035,7 @@ var ts; } // @api function createJSDocTypeExpression(type) { - var node = createBaseNode(309 /* SyntaxKind.JSDocTypeExpression */); + var node = createBaseNode(312 /* SyntaxKind.JSDocTypeExpression */); node.type = type; return node; } @@ -26020,7 +26047,7 @@ var ts; } // @api function createJSDocSignature(typeParameters, parameters, type) { - var node = createBaseNode(323 /* SyntaxKind.JSDocSignature */); + var node = createBaseNode(326 /* SyntaxKind.JSDocSignature */); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; @@ -26049,7 +26076,7 @@ var ts; } // @api function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) { - var node = createBaseJSDocTag(344 /* SyntaxKind.JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); + var node = createBaseJSDocTag(347 /* SyntaxKind.JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); return node; @@ -26066,7 +26093,7 @@ var ts; } // @api function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(345 /* SyntaxKind.JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); + var node = createBaseJSDocTag(348 /* SyntaxKind.JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -26084,7 +26111,7 @@ var ts; } // @api function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(340 /* SyntaxKind.JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); + var node = createBaseJSDocTag(343 /* SyntaxKind.JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -26105,7 +26132,7 @@ var ts; } // @api function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(347 /* SyntaxKind.JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); + var node = createBaseJSDocTag(350 /* SyntaxKind.JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -26126,7 +26153,7 @@ var ts; } // @api function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(338 /* SyntaxKind.JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); + var node = createBaseJSDocTag(341 /* SyntaxKind.JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -26144,7 +26171,7 @@ var ts; } // @api function createJSDocAugmentsTag(tagName, className, comment) { - var node = createBaseJSDocTag(328 /* SyntaxKind.JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); + var node = createBaseJSDocTag(331 /* SyntaxKind.JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); node.class = className; return node; } @@ -26159,13 +26186,13 @@ var ts; } // @api function createJSDocImplementsTag(tagName, className, comment) { - var node = createBaseJSDocTag(329 /* SyntaxKind.JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); + var node = createBaseJSDocTag(332 /* SyntaxKind.JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); node.class = className; return node; } // @api function createJSDocSeeTag(tagName, name, comment) { - var node = createBaseJSDocTag(346 /* SyntaxKind.JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); + var node = createBaseJSDocTag(349 /* SyntaxKind.JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); node.name = name; return node; } @@ -26179,7 +26206,7 @@ var ts; } // @api function createJSDocNameReference(name) { - var node = createBaseNode(310 /* SyntaxKind.JSDocNameReference */); + var node = createBaseNode(313 /* SyntaxKind.JSDocNameReference */); node.name = name; return node; } @@ -26191,7 +26218,7 @@ var ts; } // @api function createJSDocMemberName(left, right) { - var node = createBaseNode(311 /* SyntaxKind.JSDocMemberName */); + var node = createBaseNode(314 /* SyntaxKind.JSDocMemberName */); node.left = left; node.right = right; node.transformFlags |= @@ -26208,7 +26235,7 @@ var ts; } // @api function createJSDocLink(name, text) { - var node = createBaseNode(324 /* SyntaxKind.JSDocLink */); + var node = createBaseNode(327 /* SyntaxKind.JSDocLink */); node.name = name; node.text = text; return node; @@ -26221,7 +26248,7 @@ var ts; } // @api function createJSDocLinkCode(name, text) { - var node = createBaseNode(325 /* SyntaxKind.JSDocLinkCode */); + var node = createBaseNode(328 /* SyntaxKind.JSDocLinkCode */); node.name = name; node.text = text; return node; @@ -26234,7 +26261,7 @@ var ts; } // @api function createJSDocLinkPlain(name, text) { - var node = createBaseNode(326 /* SyntaxKind.JSDocLinkPlain */); + var node = createBaseNode(329 /* SyntaxKind.JSDocLinkPlain */); node.name = name; node.text = text; return node; @@ -26306,7 +26333,7 @@ var ts; } // @api function createJSDocUnknownTag(tagName, comment) { - var node = createBaseJSDocTag(327 /* SyntaxKind.JSDocTag */, tagName, comment); + var node = createBaseJSDocTag(330 /* SyntaxKind.JSDocTag */, tagName, comment); return node; } // @api @@ -26318,7 +26345,7 @@ var ts; } // @api function createJSDocText(text) { - var node = createBaseNode(321 /* SyntaxKind.JSDocText */); + var node = createBaseNode(324 /* SyntaxKind.JSDocText */); node.text = text; return node; } @@ -26330,7 +26357,7 @@ var ts; } // @api function createJSDocComment(comment, tags) { - var node = createBaseNode(320 /* SyntaxKind.JSDoc */); + var node = createBaseNode(323 /* SyntaxKind.JSDoc */); node.comment = comment; node.tags = asNodeArray(tags); return node; @@ -26347,7 +26374,7 @@ var ts; // // @api function createJsxElement(openingElement, children, closingElement) { - var node = createBaseNode(278 /* SyntaxKind.JsxElement */); + var node = createBaseNode(281 /* SyntaxKind.JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -26368,7 +26395,7 @@ var ts; } // @api function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createBaseNode(279 /* SyntaxKind.JsxSelfClosingElement */); + var node = createBaseNode(282 /* SyntaxKind.JsxSelfClosingElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -26392,7 +26419,7 @@ var ts; } // @api function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createBaseNode(280 /* SyntaxKind.JsxOpeningElement */); + var node = createBaseNode(283 /* SyntaxKind.JsxOpeningElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -26416,7 +26443,7 @@ var ts; } // @api function createJsxClosingElement(tagName) { - var node = createBaseNode(281 /* SyntaxKind.JsxClosingElement */); + var node = createBaseNode(284 /* SyntaxKind.JsxClosingElement */); node.tagName = tagName; node.transformFlags |= propagateChildFlags(node.tagName) | @@ -26431,7 +26458,7 @@ var ts; } // @api function createJsxFragment(openingFragment, children, closingFragment) { - var node = createBaseNode(282 /* SyntaxKind.JsxFragment */); + var node = createBaseNode(285 /* SyntaxKind.JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -26467,19 +26494,19 @@ var ts; } // @api function createJsxOpeningFragment() { - var node = createBaseNode(283 /* SyntaxKind.JsxOpeningFragment */); + var node = createBaseNode(286 /* SyntaxKind.JsxOpeningFragment */); node.transformFlags |= 2 /* TransformFlags.ContainsJsx */; return node; } // @api function createJsxJsxClosingFragment() { - var node = createBaseNode(284 /* SyntaxKind.JsxClosingFragment */); + var node = createBaseNode(287 /* SyntaxKind.JsxClosingFragment */); node.transformFlags |= 2 /* TransformFlags.ContainsJsx */; return node; } // @api function createJsxAttribute(name, initializer) { - var node = createBaseNode(285 /* SyntaxKind.JsxAttribute */); + var node = createBaseNode(288 /* SyntaxKind.JsxAttribute */); node.name = name; node.initializer = initializer; node.transformFlags |= @@ -26497,7 +26524,7 @@ var ts; } // @api function createJsxAttributes(properties) { - var node = createBaseNode(286 /* SyntaxKind.JsxAttributes */); + var node = createBaseNode(289 /* SyntaxKind.JsxAttributes */); node.properties = createNodeArray(properties); node.transformFlags |= propagateChildrenFlags(node.properties) | @@ -26512,7 +26539,7 @@ var ts; } // @api function createJsxSpreadAttribute(expression) { - var node = createBaseNode(287 /* SyntaxKind.JsxSpreadAttribute */); + var node = createBaseNode(290 /* SyntaxKind.JsxSpreadAttribute */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression) | @@ -26527,7 +26554,7 @@ var ts; } // @api function createJsxExpression(dotDotDotToken, expression) { - var node = createBaseNode(288 /* SyntaxKind.JsxExpression */); + var node = createBaseNode(291 /* SyntaxKind.JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; node.transformFlags |= @@ -26547,7 +26574,7 @@ var ts; // // @api function createCaseClause(expression, statements) { - var node = createBaseNode(289 /* SyntaxKind.CaseClause */); + var node = createBaseNode(292 /* SyntaxKind.CaseClause */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statements = createNodeArray(statements); node.transformFlags |= @@ -26564,7 +26591,7 @@ var ts; } // @api function createDefaultClause(statements) { - var node = createBaseNode(290 /* SyntaxKind.DefaultClause */); + var node = createBaseNode(293 /* SyntaxKind.DefaultClause */); node.statements = createNodeArray(statements); node.transformFlags = propagateChildrenFlags(node.statements); return node; @@ -26577,7 +26604,7 @@ var ts; } // @api function createHeritageClause(token, types) { - var node = createBaseNode(291 /* SyntaxKind.HeritageClause */); + var node = createBaseNode(294 /* SyntaxKind.HeritageClause */); node.token = token; node.types = createNodeArray(types); node.transformFlags |= propagateChildrenFlags(node.types); @@ -26601,7 +26628,7 @@ var ts; } // @api function createCatchClause(variableDeclaration, block) { - var node = createBaseNode(292 /* SyntaxKind.CatchClause */); + var node = createBaseNode(295 /* SyntaxKind.CatchClause */); if (typeof variableDeclaration === "string" || variableDeclaration && !ts.isVariableDeclaration(variableDeclaration)) { variableDeclaration = createVariableDeclaration(variableDeclaration, /*exclamationToken*/ undefined, @@ -26629,7 +26656,7 @@ var ts; // // @api function createPropertyAssignment(name, initializer) { - var node = createBaseNamedDeclaration(296 /* SyntaxKind.PropertyAssignment */, + var node = createBaseNamedDeclaration(299 /* SyntaxKind.PropertyAssignment */, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= @@ -26661,7 +26688,7 @@ var ts; } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createBaseNamedDeclaration(297 /* SyntaxKind.ShorthandPropertyAssignment */, + var node = createBaseNamedDeclaration(300 /* SyntaxKind.ShorthandPropertyAssignment */, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= @@ -26695,7 +26722,7 @@ var ts; } // @api function createSpreadAssignment(expression) { - var node = createBaseNode(298 /* SyntaxKind.SpreadAssignment */); + var node = createBaseNode(301 /* SyntaxKind.SpreadAssignment */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | @@ -26714,7 +26741,7 @@ var ts; // // @api function createEnumMember(name, initializer) { - var node = createBaseNode(299 /* SyntaxKind.EnumMember */); + var node = createBaseNode(302 /* SyntaxKind.EnumMember */); node.name = asName(name); node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= @@ -26735,7 +26762,7 @@ var ts; // // @api function createSourceFile(statements, endOfFileToken, flags) { - var node = baseFactory.createBaseSourceFileNode(305 /* SyntaxKind.SourceFile */); + var node = baseFactory.createBaseSourceFileNode(308 /* SyntaxKind.SourceFile */); node.statements = createNodeArray(statements); node.endOfFileToken = endOfFileToken; node.flags |= flags; @@ -26752,7 +26779,7 @@ var ts; return node; } function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { - var node = (source.redirectInfo ? Object.create(source.redirectInfo.redirectTarget) : baseFactory.createBaseSourceFileNode(305 /* SyntaxKind.SourceFile */)); + var node = (source.redirectInfo ? Object.create(source.redirectInfo.redirectTarget) : baseFactory.createBaseSourceFileNode(308 /* SyntaxKind.SourceFile */)); for (var p in source) { if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p)) continue; @@ -26791,7 +26818,7 @@ var ts; // @api function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = createBaseNode(306 /* SyntaxKind.Bundle */); + var node = createBaseNode(309 /* SyntaxKind.Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; @@ -26806,7 +26833,7 @@ var ts; } // @api function createUnparsedSource(prologues, syntheticReferences, texts) { - var node = createBaseNode(307 /* SyntaxKind.UnparsedSource */); + var node = createBaseNode(310 /* SyntaxKind.UnparsedSource */); node.prologues = prologues; node.syntheticReferences = syntheticReferences; node.texts = texts; @@ -26824,28 +26851,28 @@ var ts; } // @api function createUnparsedPrologue(data) { - return createBaseUnparsedNode(300 /* SyntaxKind.UnparsedPrologue */, data); + return createBaseUnparsedNode(303 /* SyntaxKind.UnparsedPrologue */, data); } // @api function createUnparsedPrepend(data, texts) { - var node = createBaseUnparsedNode(301 /* SyntaxKind.UnparsedPrepend */, data); + var node = createBaseUnparsedNode(304 /* SyntaxKind.UnparsedPrepend */, data); node.texts = texts; return node; } // @api function createUnparsedTextLike(data, internal) { - return createBaseUnparsedNode(internal ? 303 /* SyntaxKind.UnparsedInternalText */ : 302 /* SyntaxKind.UnparsedText */, data); + return createBaseUnparsedNode(internal ? 306 /* SyntaxKind.UnparsedInternalText */ : 305 /* SyntaxKind.UnparsedText */, data); } // @api function createUnparsedSyntheticReference(section) { - var node = createBaseNode(304 /* SyntaxKind.UnparsedSyntheticReference */); + var node = createBaseNode(307 /* SyntaxKind.UnparsedSyntheticReference */); node.data = section.data; node.section = section; return node; } // @api function createInputFiles() { - var node = createBaseNode(308 /* SyntaxKind.InputFiles */); + var node = createBaseNode(311 /* SyntaxKind.InputFiles */); node.javascriptText = ""; node.declarationText = ""; return node; @@ -26856,7 +26883,7 @@ var ts; // @api function createSyntheticExpression(type, isSpread, tupleNameSource) { if (isSpread === void 0) { isSpread = false; } - var node = createBaseNode(232 /* SyntaxKind.SyntheticExpression */); + var node = createBaseNode(234 /* SyntaxKind.SyntheticExpression */); node.type = type; node.isSpread = isSpread; node.tupleNameSource = tupleNameSource; @@ -26864,7 +26891,7 @@ var ts; } // @api function createSyntaxList(children) { - var node = createBaseNode(348 /* SyntaxKind.SyntaxList */); + var node = createBaseNode(351 /* SyntaxKind.SyntaxList */); node._children = children; return node; } @@ -26879,7 +26906,7 @@ var ts; */ // @api function createNotEmittedStatement(original) { - var node = createBaseNode(349 /* SyntaxKind.NotEmittedStatement */); + var node = createBaseNode(352 /* SyntaxKind.NotEmittedStatement */); node.original = original; ts.setTextRange(node, original); return node; @@ -26893,7 +26920,7 @@ var ts; */ // @api function createPartiallyEmittedExpression(expression, original) { - var node = createBaseNode(350 /* SyntaxKind.PartiallyEmittedExpression */); + var node = createBaseNode(353 /* SyntaxKind.PartiallyEmittedExpression */); node.expression = expression; node.original = original; node.transformFlags |= @@ -26921,7 +26948,7 @@ var ts; } // @api function createCommaListExpression(elements) { - var node = createBaseNode(351 /* SyntaxKind.CommaListExpression */); + var node = createBaseNode(354 /* SyntaxKind.CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); node.transformFlags |= propagateChildrenFlags(node.elements); return node; @@ -26938,7 +26965,7 @@ var ts; */ // @api function createEndOfDeclarationMarker(original) { - var node = createBaseNode(353 /* SyntaxKind.EndOfDeclarationMarker */); + var node = createBaseNode(356 /* SyntaxKind.EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -26949,14 +26976,14 @@ var ts; */ // @api function createMergeDeclarationMarker(original) { - var node = createBaseNode(352 /* SyntaxKind.MergeDeclarationMarker */); + var node = createBaseNode(355 /* SyntaxKind.MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; } // @api function createSyntheticReferenceExpression(expression, thisArg) { - var node = createBaseNode(354 /* SyntaxKind.SyntheticReferenceExpression */); + var node = createBaseNode(357 /* SyntaxKind.SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= @@ -26978,7 +27005,7 @@ var ts; if (node === undefined) { return node; } - var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(305 /* SyntaxKind.SourceFile */) : + var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(308 /* SyntaxKind.SourceFile */) : ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(79 /* SyntaxKind.Identifier */) : ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(80 /* SyntaxKind.PrivateIdentifier */) : !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) : @@ -26987,7 +27014,7 @@ var ts; clone.transformFlags = node.transformFlags; setOriginalNode(clone, node); for (var key in node) { - if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + if (ts.hasProperty(clone, key) || !ts.hasProperty(node, key)) { continue; } clone[key] = node[key]; @@ -27095,11 +27122,12 @@ var ts; } function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 212 /* SyntaxKind.ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); - case 211 /* SyntaxKind.TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 229 /* SyntaxKind.AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); - case 230 /* SyntaxKind.NonNullExpression */: return updateNonNullExpression(outerExpression, expression); - case 350 /* SyntaxKind.PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); + case 214 /* SyntaxKind.ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); + case 213 /* SyntaxKind.TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 231 /* SyntaxKind.AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); + case 235 /* SyntaxKind.SatisfiesExpression */: return updateSatisfiesExpression(outerExpression, expression, outerExpression.type); + case 232 /* SyntaxKind.NonNullExpression */: return updateNonNullExpression(outerExpression, expression); + case 353 /* SyntaxKind.PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -27153,13 +27181,13 @@ var ts; case 9 /* SyntaxKind.BigIntLiteral */: case 10 /* SyntaxKind.StringLiteral */: return false; - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -27585,24 +27613,24 @@ var ts; } function getDefaultTagNameForKind(kind) { switch (kind) { - case 343 /* SyntaxKind.JSDocTypeTag */: return "type"; - case 341 /* SyntaxKind.JSDocReturnTag */: return "returns"; - case 342 /* SyntaxKind.JSDocThisTag */: return "this"; - case 339 /* SyntaxKind.JSDocEnumTag */: return "enum"; - case 330 /* SyntaxKind.JSDocAuthorTag */: return "author"; - case 332 /* SyntaxKind.JSDocClassTag */: return "class"; - case 333 /* SyntaxKind.JSDocPublicTag */: return "public"; - case 334 /* SyntaxKind.JSDocPrivateTag */: return "private"; - case 335 /* SyntaxKind.JSDocProtectedTag */: return "protected"; - case 336 /* SyntaxKind.JSDocReadonlyTag */: return "readonly"; - case 337 /* SyntaxKind.JSDocOverrideTag */: return "override"; - case 344 /* SyntaxKind.JSDocTemplateTag */: return "template"; - case 345 /* SyntaxKind.JSDocTypedefTag */: return "typedef"; - case 340 /* SyntaxKind.JSDocParameterTag */: return "param"; - case 347 /* SyntaxKind.JSDocPropertyTag */: return "prop"; - case 338 /* SyntaxKind.JSDocCallbackTag */: return "callback"; - case 328 /* SyntaxKind.JSDocAugmentsTag */: return "augments"; - case 329 /* SyntaxKind.JSDocImplementsTag */: return "implements"; + case 346 /* SyntaxKind.JSDocTypeTag */: return "type"; + case 344 /* SyntaxKind.JSDocReturnTag */: return "returns"; + case 345 /* SyntaxKind.JSDocThisTag */: return "this"; + case 342 /* SyntaxKind.JSDocEnumTag */: return "enum"; + case 333 /* SyntaxKind.JSDocAuthorTag */: return "author"; + case 335 /* SyntaxKind.JSDocClassTag */: return "class"; + case 336 /* SyntaxKind.JSDocPublicTag */: return "public"; + case 337 /* SyntaxKind.JSDocPrivateTag */: return "private"; + case 338 /* SyntaxKind.JSDocProtectedTag */: return "protected"; + case 339 /* SyntaxKind.JSDocReadonlyTag */: return "readonly"; + case 340 /* SyntaxKind.JSDocOverrideTag */: return "override"; + case 347 /* SyntaxKind.JSDocTemplateTag */: return "template"; + case 348 /* SyntaxKind.JSDocTypedefTag */: return "typedef"; + case 343 /* SyntaxKind.JSDocParameterTag */: return "param"; + case 350 /* SyntaxKind.JSDocPropertyTag */: return "prop"; + case 341 /* SyntaxKind.JSDocCallbackTag */: return "callback"; + case 331 /* SyntaxKind.JSDocAugmentsTag */: return "augments"; + case 332 /* SyntaxKind.JSDocImplementsTag */: return "implements"; default: return ts.Debug.fail("Unsupported kind: ".concat(ts.Debug.formatSyntaxKind(kind))); } @@ -27618,11 +27646,9 @@ var ts; rawTextScanner.setText("`" + rawText + "`"); break; case 15 /* SyntaxKind.TemplateHead */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("`" + rawText + "${"); break; case 16 /* SyntaxKind.TemplateMiddle */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("}" + rawText + "${"); break; case 17 /* SyntaxKind.TemplateTail */: @@ -27682,69 +27708,70 @@ var ts; */ /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 177 /* SyntaxKind.FirstTypeNode */ && kind <= 200 /* SyntaxKind.LastTypeNode */) { + if (kind >= 179 /* SyntaxKind.FirstTypeNode */ && kind <= 202 /* SyntaxKind.LastTypeNode */) { return -2 /* TransformFlags.TypeExcludes */; } switch (kind) { - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return -2147450880 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return -1941676032 /* TransformFlags.ModuleExcludes */; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return -2147483648 /* TransformFlags.ParameterExcludes */; - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return -2072174592 /* TransformFlags.ArrowFunctionExcludes */; - case 213 /* SyntaxKind.FunctionExpression */: - case 256 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: return -1937940480 /* TransformFlags.FunctionExcludes */; - case 255 /* SyntaxKind.VariableDeclarationList */: + case 258 /* SyntaxKind.VariableDeclarationList */: return -2146893824 /* TransformFlags.VariableDeclarationListExcludes */; - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: return -2147344384 /* TransformFlags.ClassExcludes */; - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return -1937948672 /* TransformFlags.ConstructorExcludes */; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: return -2013249536 /* TransformFlags.PropertyExcludes */; - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return -2005057536 /* TransformFlags.MethodOrAccessorExcludes */; - case 130 /* SyntaxKind.AnyKeyword */: - case 147 /* SyntaxKind.NumberKeyword */: - case 158 /* SyntaxKind.BigIntKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: - case 150 /* SyntaxKind.StringKeyword */: - case 148 /* SyntaxKind.ObjectKeyword */: - case 133 /* SyntaxKind.BooleanKeyword */: - case 151 /* SyntaxKind.SymbolKeyword */: + case 131 /* SyntaxKind.AnyKeyword */: + case 148 /* SyntaxKind.NumberKeyword */: + case 160 /* SyntaxKind.BigIntKeyword */: + case 144 /* SyntaxKind.NeverKeyword */: + case 152 /* SyntaxKind.StringKeyword */: + case 149 /* SyntaxKind.ObjectKeyword */: + case 134 /* SyntaxKind.BooleanKeyword */: + case 153 /* SyntaxKind.SymbolKeyword */: case 114 /* SyntaxKind.VoidKeyword */: - case 163 /* SyntaxKind.TypeParameter */: - case 166 /* SyntaxKind.PropertySignature */: - case 168 /* SyntaxKind.MethodSignature */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 176 /* SyntaxKind.IndexSignature */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 165 /* SyntaxKind.TypeParameter */: + case 168 /* SyntaxKind.PropertySignature */: + case 170 /* SyntaxKind.MethodSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 178 /* SyntaxKind.IndexSignature */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return -2 /* TransformFlags.TypeExcludes */; - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return -2147278848 /* TransformFlags.ObjectLiteralExcludes */; - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return -2147418112 /* TransformFlags.CatchClauseExcludes */; - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 202 /* SyntaxKind.ArrayBindingPattern */: + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: return -2147450880 /* TransformFlags.BindingPatternExcludes */; - case 211 /* SyntaxKind.TypeAssertionExpression */: - case 229 /* SyntaxKind.AsExpression */: - case 350 /* SyntaxKind.PartiallyEmittedExpression */: - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: + case 235 /* SyntaxKind.SatisfiesExpression */: + case 231 /* SyntaxKind.AsExpression */: + case 353 /* SyntaxKind.PartiallyEmittedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: case 106 /* SyntaxKind.SuperKeyword */: return -2147483648 /* TransformFlags.OuterExpressionExcludes */; - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return -2147483648 /* TransformFlags.PropertyAccessExcludes */; default: return -2147483648 /* TransformFlags.NodeExcludes */; @@ -27944,9 +27971,10 @@ var ts; }; var buildInfo_1; var getAndCacheBuildInfo_1 = function (getText) { + var _a; if (buildInfo_1 === undefined) { var result = getText(); - buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false; + buildInfo_1 = result !== undefined ? (_a = ts.getBuildInfo(node.buildInfoPath, result)) !== null && _a !== void 0 ? _a : false : false; } return buildInfo_1 || undefined; }; @@ -27979,7 +28007,6 @@ var ts; return node; } ts.createInputFiles = createInputFiles; - // tslint:disable-next-line variable-name var SourceMapSource; /** * Create an external source map source file reference @@ -28000,7 +28027,7 @@ var ts; } ts.setOriginalNode = setOriginalNode; function mergeEmitNode(sourceEmitNode, destEmitNode) { - var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine, snippetElement = sourceEmitNode.snippetElement; if (!destEmitNode) destEmitNode = {}; // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. @@ -28026,6 +28053,8 @@ var ts; } if (startsOnNewLine !== undefined) destEmitNode.startsOnNewLine = startsOnNewLine; + if (snippetElement !== undefined) + destEmitNode.snippetElement = snippetElement; return destEmitNode; } function mergeTokenSourceMapRanges(sourceRanges, destRanges) { @@ -28051,7 +28080,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 305 /* SyntaxKind.SourceFile */) { + if (node.kind === 308 /* SyntaxKind.SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file."); @@ -28769,6 +28798,8 @@ var ts; // - The verb (`next`, `throw`, or `return` method) to delegate to the expression // of a `yield*`. // - The result of evaluating the verb delegated to the expression of a `yield*`. + // g A temporary variable that holds onto the generator object until the generator + // is started, allowing it to also act as the `suspendedStart` state. // // functions: // verb(n) Creates a bound callback to the `step` function for opcode `n`. @@ -28807,7 +28838,7 @@ var ts; importName: "__generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; // ES Module Helpers ts.createBindingHelper = { @@ -29129,22 +29160,22 @@ var ts; ts.isExportModifier = isExportModifier; /* @internal */ function isAsyncModifier(node) { - return node.kind === 131 /* SyntaxKind.AsyncKeyword */; + return node.kind === 132 /* SyntaxKind.AsyncKeyword */; } ts.isAsyncModifier = isAsyncModifier; /* @internal */ function isAssertsKeyword(node) { - return node.kind === 128 /* SyntaxKind.AssertsKeyword */; + return node.kind === 129 /* SyntaxKind.AssertsKeyword */; } ts.isAssertsKeyword = isAssertsKeyword; /* @internal */ function isAwaitKeyword(node) { - return node.kind === 132 /* SyntaxKind.AwaitKeyword */; + return node.kind === 133 /* SyntaxKind.AwaitKeyword */; } ts.isAwaitKeyword = isAwaitKeyword; /* @internal */ function isReadonlyKeyword(node) { - return node.kind === 145 /* SyntaxKind.ReadonlyKeyword */; + return node.kind === 146 /* SyntaxKind.ReadonlyKeyword */; } ts.isReadonlyKeyword = isReadonlyKeyword; /* @internal */ @@ -29159,9 +29190,14 @@ var ts; ts.isAbstractModifier = isAbstractModifier; /* @internal */ function isOverrideModifier(node) { - return node.kind === 159 /* SyntaxKind.OverrideKeyword */; + return node.kind === 161 /* SyntaxKind.OverrideKeyword */; } ts.isOverrideModifier = isOverrideModifier; + /* @internal */ + function isAccessorModifier(node) { + return node.kind === 127 /* SyntaxKind.AccessorKeyword */; + } + ts.isAccessorModifier = isAccessorModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 106 /* SyntaxKind.SuperKeyword */; @@ -29174,605 +29210,609 @@ var ts; ts.isImportKeyword = isImportKeyword; // Names function isQualifiedName(node) { - return node.kind === 161 /* SyntaxKind.QualifiedName */; + return node.kind === 163 /* SyntaxKind.QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 162 /* SyntaxKind.ComputedPropertyName */; + return node.kind === 164 /* SyntaxKind.ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 163 /* SyntaxKind.TypeParameter */; + return node.kind === 165 /* SyntaxKind.TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; // TODO(rbuckton): Rename to 'isParameterDeclaration' function isParameter(node) { - return node.kind === 164 /* SyntaxKind.Parameter */; + return node.kind === 166 /* SyntaxKind.Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 165 /* SyntaxKind.Decorator */; + return node.kind === 167 /* SyntaxKind.Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 166 /* SyntaxKind.PropertySignature */; + return node.kind === 168 /* SyntaxKind.PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 167 /* SyntaxKind.PropertyDeclaration */; + return node.kind === 169 /* SyntaxKind.PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 168 /* SyntaxKind.MethodSignature */; + return node.kind === 170 /* SyntaxKind.MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 169 /* SyntaxKind.MethodDeclaration */; + return node.kind === 171 /* SyntaxKind.MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isClassStaticBlockDeclaration(node) { - return node.kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */; + return node.kind === 172 /* SyntaxKind.ClassStaticBlockDeclaration */; } ts.isClassStaticBlockDeclaration = isClassStaticBlockDeclaration; function isConstructorDeclaration(node) { - return node.kind === 171 /* SyntaxKind.Constructor */; + return node.kind === 173 /* SyntaxKind.Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 172 /* SyntaxKind.GetAccessor */; + return node.kind === 174 /* SyntaxKind.GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 173 /* SyntaxKind.SetAccessor */; + return node.kind === 175 /* SyntaxKind.SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 174 /* SyntaxKind.CallSignature */; + return node.kind === 176 /* SyntaxKind.CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 175 /* SyntaxKind.ConstructSignature */; + return node.kind === 177 /* SyntaxKind.ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 176 /* SyntaxKind.IndexSignature */; + return node.kind === 178 /* SyntaxKind.IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 177 /* SyntaxKind.TypePredicate */; + return node.kind === 179 /* SyntaxKind.TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 178 /* SyntaxKind.TypeReference */; + return node.kind === 180 /* SyntaxKind.TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 179 /* SyntaxKind.FunctionType */; + return node.kind === 181 /* SyntaxKind.FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 180 /* SyntaxKind.ConstructorType */; + return node.kind === 182 /* SyntaxKind.ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 181 /* SyntaxKind.TypeQuery */; + return node.kind === 183 /* SyntaxKind.TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 182 /* SyntaxKind.TypeLiteral */; + return node.kind === 184 /* SyntaxKind.TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 183 /* SyntaxKind.ArrayType */; + return node.kind === 185 /* SyntaxKind.ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 184 /* SyntaxKind.TupleType */; + return node.kind === 186 /* SyntaxKind.TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isNamedTupleMember(node) { - return node.kind === 197 /* SyntaxKind.NamedTupleMember */; + return node.kind === 199 /* SyntaxKind.NamedTupleMember */; } ts.isNamedTupleMember = isNamedTupleMember; function isOptionalTypeNode(node) { - return node.kind === 185 /* SyntaxKind.OptionalType */; + return node.kind === 187 /* SyntaxKind.OptionalType */; } ts.isOptionalTypeNode = isOptionalTypeNode; function isRestTypeNode(node) { - return node.kind === 186 /* SyntaxKind.RestType */; + return node.kind === 188 /* SyntaxKind.RestType */; } ts.isRestTypeNode = isRestTypeNode; function isUnionTypeNode(node) { - return node.kind === 187 /* SyntaxKind.UnionType */; + return node.kind === 189 /* SyntaxKind.UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 188 /* SyntaxKind.IntersectionType */; + return node.kind === 190 /* SyntaxKind.IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 189 /* SyntaxKind.ConditionalType */; + return node.kind === 191 /* SyntaxKind.ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 190 /* SyntaxKind.InferType */; + return node.kind === 192 /* SyntaxKind.InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 191 /* SyntaxKind.ParenthesizedType */; + return node.kind === 193 /* SyntaxKind.ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 192 /* SyntaxKind.ThisType */; + return node.kind === 194 /* SyntaxKind.ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 193 /* SyntaxKind.TypeOperator */; + return node.kind === 195 /* SyntaxKind.TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 194 /* SyntaxKind.IndexedAccessType */; + return node.kind === 196 /* SyntaxKind.IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 195 /* SyntaxKind.MappedType */; + return node.kind === 197 /* SyntaxKind.MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 196 /* SyntaxKind.LiteralType */; + return node.kind === 198 /* SyntaxKind.LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 200 /* SyntaxKind.ImportType */; + return node.kind === 202 /* SyntaxKind.ImportType */; } ts.isImportTypeNode = isImportTypeNode; function isTemplateLiteralTypeSpan(node) { - return node.kind === 199 /* SyntaxKind.TemplateLiteralTypeSpan */; + return node.kind === 201 /* SyntaxKind.TemplateLiteralTypeSpan */; } ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan; function isTemplateLiteralTypeNode(node) { - return node.kind === 198 /* SyntaxKind.TemplateLiteralType */; + return node.kind === 200 /* SyntaxKind.TemplateLiteralType */; } ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 201 /* SyntaxKind.ObjectBindingPattern */; + return node.kind === 203 /* SyntaxKind.ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 202 /* SyntaxKind.ArrayBindingPattern */; + return node.kind === 204 /* SyntaxKind.ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 203 /* SyntaxKind.BindingElement */; + return node.kind === 205 /* SyntaxKind.BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 204 /* SyntaxKind.ArrayLiteralExpression */; + return node.kind === 206 /* SyntaxKind.ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 205 /* SyntaxKind.ObjectLiteralExpression */; + return node.kind === 207 /* SyntaxKind.ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 206 /* SyntaxKind.PropertyAccessExpression */; + return node.kind === 208 /* SyntaxKind.PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 207 /* SyntaxKind.ElementAccessExpression */; + return node.kind === 209 /* SyntaxKind.ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 208 /* SyntaxKind.CallExpression */; + return node.kind === 210 /* SyntaxKind.CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 209 /* SyntaxKind.NewExpression */; + return node.kind === 211 /* SyntaxKind.NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 210 /* SyntaxKind.TaggedTemplateExpression */; + return node.kind === 212 /* SyntaxKind.TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertionExpression(node) { - return node.kind === 211 /* SyntaxKind.TypeAssertionExpression */; + return node.kind === 213 /* SyntaxKind.TypeAssertionExpression */; } ts.isTypeAssertionExpression = isTypeAssertionExpression; function isParenthesizedExpression(node) { - return node.kind === 212 /* SyntaxKind.ParenthesizedExpression */; + return node.kind === 214 /* SyntaxKind.ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function isFunctionExpression(node) { - return node.kind === 213 /* SyntaxKind.FunctionExpression */; + return node.kind === 215 /* SyntaxKind.FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 214 /* SyntaxKind.ArrowFunction */; + return node.kind === 216 /* SyntaxKind.ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 215 /* SyntaxKind.DeleteExpression */; + return node.kind === 217 /* SyntaxKind.DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 216 /* SyntaxKind.TypeOfExpression */; + return node.kind === 218 /* SyntaxKind.TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 217 /* SyntaxKind.VoidExpression */; + return node.kind === 219 /* SyntaxKind.VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 218 /* SyntaxKind.AwaitExpression */; + return node.kind === 220 /* SyntaxKind.AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 219 /* SyntaxKind.PrefixUnaryExpression */; + return node.kind === 221 /* SyntaxKind.PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 220 /* SyntaxKind.PostfixUnaryExpression */; + return node.kind === 222 /* SyntaxKind.PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 221 /* SyntaxKind.BinaryExpression */; + return node.kind === 223 /* SyntaxKind.BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 222 /* SyntaxKind.ConditionalExpression */; + return node.kind === 224 /* SyntaxKind.ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 223 /* SyntaxKind.TemplateExpression */; + return node.kind === 225 /* SyntaxKind.TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 224 /* SyntaxKind.YieldExpression */; + return node.kind === 226 /* SyntaxKind.YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 225 /* SyntaxKind.SpreadElement */; + return node.kind === 227 /* SyntaxKind.SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 226 /* SyntaxKind.ClassExpression */; + return node.kind === 228 /* SyntaxKind.ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 227 /* SyntaxKind.OmittedExpression */; + return node.kind === 229 /* SyntaxKind.OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */; + return node.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 229 /* SyntaxKind.AsExpression */; + return node.kind === 231 /* SyntaxKind.AsExpression */; } ts.isAsExpression = isAsExpression; + function isSatisfiesExpression(node) { + return node.kind === 235 /* SyntaxKind.SatisfiesExpression */; + } + ts.isSatisfiesExpression = isSatisfiesExpression; function isNonNullExpression(node) { - return node.kind === 230 /* SyntaxKind.NonNullExpression */; + return node.kind === 232 /* SyntaxKind.NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 231 /* SyntaxKind.MetaProperty */; + return node.kind === 233 /* SyntaxKind.MetaProperty */; } ts.isMetaProperty = isMetaProperty; function isSyntheticExpression(node) { - return node.kind === 232 /* SyntaxKind.SyntheticExpression */; + return node.kind === 234 /* SyntaxKind.SyntheticExpression */; } ts.isSyntheticExpression = isSyntheticExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 350 /* SyntaxKind.PartiallyEmittedExpression */; + return node.kind === 353 /* SyntaxKind.PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isCommaListExpression(node) { - return node.kind === 351 /* SyntaxKind.CommaListExpression */; + return node.kind === 354 /* SyntaxKind.CommaListExpression */; } ts.isCommaListExpression = isCommaListExpression; // Misc function isTemplateSpan(node) { - return node.kind === 233 /* SyntaxKind.TemplateSpan */; + return node.kind === 236 /* SyntaxKind.TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 234 /* SyntaxKind.SemicolonClassElement */; + return node.kind === 237 /* SyntaxKind.SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Elements function isBlock(node) { - return node.kind === 235 /* SyntaxKind.Block */; + return node.kind === 238 /* SyntaxKind.Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 237 /* SyntaxKind.VariableStatement */; + return node.kind === 240 /* SyntaxKind.VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 236 /* SyntaxKind.EmptyStatement */; + return node.kind === 239 /* SyntaxKind.EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 238 /* SyntaxKind.ExpressionStatement */; + return node.kind === 241 /* SyntaxKind.ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 239 /* SyntaxKind.IfStatement */; + return node.kind === 242 /* SyntaxKind.IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 240 /* SyntaxKind.DoStatement */; + return node.kind === 243 /* SyntaxKind.DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 241 /* SyntaxKind.WhileStatement */; + return node.kind === 244 /* SyntaxKind.WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 242 /* SyntaxKind.ForStatement */; + return node.kind === 245 /* SyntaxKind.ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 243 /* SyntaxKind.ForInStatement */; + return node.kind === 246 /* SyntaxKind.ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 244 /* SyntaxKind.ForOfStatement */; + return node.kind === 247 /* SyntaxKind.ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 245 /* SyntaxKind.ContinueStatement */; + return node.kind === 248 /* SyntaxKind.ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 246 /* SyntaxKind.BreakStatement */; + return node.kind === 249 /* SyntaxKind.BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isReturnStatement(node) { - return node.kind === 247 /* SyntaxKind.ReturnStatement */; + return node.kind === 250 /* SyntaxKind.ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 248 /* SyntaxKind.WithStatement */; + return node.kind === 251 /* SyntaxKind.WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 249 /* SyntaxKind.SwitchStatement */; + return node.kind === 252 /* SyntaxKind.SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 250 /* SyntaxKind.LabeledStatement */; + return node.kind === 253 /* SyntaxKind.LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 251 /* SyntaxKind.ThrowStatement */; + return node.kind === 254 /* SyntaxKind.ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 252 /* SyntaxKind.TryStatement */; + return node.kind === 255 /* SyntaxKind.TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 253 /* SyntaxKind.DebuggerStatement */; + return node.kind === 256 /* SyntaxKind.DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 254 /* SyntaxKind.VariableDeclaration */; + return node.kind === 257 /* SyntaxKind.VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 255 /* SyntaxKind.VariableDeclarationList */; + return node.kind === 258 /* SyntaxKind.VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 256 /* SyntaxKind.FunctionDeclaration */; + return node.kind === 259 /* SyntaxKind.FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 257 /* SyntaxKind.ClassDeclaration */; + return node.kind === 260 /* SyntaxKind.ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 258 /* SyntaxKind.InterfaceDeclaration */; + return node.kind === 261 /* SyntaxKind.InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 259 /* SyntaxKind.TypeAliasDeclaration */; + return node.kind === 262 /* SyntaxKind.TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 260 /* SyntaxKind.EnumDeclaration */; + return node.kind === 263 /* SyntaxKind.EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 261 /* SyntaxKind.ModuleDeclaration */; + return node.kind === 264 /* SyntaxKind.ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 262 /* SyntaxKind.ModuleBlock */; + return node.kind === 265 /* SyntaxKind.ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 263 /* SyntaxKind.CaseBlock */; + return node.kind === 266 /* SyntaxKind.CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 264 /* SyntaxKind.NamespaceExportDeclaration */; + return node.kind === 267 /* SyntaxKind.NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */; + return node.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 266 /* SyntaxKind.ImportDeclaration */; + return node.kind === 269 /* SyntaxKind.ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 267 /* SyntaxKind.ImportClause */; + return node.kind === 270 /* SyntaxKind.ImportClause */; } ts.isImportClause = isImportClause; function isImportTypeAssertionContainer(node) { - return node.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */; + return node.kind === 298 /* SyntaxKind.ImportTypeAssertionContainer */; } ts.isImportTypeAssertionContainer = isImportTypeAssertionContainer; function isAssertClause(node) { - return node.kind === 293 /* SyntaxKind.AssertClause */; + return node.kind === 296 /* SyntaxKind.AssertClause */; } ts.isAssertClause = isAssertClause; function isAssertEntry(node) { - return node.kind === 294 /* SyntaxKind.AssertEntry */; + return node.kind === 297 /* SyntaxKind.AssertEntry */; } ts.isAssertEntry = isAssertEntry; function isNamespaceImport(node) { - return node.kind === 268 /* SyntaxKind.NamespaceImport */; + return node.kind === 271 /* SyntaxKind.NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamespaceExport(node) { - return node.kind === 274 /* SyntaxKind.NamespaceExport */; + return node.kind === 277 /* SyntaxKind.NamespaceExport */; } ts.isNamespaceExport = isNamespaceExport; function isNamedImports(node) { - return node.kind === 269 /* SyntaxKind.NamedImports */; + return node.kind === 272 /* SyntaxKind.NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 270 /* SyntaxKind.ImportSpecifier */; + return node.kind === 273 /* SyntaxKind.ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 271 /* SyntaxKind.ExportAssignment */; + return node.kind === 274 /* SyntaxKind.ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 272 /* SyntaxKind.ExportDeclaration */; + return node.kind === 275 /* SyntaxKind.ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 273 /* SyntaxKind.NamedExports */; + return node.kind === 276 /* SyntaxKind.NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 275 /* SyntaxKind.ExportSpecifier */; + return node.kind === 278 /* SyntaxKind.ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 276 /* SyntaxKind.MissingDeclaration */; + return node.kind === 279 /* SyntaxKind.MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; function isNotEmittedStatement(node) { - return node.kind === 349 /* SyntaxKind.NotEmittedStatement */; + return node.kind === 352 /* SyntaxKind.NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ function isSyntheticReference(node) { - return node.kind === 354 /* SyntaxKind.SyntheticReferenceExpression */; + return node.kind === 357 /* SyntaxKind.SyntheticReferenceExpression */; } ts.isSyntheticReference = isSyntheticReference; /* @internal */ function isMergeDeclarationMarker(node) { - return node.kind === 352 /* SyntaxKind.MergeDeclarationMarker */; + return node.kind === 355 /* SyntaxKind.MergeDeclarationMarker */; } ts.isMergeDeclarationMarker = isMergeDeclarationMarker; /* @internal */ function isEndOfDeclarationMarker(node) { - return node.kind === 353 /* SyntaxKind.EndOfDeclarationMarker */; + return node.kind === 356 /* SyntaxKind.EndOfDeclarationMarker */; } ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker; // Module References function isExternalModuleReference(node) { - return node.kind === 277 /* SyntaxKind.ExternalModuleReference */; + return node.kind === 280 /* SyntaxKind.ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 278 /* SyntaxKind.JsxElement */; + return node.kind === 281 /* SyntaxKind.JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 279 /* SyntaxKind.JsxSelfClosingElement */; + return node.kind === 282 /* SyntaxKind.JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 280 /* SyntaxKind.JsxOpeningElement */; + return node.kind === 283 /* SyntaxKind.JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 281 /* SyntaxKind.JsxClosingElement */; + return node.kind === 284 /* SyntaxKind.JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 282 /* SyntaxKind.JsxFragment */; + return node.kind === 285 /* SyntaxKind.JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 283 /* SyntaxKind.JsxOpeningFragment */; + return node.kind === 286 /* SyntaxKind.JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 284 /* SyntaxKind.JsxClosingFragment */; + return node.kind === 287 /* SyntaxKind.JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 285 /* SyntaxKind.JsxAttribute */; + return node.kind === 288 /* SyntaxKind.JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 286 /* SyntaxKind.JsxAttributes */; + return node.kind === 289 /* SyntaxKind.JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 287 /* SyntaxKind.JsxSpreadAttribute */; + return node.kind === 290 /* SyntaxKind.JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 288 /* SyntaxKind.JsxExpression */; + return node.kind === 291 /* SyntaxKind.JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 289 /* SyntaxKind.CaseClause */; + return node.kind === 292 /* SyntaxKind.CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 290 /* SyntaxKind.DefaultClause */; + return node.kind === 293 /* SyntaxKind.DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 291 /* SyntaxKind.HeritageClause */; + return node.kind === 294 /* SyntaxKind.HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 292 /* SyntaxKind.CatchClause */; + return node.kind === 295 /* SyntaxKind.CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 296 /* SyntaxKind.PropertyAssignment */; + return node.kind === 299 /* SyntaxKind.PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */; + return node.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 298 /* SyntaxKind.SpreadAssignment */; + return node.kind === 301 /* SyntaxKind.SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 299 /* SyntaxKind.EnumMember */; + return node.kind === 302 /* SyntaxKind.EnumMember */; } ts.isEnumMember = isEnumMember; // Unparsed // TODO(rbuckton): isUnparsedPrologue function isUnparsedPrepend(node) { - return node.kind === 301 /* SyntaxKind.UnparsedPrepend */; + return node.kind === 304 /* SyntaxKind.UnparsedPrepend */; } ts.isUnparsedPrepend = isUnparsedPrepend; // TODO(rbuckton): isUnparsedText @@ -29780,176 +29820,176 @@ var ts; // TODO(rbuckton): isUnparsedSyntheticReference // Top-level nodes function isSourceFile(node) { - return node.kind === 305 /* SyntaxKind.SourceFile */; + return node.kind === 308 /* SyntaxKind.SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 306 /* SyntaxKind.Bundle */; + return node.kind === 309 /* SyntaxKind.Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 307 /* SyntaxKind.UnparsedSource */; + return node.kind === 310 /* SyntaxKind.UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // TODO(rbuckton): isInputFiles // JSDoc Elements function isJSDocTypeExpression(node) { - return node.kind === 309 /* SyntaxKind.JSDocTypeExpression */; + return node.kind === 312 /* SyntaxKind.JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocNameReference(node) { - return node.kind === 310 /* SyntaxKind.JSDocNameReference */; + return node.kind === 313 /* SyntaxKind.JSDocNameReference */; } ts.isJSDocNameReference = isJSDocNameReference; function isJSDocMemberName(node) { - return node.kind === 311 /* SyntaxKind.JSDocMemberName */; + return node.kind === 314 /* SyntaxKind.JSDocMemberName */; } ts.isJSDocMemberName = isJSDocMemberName; function isJSDocLink(node) { - return node.kind === 324 /* SyntaxKind.JSDocLink */; + return node.kind === 327 /* SyntaxKind.JSDocLink */; } ts.isJSDocLink = isJSDocLink; function isJSDocLinkCode(node) { - return node.kind === 325 /* SyntaxKind.JSDocLinkCode */; + return node.kind === 328 /* SyntaxKind.JSDocLinkCode */; } ts.isJSDocLinkCode = isJSDocLinkCode; function isJSDocLinkPlain(node) { - return node.kind === 326 /* SyntaxKind.JSDocLinkPlain */; + return node.kind === 329 /* SyntaxKind.JSDocLinkPlain */; } ts.isJSDocLinkPlain = isJSDocLinkPlain; function isJSDocAllType(node) { - return node.kind === 312 /* SyntaxKind.JSDocAllType */; + return node.kind === 315 /* SyntaxKind.JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 313 /* SyntaxKind.JSDocUnknownType */; + return node.kind === 316 /* SyntaxKind.JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 314 /* SyntaxKind.JSDocNullableType */; + return node.kind === 317 /* SyntaxKind.JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 315 /* SyntaxKind.JSDocNonNullableType */; + return node.kind === 318 /* SyntaxKind.JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 316 /* SyntaxKind.JSDocOptionalType */; + return node.kind === 319 /* SyntaxKind.JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 317 /* SyntaxKind.JSDocFunctionType */; + return node.kind === 320 /* SyntaxKind.JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 318 /* SyntaxKind.JSDocVariadicType */; + return node.kind === 321 /* SyntaxKind.JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDocNamepathType(node) { - return node.kind === 319 /* SyntaxKind.JSDocNamepathType */; + return node.kind === 322 /* SyntaxKind.JSDocNamepathType */; } ts.isJSDocNamepathType = isJSDocNamepathType; function isJSDoc(node) { - return node.kind === 320 /* SyntaxKind.JSDoc */; + return node.kind === 323 /* SyntaxKind.JSDoc */; } ts.isJSDoc = isJSDoc; function isJSDocTypeLiteral(node) { - return node.kind === 322 /* SyntaxKind.JSDocTypeLiteral */; + return node.kind === 325 /* SyntaxKind.JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocSignature(node) { - return node.kind === 323 /* SyntaxKind.JSDocSignature */; + return node.kind === 326 /* SyntaxKind.JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; // JSDoc Tags function isJSDocAugmentsTag(node) { - return node.kind === 328 /* SyntaxKind.JSDocAugmentsTag */; + return node.kind === 331 /* SyntaxKind.JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocAuthorTag(node) { - return node.kind === 330 /* SyntaxKind.JSDocAuthorTag */; + return node.kind === 333 /* SyntaxKind.JSDocAuthorTag */; } ts.isJSDocAuthorTag = isJSDocAuthorTag; function isJSDocClassTag(node) { - return node.kind === 332 /* SyntaxKind.JSDocClassTag */; + return node.kind === 335 /* SyntaxKind.JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocCallbackTag(node) { - return node.kind === 338 /* SyntaxKind.JSDocCallbackTag */; + return node.kind === 341 /* SyntaxKind.JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocPublicTag(node) { - return node.kind === 333 /* SyntaxKind.JSDocPublicTag */; + return node.kind === 336 /* SyntaxKind.JSDocPublicTag */; } ts.isJSDocPublicTag = isJSDocPublicTag; function isJSDocPrivateTag(node) { - return node.kind === 334 /* SyntaxKind.JSDocPrivateTag */; + return node.kind === 337 /* SyntaxKind.JSDocPrivateTag */; } ts.isJSDocPrivateTag = isJSDocPrivateTag; function isJSDocProtectedTag(node) { - return node.kind === 335 /* SyntaxKind.JSDocProtectedTag */; + return node.kind === 338 /* SyntaxKind.JSDocProtectedTag */; } ts.isJSDocProtectedTag = isJSDocProtectedTag; function isJSDocReadonlyTag(node) { - return node.kind === 336 /* SyntaxKind.JSDocReadonlyTag */; + return node.kind === 339 /* SyntaxKind.JSDocReadonlyTag */; } ts.isJSDocReadonlyTag = isJSDocReadonlyTag; function isJSDocOverrideTag(node) { - return node.kind === 337 /* SyntaxKind.JSDocOverrideTag */; + return node.kind === 340 /* SyntaxKind.JSDocOverrideTag */; } ts.isJSDocOverrideTag = isJSDocOverrideTag; function isJSDocDeprecatedTag(node) { - return node.kind === 331 /* SyntaxKind.JSDocDeprecatedTag */; + return node.kind === 334 /* SyntaxKind.JSDocDeprecatedTag */; } ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag; function isJSDocSeeTag(node) { - return node.kind === 346 /* SyntaxKind.JSDocSeeTag */; + return node.kind === 349 /* SyntaxKind.JSDocSeeTag */; } ts.isJSDocSeeTag = isJSDocSeeTag; function isJSDocEnumTag(node) { - return node.kind === 339 /* SyntaxKind.JSDocEnumTag */; + return node.kind === 342 /* SyntaxKind.JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocParameterTag(node) { - return node.kind === 340 /* SyntaxKind.JSDocParameterTag */; + return node.kind === 343 /* SyntaxKind.JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 341 /* SyntaxKind.JSDocReturnTag */; + return node.kind === 344 /* SyntaxKind.JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocThisTag(node) { - return node.kind === 342 /* SyntaxKind.JSDocThisTag */; + return node.kind === 345 /* SyntaxKind.JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocTypeTag(node) { - return node.kind === 343 /* SyntaxKind.JSDocTypeTag */; + return node.kind === 346 /* SyntaxKind.JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 344 /* SyntaxKind.JSDocTemplateTag */; + return node.kind === 347 /* SyntaxKind.JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 345 /* SyntaxKind.JSDocTypedefTag */; + return node.kind === 348 /* SyntaxKind.JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocUnknownTag(node) { - return node.kind === 327 /* SyntaxKind.JSDocTag */; + return node.kind === 330 /* SyntaxKind.JSDocTag */; } ts.isJSDocUnknownTag = isJSDocUnknownTag; function isJSDocPropertyTag(node) { - return node.kind === 347 /* SyntaxKind.JSDocPropertyTag */; + return node.kind === 350 /* SyntaxKind.JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocImplementsTag(node) { - return node.kind === 329 /* SyntaxKind.JSDocImplementsTag */; + return node.kind === 332 /* SyntaxKind.JSDocImplementsTag */; } ts.isJSDocImplementsTag = isJSDocImplementsTag; // Synthesized list /* @internal */ function isSyntaxList(n) { - return n.kind === 348 /* SyntaxKind.SyntaxList */; + return n.kind === 351 /* SyntaxKind.SyntaxList */; } ts.isSyntaxList = isSyntaxList; })(ts || (ts = {})); @@ -30148,14 +30188,14 @@ var ts; ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals."); } switch (property.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine); - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: return createExpressionForPropertyAssignment(factory, property, receiver); - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(factory, property, receiver); - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: return createExpressionForMethodDeclaration(factory, property, receiver); } } @@ -30263,8 +30303,8 @@ var ts; } ts.startsWithUseStrict = startsWithUseStrict; function isCommaSequence(node) { - return node.kind === 221 /* SyntaxKind.BinaryExpression */ && node.operatorToken.kind === 27 /* SyntaxKind.CommaToken */ || - node.kind === 351 /* SyntaxKind.CommaListExpression */; + return node.kind === 223 /* SyntaxKind.BinaryExpression */ && node.operatorToken.kind === 27 /* SyntaxKind.CommaToken */ || + node.kind === 354 /* SyntaxKind.CommaListExpression */; } ts.isCommaSequence = isCommaSequence; function isJSDocTypeAssertion(node) { @@ -30282,17 +30322,18 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 15 /* OuterExpressionKinds.All */; } switch (node.kind) { - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: if (kinds & 16 /* OuterExpressionKinds.ExcludeJSDocTypeAssertion */ && isJSDocTypeAssertion(node)) { return false; } return (kinds & 1 /* OuterExpressionKinds.Parentheses */) !== 0; - case 211 /* SyntaxKind.TypeAssertionExpression */: - case 229 /* SyntaxKind.AsExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: + case 231 /* SyntaxKind.AsExpression */: + case 235 /* SyntaxKind.SatisfiesExpression */: return (kinds & 2 /* OuterExpressionKinds.TypeAssertions */) !== 0; - case 230 /* SyntaxKind.NonNullExpression */: + case 232 /* SyntaxKind.NonNullExpression */: return (kinds & 4 /* OuterExpressionKinds.NonNullAssertions */) !== 0; - case 350 /* SyntaxKind.PartiallyEmittedExpression */: + case 353 /* SyntaxKind.PartiallyEmittedExpression */: return (kinds & 8 /* OuterExpressionKinds.PartiallyEmittedExpressions */) !== 0; } return false; @@ -30413,10 +30454,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 266 /* SyntaxKind.ImportDeclaration */ && node.importClause) { + if (node.kind === 269 /* SyntaxKind.ImportDeclaration */ && node.importClause) { return factory.getGeneratedNameForNode(node); } - if (node.kind === 272 /* SyntaxKind.ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 275 /* SyntaxKind.ExportDeclaration */ && node.moduleSpecifier) { return factory.getGeneratedNameForNode(node); } return undefined; @@ -30535,7 +30576,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -30547,11 +30588,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 298 /* SyntaxKind.SpreadAssignment */: + case 301 /* SyntaxKind.SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -30583,12 +30624,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 164 /* SyntaxKind.Parameter */: - case 203 /* SyntaxKind.BindingElement */: + case 166 /* SyntaxKind.Parameter */: + case 205 /* SyntaxKind.BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 225 /* SyntaxKind.SpreadElement */: - case 298 /* SyntaxKind.SpreadAssignment */: + case 227 /* SyntaxKind.SpreadElement */: + case 301 /* SyntaxKind.SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -30606,7 +30647,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -30621,7 +30662,7 @@ var ts; : propertyName; } break; - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -30636,7 +30677,7 @@ var ts; : propertyName; } break; - case 298 /* SyntaxKind.SpreadAssignment */: + case 301 /* SyntaxKind.SpreadAssignment */: // `a` in `({ ...a } = ...)` if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) { return ts.Debug.failBadSyntaxKind(bindingElement.name); @@ -30659,13 +30700,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 202 /* SyntaxKind.ArrayBindingPattern */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -30686,46 +30727,46 @@ var ts; ts.getJSDocTypeAliasName = getJSDocTypeAliasName; function canHaveIllegalType(node) { var kind = node.kind; - return kind === 171 /* SyntaxKind.Constructor */ - || kind === 173 /* SyntaxKind.SetAccessor */; + return kind === 173 /* SyntaxKind.Constructor */ + || kind === 175 /* SyntaxKind.SetAccessor */; } ts.canHaveIllegalType = canHaveIllegalType; function canHaveIllegalTypeParameters(node) { var kind = node.kind; - return kind === 171 /* SyntaxKind.Constructor */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */; + return kind === 173 /* SyntaxKind.Constructor */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 175 /* SyntaxKind.SetAccessor */; } ts.canHaveIllegalTypeParameters = canHaveIllegalTypeParameters; function canHaveIllegalDecorators(node) { var kind = node.kind; - return kind === 296 /* SyntaxKind.PropertyAssignment */ - || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ - || kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ - || kind === 176 /* SyntaxKind.IndexSignature */ - || kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ - || kind === 276 /* SyntaxKind.MissingDeclaration */ - || kind === 237 /* SyntaxKind.VariableStatement */ - || kind === 258 /* SyntaxKind.InterfaceDeclaration */ - || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ - || kind === 260 /* SyntaxKind.EnumDeclaration */ - || kind === 261 /* SyntaxKind.ModuleDeclaration */ - || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ - || kind === 266 /* SyntaxKind.ImportDeclaration */ - || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ - || kind === 272 /* SyntaxKind.ExportDeclaration */ - || kind === 271 /* SyntaxKind.ExportAssignment */; + return kind === 299 /* SyntaxKind.PropertyAssignment */ + || kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 259 /* SyntaxKind.FunctionDeclaration */ + || kind === 173 /* SyntaxKind.Constructor */ + || kind === 178 /* SyntaxKind.IndexSignature */ + || kind === 172 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 279 /* SyntaxKind.MissingDeclaration */ + || kind === 240 /* SyntaxKind.VariableStatement */ + || kind === 261 /* SyntaxKind.InterfaceDeclaration */ + || kind === 262 /* SyntaxKind.TypeAliasDeclaration */ + || kind === 263 /* SyntaxKind.EnumDeclaration */ + || kind === 264 /* SyntaxKind.ModuleDeclaration */ + || kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ + || kind === 269 /* SyntaxKind.ImportDeclaration */ + || kind === 267 /* SyntaxKind.NamespaceExportDeclaration */ + || kind === 275 /* SyntaxKind.ExportDeclaration */ + || kind === 274 /* SyntaxKind.ExportAssignment */; } ts.canHaveIllegalDecorators = canHaveIllegalDecorators; function canHaveIllegalModifiers(node) { var kind = node.kind; - return kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ - || kind === 296 /* SyntaxKind.PropertyAssignment */ - || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ - || kind === 179 /* SyntaxKind.FunctionType */ - || kind === 276 /* SyntaxKind.MissingDeclaration */ - || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */; + return kind === 172 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 299 /* SyntaxKind.PropertyAssignment */ + || kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 181 /* SyntaxKind.FunctionType */ + || kind === 279 /* SyntaxKind.MissingDeclaration */ + || kind === 267 /* SyntaxKind.NamespaceExportDeclaration */; } ts.canHaveIllegalModifiers = canHaveIllegalModifiers; ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); @@ -30999,6 +31040,83 @@ var ts; return ts.setTextRange(factory.createNodeArray([], nodes.hasTrailingComma), nodes); } ts.elideNodes = elideNodes; + /** + * Gets the node from which a name should be generated. + */ + function getNodeForGeneratedName(name) { + if (name.autoGenerateFlags & 4 /* GeneratedIdentifierFlags.Node */) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + // if "node" is a different generated name (having a different "autoGenerateId"), use it and stop traversing. + if (ts.isMemberName(node) + && !!(node.autoGenerateFlags & 4 /* GeneratedIdentifierFlags.Node */) + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + // otherwise, return the original node for the source + return node; + } + return name; + } + ts.getNodeForGeneratedName = getNodeForGeneratedName; + function formatGeneratedNamePart(part, generateName) { + return typeof part === "object" ? formatGeneratedName(/*privateName*/ false, part.prefix, part.node, part.suffix, generateName) : + typeof part === "string" ? part.length > 0 && part.charCodeAt(0) === 35 /* CharacterCodes.hash */ ? part.slice(1) : part : + ""; + } + ts.formatGeneratedNamePart = formatGeneratedNamePart; + function formatIdentifier(name, generateName) { + return typeof name === "string" ? name : + formatIdentifierWorker(name, ts.Debug.checkDefined(generateName)); + } + function formatIdentifierWorker(node, generateName) { + return ts.isGeneratedPrivateIdentifier(node) ? generateName(node).slice(1) : + ts.isGeneratedIdentifier(node) ? generateName(node) : + ts.isPrivateIdentifier(node) ? node.escapedText.slice(1) : + ts.idText(node); + } + function formatGeneratedName(privateName, prefix, baseName, suffix, generateName) { + prefix = formatGeneratedNamePart(prefix, generateName); + suffix = formatGeneratedNamePart(suffix, generateName); + baseName = formatIdentifier(baseName, generateName); + return "".concat(privateName ? "#" : "").concat(prefix).concat(baseName).concat(suffix); + } + ts.formatGeneratedName = formatGeneratedName; + /** + * Creates a private backing field for an `accessor` {@link PropertyDeclaration}. + */ + function createAccessorPropertyBackingField(factory, node, modifiers, initializer) { + return factory.updatePropertyDeclaration(node, modifiers, factory.getGeneratedPrivateNameForNode(node.name, /*prefix*/ undefined, "_accessor_storage"), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, initializer); + } + ts.createAccessorPropertyBackingField = createAccessorPropertyBackingField; + /** + * Creates a {@link GetAccessorDeclaration} that reads from a private backing field. + */ + function createAccessorPropertyGetRedirector(factory, node, modifiers, name) { + return factory.createGetAccessorDeclaration(modifiers, name, [], + /*type*/ undefined, factory.createBlock([ + factory.createReturnStatement(factory.createPropertyAccessExpression(factory.createThis(), factory.getGeneratedPrivateNameForNode(node.name, /*prefix*/ undefined, "_accessor_storage"))) + ])); + } + ts.createAccessorPropertyGetRedirector = createAccessorPropertyGetRedirector; + /** + * Creates a {@link SetAccessorDeclaration} that writes to a private backing field. + */ + function createAccessorPropertySetRedirector(factory, node, modifiers, name) { + return factory.createSetAccessorDeclaration(modifiers, name, [factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotdotDotToken*/ undefined, "value")], factory.createBlock([ + factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(factory.createThis(), factory.getGeneratedPrivateNameForNode(node.name, /*prefix*/ undefined, "_accessor_storage")), factory.createIdentifier("value"))) + ])); + } + ts.createAccessorPropertySetRedirector = createAccessorPropertySetRedirector; })(ts || (ts = {})); var ts; (function (ts) { @@ -31008,47 +31126,48 @@ var ts; ts.setTextRange = setTextRange; function canHaveModifiers(node) { var kind = node.kind; - return kind === 163 /* SyntaxKind.TypeParameter */ - || kind === 164 /* SyntaxKind.Parameter */ - || kind === 166 /* SyntaxKind.PropertySignature */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */ - || kind === 168 /* SyntaxKind.MethodSignature */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */ - || kind === 176 /* SyntaxKind.IndexSignature */ - || kind === 180 /* SyntaxKind.ConstructorType */ - || kind === 213 /* SyntaxKind.FunctionExpression */ - || kind === 214 /* SyntaxKind.ArrowFunction */ - || kind === 226 /* SyntaxKind.ClassExpression */ - || kind === 237 /* SyntaxKind.VariableStatement */ - || kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 257 /* SyntaxKind.ClassDeclaration */ - || kind === 258 /* SyntaxKind.InterfaceDeclaration */ - || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ - || kind === 260 /* SyntaxKind.EnumDeclaration */ - || kind === 261 /* SyntaxKind.ModuleDeclaration */ - || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ - || kind === 266 /* SyntaxKind.ImportDeclaration */ - || kind === 271 /* SyntaxKind.ExportAssignment */ - || kind === 272 /* SyntaxKind.ExportDeclaration */; + return kind === 165 /* SyntaxKind.TypeParameter */ + || kind === 166 /* SyntaxKind.Parameter */ + || kind === 168 /* SyntaxKind.PropertySignature */ + || kind === 169 /* SyntaxKind.PropertyDeclaration */ + || kind === 170 /* SyntaxKind.MethodSignature */ + || kind === 171 /* SyntaxKind.MethodDeclaration */ + || kind === 173 /* SyntaxKind.Constructor */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 175 /* SyntaxKind.SetAccessor */ + || kind === 178 /* SyntaxKind.IndexSignature */ + || kind === 182 /* SyntaxKind.ConstructorType */ + || kind === 215 /* SyntaxKind.FunctionExpression */ + || kind === 216 /* SyntaxKind.ArrowFunction */ + || kind === 228 /* SyntaxKind.ClassExpression */ + || kind === 240 /* SyntaxKind.VariableStatement */ + || kind === 259 /* SyntaxKind.FunctionDeclaration */ + || kind === 260 /* SyntaxKind.ClassDeclaration */ + || kind === 261 /* SyntaxKind.InterfaceDeclaration */ + || kind === 262 /* SyntaxKind.TypeAliasDeclaration */ + || kind === 263 /* SyntaxKind.EnumDeclaration */ + || kind === 264 /* SyntaxKind.ModuleDeclaration */ + || kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ + || kind === 269 /* SyntaxKind.ImportDeclaration */ + || kind === 274 /* SyntaxKind.ExportAssignment */ + || kind === 275 /* SyntaxKind.ExportDeclaration */; } ts.canHaveModifiers = canHaveModifiers; function canHaveDecorators(node) { var kind = node.kind; - return kind === 164 /* SyntaxKind.Parameter */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */ - || kind === 226 /* SyntaxKind.ClassExpression */ - || kind === 257 /* SyntaxKind.ClassDeclaration */; + return kind === 166 /* SyntaxKind.Parameter */ + || kind === 169 /* SyntaxKind.PropertyDeclaration */ + || kind === 171 /* SyntaxKind.MethodDeclaration */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 175 /* SyntaxKind.SetAccessor */ + || kind === 228 /* SyntaxKind.ClassExpression */ + || kind === 260 /* SyntaxKind.ClassDeclaration */; } ts.canHaveDecorators = canHaveDecorators; })(ts || (ts = {})); var ts; (function (ts) { + var _a; var SignatureFlags; (function (SignatureFlags) { SignatureFlags[SignatureFlags["None"] = 0] = "None"; @@ -31136,6 +31255,718 @@ var ts; function isImportMeta(node) { return ts.isMetaProperty(node) && node.keywordToken === 100 /* SyntaxKind.ImportKeyword */ && node.name.escapedText === "meta"; } + var forEachChildTable = (_a = {}, + _a[163 /* SyntaxKind.QualifiedName */] = function forEachChildInQualifiedName(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + }, + _a[165 /* SyntaxKind.TypeParameter */] = function forEachChildInTypeParameter(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + }, + _a[300 /* SyntaxKind.ShorthandPropertyAssignment */] = function forEachChildInShorthandPropertyAssignment(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + }, + _a[301 /* SyntaxKind.SpreadAssignment */] = function forEachChildInSpreadAssignment(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[166 /* SyntaxKind.Parameter */] = function forEachChildInParameter(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + }, + _a[169 /* SyntaxKind.PropertyDeclaration */] = function forEachChildInPropertyDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + }, + _a[168 /* SyntaxKind.PropertySignature */] = function forEachChildInPropertySignature(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + }, + _a[299 /* SyntaxKind.PropertyAssignment */] = function forEachChildInPropertyAssignment(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.initializer); + }, + _a[257 /* SyntaxKind.VariableDeclaration */] = function forEachChildInVariableDeclaration(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + }, + _a[205 /* SyntaxKind.BindingElement */] = function forEachChildInBindingElement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + }, + _a[178 /* SyntaxKind.IndexSignature */] = function forEachChildInIndexSignature(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + }, + _a[182 /* SyntaxKind.ConstructorType */] = function forEachChildInConstructorType(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + }, + _a[181 /* SyntaxKind.FunctionType */] = function forEachChildInFunctionType(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + }, + _a[176 /* SyntaxKind.CallSignature */] = forEachChildInCallOrConstructSignature, + _a[177 /* SyntaxKind.ConstructSignature */] = forEachChildInCallOrConstructSignature, + _a[171 /* SyntaxKind.MethodDeclaration */] = function forEachChildInMethodDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + }, + _a[170 /* SyntaxKind.MethodSignature */] = function forEachChildInMethodSignature(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + }, + _a[173 /* SyntaxKind.Constructor */] = function forEachChildInConstructor(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + }, + _a[174 /* SyntaxKind.GetAccessor */] = function forEachChildInGetAccessor(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + }, + _a[175 /* SyntaxKind.SetAccessor */] = function forEachChildInSetAccessor(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + }, + _a[259 /* SyntaxKind.FunctionDeclaration */] = function forEachChildInFunctionDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + }, + _a[215 /* SyntaxKind.FunctionExpression */] = function forEachChildInFunctionExpression(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + }, + _a[216 /* SyntaxKind.ArrowFunction */] = function forEachChildInArrowFunction(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + }, + _a[172 /* SyntaxKind.ClassStaticBlockDeclaration */] = function forEachChildInClassStaticBlockDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.body); + }, + _a[180 /* SyntaxKind.TypeReference */] = function forEachChildInTypeReference(node, cbNode, cbNodes) { + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + }, + _a[179 /* SyntaxKind.TypePredicate */] = function forEachChildInTypePredicate(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.assertsModifier) || + visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + }, + _a[183 /* SyntaxKind.TypeQuery */] = function forEachChildInTypeQuery(node, cbNode, cbNodes) { + return visitNode(cbNode, node.exprName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + }, + _a[184 /* SyntaxKind.TypeLiteral */] = function forEachChildInTypeLiteral(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.members); + }, + _a[185 /* SyntaxKind.ArrayType */] = function forEachChildInArrayType(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.elementType); + }, + _a[186 /* SyntaxKind.TupleType */] = function forEachChildInTupleType(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); + }, + _a[189 /* SyntaxKind.UnionType */] = forEachChildInUnionOrIntersectionType, + _a[190 /* SyntaxKind.IntersectionType */] = forEachChildInUnionOrIntersectionType, + _a[191 /* SyntaxKind.ConditionalType */] = function forEachChildInConditionalType(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.checkType) || + visitNode(cbNode, node.extendsType) || + visitNode(cbNode, node.trueType) || + visitNode(cbNode, node.falseType); + }, + _a[192 /* SyntaxKind.InferType */] = function forEachChildInInferType(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.typeParameter); + }, + _a[202 /* SyntaxKind.ImportType */] = function forEachChildInImportType(node, cbNode, cbNodes) { + return visitNode(cbNode, node.argument) || + visitNode(cbNode, node.assertions) || + visitNode(cbNode, node.qualifier) || + visitNodes(cbNode, cbNodes, node.typeArguments); + }, + _a[298 /* SyntaxKind.ImportTypeAssertionContainer */] = function forEachChildInImportTypeAssertionContainer(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.assertClause); + }, + _a[193 /* SyntaxKind.ParenthesizedType */] = forEachChildInParenthesizedTypeOrTypeOperator, + _a[195 /* SyntaxKind.TypeOperator */] = forEachChildInParenthesizedTypeOrTypeOperator, + _a[196 /* SyntaxKind.IndexedAccessType */] = function forEachChildInIndexedAccessType(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + }, + _a[197 /* SyntaxKind.MappedType */] = function forEachChildInMappedType(node, cbNode, cbNodes) { + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.nameType) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNodes(cbNode, cbNodes, node.members); + }, + _a[198 /* SyntaxKind.LiteralType */] = function forEachChildInLiteralType(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.literal); + }, + _a[199 /* SyntaxKind.NamedTupleMember */] = function forEachChildInNamedTupleMember(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + }, + _a[203 /* SyntaxKind.ObjectBindingPattern */] = forEachChildInObjectOrArrayBindingPattern, + _a[204 /* SyntaxKind.ArrayBindingPattern */] = forEachChildInObjectOrArrayBindingPattern, + _a[206 /* SyntaxKind.ArrayLiteralExpression */] = function forEachChildInArrayLiteralExpression(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); + }, + _a[207 /* SyntaxKind.ObjectLiteralExpression */] = function forEachChildInObjectLiteralExpression(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.properties); + }, + _a[208 /* SyntaxKind.PropertyAccessExpression */] = function forEachChildInPropertyAccessExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.questionDotToken) || + visitNode(cbNode, node.name); + }, + _a[209 /* SyntaxKind.ElementAccessExpression */] = function forEachChildInElementAccessExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.questionDotToken) || + visitNode(cbNode, node.argumentExpression); + }, + _a[210 /* SyntaxKind.CallExpression */] = forEachChildInCallOrNewExpression, + _a[211 /* SyntaxKind.NewExpression */] = forEachChildInCallOrNewExpression, + _a[212 /* SyntaxKind.TaggedTemplateExpression */] = function forEachChildInTaggedTemplateExpression(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tag) || + visitNode(cbNode, node.questionDotToken) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.template); + }, + _a[213 /* SyntaxKind.TypeAssertionExpression */] = function forEachChildInTypeAssertionExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + }, + _a[214 /* SyntaxKind.ParenthesizedExpression */] = function forEachChildInParenthesizedExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[217 /* SyntaxKind.DeleteExpression */] = function forEachChildInDeleteExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[218 /* SyntaxKind.TypeOfExpression */] = function forEachChildInTypeOfExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[219 /* SyntaxKind.VoidExpression */] = function forEachChildInVoidExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[221 /* SyntaxKind.PrefixUnaryExpression */] = function forEachChildInPrefixUnaryExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.operand); + }, + _a[226 /* SyntaxKind.YieldExpression */] = function forEachChildInYieldExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + }, + _a[220 /* SyntaxKind.AwaitExpression */] = function forEachChildInAwaitExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[222 /* SyntaxKind.PostfixUnaryExpression */] = function forEachChildInPostfixUnaryExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.operand); + }, + _a[223 /* SyntaxKind.BinaryExpression */] = function forEachChildInBinaryExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + }, + _a[231 /* SyntaxKind.AsExpression */] = function forEachChildInAsExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + }, + _a[232 /* SyntaxKind.NonNullExpression */] = function forEachChildInNonNullExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[235 /* SyntaxKind.SatisfiesExpression */] = function forEachChildInSatisfiesExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); + }, + _a[233 /* SyntaxKind.MetaProperty */] = function forEachChildInMetaProperty(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.name); + }, + _a[224 /* SyntaxKind.ConditionalExpression */] = function forEachChildInConditionalExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + }, + _a[227 /* SyntaxKind.SpreadElement */] = function forEachChildInSpreadElement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[238 /* SyntaxKind.Block */] = forEachChildInBlock, + _a[265 /* SyntaxKind.ModuleBlock */] = forEachChildInBlock, + _a[308 /* SyntaxKind.SourceFile */] = function forEachChildInSourceFile(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + }, + _a[240 /* SyntaxKind.VariableStatement */] = function forEachChildInVariableStatement(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + }, + _a[258 /* SyntaxKind.VariableDeclarationList */] = function forEachChildInVariableDeclarationList(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.declarations); + }, + _a[241 /* SyntaxKind.ExpressionStatement */] = function forEachChildInExpressionStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[242 /* SyntaxKind.IfStatement */] = function forEachChildInIfStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + }, + _a[243 /* SyntaxKind.DoStatement */] = function forEachChildInDoStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + }, + _a[244 /* SyntaxKind.WhileStatement */] = function forEachChildInWhileStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + }, + _a[245 /* SyntaxKind.ForStatement */] = function forEachChildInForStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + }, + _a[246 /* SyntaxKind.ForInStatement */] = function forEachChildInForInStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + }, + _a[247 /* SyntaxKind.ForOfStatement */] = function forEachChildInForOfStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + }, + _a[248 /* SyntaxKind.ContinueStatement */] = forEachChildInContinueOrBreakStatement, + _a[249 /* SyntaxKind.BreakStatement */] = forEachChildInContinueOrBreakStatement, + _a[250 /* SyntaxKind.ReturnStatement */] = function forEachChildInReturnStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[251 /* SyntaxKind.WithStatement */] = function forEachChildInWithStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + }, + _a[252 /* SyntaxKind.SwitchStatement */] = function forEachChildInSwitchStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + }, + _a[266 /* SyntaxKind.CaseBlock */] = function forEachChildInCaseBlock(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.clauses); + }, + _a[292 /* SyntaxKind.CaseClause */] = function forEachChildInCaseClause(node, cbNode, cbNodes) { + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + }, + _a[293 /* SyntaxKind.DefaultClause */] = function forEachChildInDefaultClause(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.statements); + }, + _a[253 /* SyntaxKind.LabeledStatement */] = function forEachChildInLabeledStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + }, + _a[254 /* SyntaxKind.ThrowStatement */] = function forEachChildInThrowStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[255 /* SyntaxKind.TryStatement */] = function forEachChildInTryStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + }, + _a[295 /* SyntaxKind.CatchClause */] = function forEachChildInCatchClause(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + }, + _a[167 /* SyntaxKind.Decorator */] = function forEachChildInDecorator(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[260 /* SyntaxKind.ClassDeclaration */] = forEachChildInClassDeclarationOrExpression, + _a[228 /* SyntaxKind.ClassExpression */] = forEachChildInClassDeclarationOrExpression, + _a[261 /* SyntaxKind.InterfaceDeclaration */] = function forEachChildInInterfaceDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + }, + _a[262 /* SyntaxKind.TypeAliasDeclaration */] = function forEachChildInTypeAliasDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + }, + _a[263 /* SyntaxKind.EnumDeclaration */] = function forEachChildInEnumDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + }, + _a[302 /* SyntaxKind.EnumMember */] = function forEachChildInEnumMember(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + }, + _a[264 /* SyntaxKind.ModuleDeclaration */] = function forEachChildInModuleDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + }, + _a[268 /* SyntaxKind.ImportEqualsDeclaration */] = function forEachChildInImportEqualsDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + }, + _a[269 /* SyntaxKind.ImportDeclaration */] = function forEachChildInImportDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier) || + visitNode(cbNode, node.assertClause); + }, + _a[270 /* SyntaxKind.ImportClause */] = function forEachChildInImportClause(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + }, + _a[296 /* SyntaxKind.AssertClause */] = function forEachChildInAssertClause(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); + }, + _a[297 /* SyntaxKind.AssertEntry */] = function forEachChildInAssertEntry(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.value); + }, + _a[267 /* SyntaxKind.NamespaceExportDeclaration */] = function forEachChildInNamespaceExportDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNode(cbNode, node.name); + }, + _a[271 /* SyntaxKind.NamespaceImport */] = function forEachChildInNamespaceImport(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.name); + }, + _a[277 /* SyntaxKind.NamespaceExport */] = function forEachChildInNamespaceExport(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.name); + }, + _a[272 /* SyntaxKind.NamedImports */] = forEachChildInNamedImportsOrExports, + _a[276 /* SyntaxKind.NamedExports */] = forEachChildInNamedImportsOrExports, + _a[275 /* SyntaxKind.ExportDeclaration */] = function forEachChildInExportDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier) || + visitNode(cbNode, node.assertClause); + }, + _a[273 /* SyntaxKind.ImportSpecifier */] = forEachChildInImportOrExportSpecifier, + _a[278 /* SyntaxKind.ExportSpecifier */] = forEachChildInImportOrExportSpecifier, + _a[274 /* SyntaxKind.ExportAssignment */] = function forEachChildInExportAssignment(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + }, + _a[225 /* SyntaxKind.TemplateExpression */] = function forEachChildInTemplateExpression(node, cbNode, cbNodes) { + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); + }, + _a[236 /* SyntaxKind.TemplateSpan */] = function forEachChildInTemplateSpan(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.literal); + }, + _a[200 /* SyntaxKind.TemplateLiteralType */] = function forEachChildInTemplateLiteralType(node, cbNode, cbNodes) { + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); + }, + _a[201 /* SyntaxKind.TemplateLiteralTypeSpan */] = function forEachChildInTemplateLiteralTypeSpan(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.literal); + }, + _a[164 /* SyntaxKind.ComputedPropertyName */] = function forEachChildInComputedPropertyName(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[294 /* SyntaxKind.HeritageClause */] = function forEachChildInHeritageClause(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.types); + }, + _a[230 /* SyntaxKind.ExpressionWithTypeArguments */] = function forEachChildInExpressionWithTypeArguments(node, cbNode, cbNodes) { + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + }, + _a[280 /* SyntaxKind.ExternalModuleReference */] = function forEachChildInExternalModuleReference(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[279 /* SyntaxKind.MissingDeclaration */] = function forEachChildInMissingDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers); + }, + _a[354 /* SyntaxKind.CommaListExpression */] = function forEachChildInCommaListExpression(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); + }, + _a[281 /* SyntaxKind.JsxElement */] = function forEachChildInJsxElement(node, cbNode, cbNodes) { + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + }, + _a[285 /* SyntaxKind.JsxFragment */] = function forEachChildInJsxFragment(node, cbNode, cbNodes) { + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); + }, + _a[282 /* SyntaxKind.JsxSelfClosingElement */] = forEachChildInJsxOpeningOrSelfClosingElement, + _a[283 /* SyntaxKind.JsxOpeningElement */] = forEachChildInJsxOpeningOrSelfClosingElement, + _a[289 /* SyntaxKind.JsxAttributes */] = function forEachChildInJsxAttributes(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.properties); + }, + _a[288 /* SyntaxKind.JsxAttribute */] = function forEachChildInJsxAttribute(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + }, + _a[290 /* SyntaxKind.JsxSpreadAttribute */] = function forEachChildInJsxSpreadAttribute(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + }, + _a[291 /* SyntaxKind.JsxExpression */] = function forEachChildInJsxExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + }, + _a[284 /* SyntaxKind.JsxClosingElement */] = function forEachChildInJsxClosingElement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.tagName); + }, + _a[187 /* SyntaxKind.OptionalType */] = forEachChildInOptionalRestOrJSDocParameterModifier, + _a[188 /* SyntaxKind.RestType */] = forEachChildInOptionalRestOrJSDocParameterModifier, + _a[312 /* SyntaxKind.JSDocTypeExpression */] = forEachChildInOptionalRestOrJSDocParameterModifier, + _a[318 /* SyntaxKind.JSDocNonNullableType */] = forEachChildInOptionalRestOrJSDocParameterModifier, + _a[317 /* SyntaxKind.JSDocNullableType */] = forEachChildInOptionalRestOrJSDocParameterModifier, + _a[319 /* SyntaxKind.JSDocOptionalType */] = forEachChildInOptionalRestOrJSDocParameterModifier, + _a[321 /* SyntaxKind.JSDocVariadicType */] = forEachChildInOptionalRestOrJSDocParameterModifier, + _a[320 /* SyntaxKind.JSDocFunctionType */] = function forEachChildInJSDocFunctionType(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + }, + _a[323 /* SyntaxKind.JSDoc */] = function forEachChildInJSDoc(node, cbNode, cbNodes) { + return (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) + || visitNodes(cbNode, cbNodes, node.tags); + }, + _a[349 /* SyntaxKind.JSDocSeeTag */] = function forEachChildInJSDocSeeTag(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.name) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + }, + _a[313 /* SyntaxKind.JSDocNameReference */] = function forEachChildInJSDocNameReference(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.name); + }, + _a[314 /* SyntaxKind.JSDocMemberName */] = function forEachChildInJSDocMemberName(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + }, + _a[343 /* SyntaxKind.JSDocParameterTag */] = forEachChildInJSDocParameterOrPropertyTag, + _a[350 /* SyntaxKind.JSDocPropertyTag */] = forEachChildInJSDocParameterOrPropertyTag, + _a[333 /* SyntaxKind.JSDocAuthorTag */] = function forEachChildInJSDocAuthorTag(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tagName) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + }, + _a[332 /* SyntaxKind.JSDocImplementsTag */] = function forEachChildInJSDocImplementsTag(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + }, + _a[331 /* SyntaxKind.JSDocAugmentsTag */] = function forEachChildInJSDocAugmentsTag(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + }, + _a[347 /* SyntaxKind.JSDocTemplateTag */] = function forEachChildInJSDocTemplateTag(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.constraint) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + }, + _a[348 /* SyntaxKind.JSDocTypedefTag */] = function forEachChildInJSDocTypedefTag(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tagName) || + (node.typeExpression && + node.typeExpression.kind === 312 /* SyntaxKind.JSDocTypeExpression */ + ? visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) + : visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))); + }, + _a[341 /* SyntaxKind.JSDocCallbackTag */] = function forEachChildInJSDocCallbackTag(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + }, + _a[344 /* SyntaxKind.JSDocReturnTag */] = forEachChildInJSDocReturnTag, + _a[346 /* SyntaxKind.JSDocTypeTag */] = forEachChildInJSDocReturnTag, + _a[345 /* SyntaxKind.JSDocThisTag */] = forEachChildInJSDocReturnTag, + _a[342 /* SyntaxKind.JSDocEnumTag */] = forEachChildInJSDocReturnTag, + _a[326 /* SyntaxKind.JSDocSignature */] = function forEachChildInJSDocSignature(node, cbNode, _cbNodes) { + return ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || + visitNode(cbNode, node.type); + }, + _a[327 /* SyntaxKind.JSDocLink */] = forEachChildInJSDocLinkCodeOrPlain, + _a[328 /* SyntaxKind.JSDocLinkCode */] = forEachChildInJSDocLinkCodeOrPlain, + _a[329 /* SyntaxKind.JSDocLinkPlain */] = forEachChildInJSDocLinkCodeOrPlain, + _a[325 /* SyntaxKind.JSDocTypeLiteral */] = function forEachChildInJSDocTypeLiteral(node, cbNode, _cbNodes) { + return ts.forEach(node.jsDocPropertyTags, cbNode); + }, + _a[330 /* SyntaxKind.JSDocTag */] = forEachChildInJSDocTag, + _a[335 /* SyntaxKind.JSDocClassTag */] = forEachChildInJSDocTag, + _a[336 /* SyntaxKind.JSDocPublicTag */] = forEachChildInJSDocTag, + _a[337 /* SyntaxKind.JSDocPrivateTag */] = forEachChildInJSDocTag, + _a[338 /* SyntaxKind.JSDocProtectedTag */] = forEachChildInJSDocTag, + _a[339 /* SyntaxKind.JSDocReadonlyTag */] = forEachChildInJSDocTag, + _a[334 /* SyntaxKind.JSDocDeprecatedTag */] = forEachChildInJSDocTag, + _a[340 /* SyntaxKind.JSDocOverrideTag */] = forEachChildInJSDocTag, + _a[353 /* SyntaxKind.PartiallyEmittedExpression */] = forEachChildInPartiallyEmittedExpression, + _a); + // shared + function forEachChildInCallOrConstructSignature(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + } + function forEachChildInUnionOrIntersectionType(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.types); + } + function forEachChildInParenthesizedTypeOrTypeOperator(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.type); + } + function forEachChildInObjectOrArrayBindingPattern(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); + } + function forEachChildInCallOrNewExpression(node, cbNode, cbNodes) { + return visitNode(cbNode, node.expression) || + // TODO: should we separate these branches out? + visitNode(cbNode, node.questionDotToken) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + } + function forEachChildInBlock(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.statements); + } + function forEachChildInContinueOrBreakStatement(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.label); + } + function forEachChildInClassDeclarationOrExpression(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + } + function forEachChildInNamedImportsOrExports(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); + } + function forEachChildInImportOrExportSpecifier(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + } + function forEachChildInJsxOpeningOrSelfClosingElement(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNode(cbNode, node.attributes); + } + function forEachChildInOptionalRestOrJSDocParameterModifier(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.type); + } + function forEachChildInJSDocParameterOrPropertyTag(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tagName) || + (node.isNameFirst + ? visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + } + function forEachChildInJSDocReturnTag(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + } + function forEachChildInJSDocLinkCodeOrPlain(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.name); + } + function forEachChildInJSDocTag(node, cbNode, cbNodes) { + return visitNode(cbNode, node.tagName) + || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + } + function forEachChildInPartiallyEmittedExpression(node, cbNode, _cbNodes) { + return visitNode(cbNode, node.expression); + } /** * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, @@ -31150,562 +31981,11 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 160 /* SyntaxKind.LastToken */) { + if (node === undefined || node.kind <= 162 /* SyntaxKind.LastToken */) { return; } - switch (node.kind) { - case 161 /* SyntaxKind.QualifiedName */: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.right); - case 163 /* SyntaxKind.TypeParameter */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.constraint) || - visitNode(cbNode, node.default) || - visitNode(cbNode, node.expression); - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.exclamationToken) || - visitNode(cbNode, node.equalsToken) || - visitNode(cbNode, node.objectAssignmentInitializer); - case 298 /* SyntaxKind.SpreadAssignment */: - return visitNode(cbNode, node.expression); - case 164 /* SyntaxKind.Parameter */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); - case 167 /* SyntaxKind.PropertyDeclaration */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.exclamationToken) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); - case 166 /* SyntaxKind.PropertySignature */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); - case 296 /* SyntaxKind.PropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.exclamationToken) || - visitNode(cbNode, node.initializer); - case 254 /* SyntaxKind.VariableDeclaration */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.exclamationToken) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); - case 203 /* SyntaxKind.BindingElement */: - return visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 176 /* SyntaxKind.IndexSignature */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 180 /* SyntaxKind.ConstructorType */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 179 /* SyntaxKind.FunctionType */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - return visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 169 /* SyntaxKind.MethodDeclaration */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.exclamationToken) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); - case 168 /* SyntaxKind.MethodSignature */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 171 /* SyntaxKind.Constructor */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); - case 172 /* SyntaxKind.GetAccessor */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); - case 173 /* SyntaxKind.SetAccessor */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); - case 256 /* SyntaxKind.FunctionDeclaration */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); - case 213 /* SyntaxKind.FunctionExpression */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); - case 214 /* SyntaxKind.ArrowFunction */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.equalsGreaterThanToken) || - visitNode(cbNode, node.body); - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.body); - case 178 /* SyntaxKind.TypeReference */: - return visitNode(cbNode, node.typeName) || - visitNodes(cbNode, cbNodes, node.typeArguments); - case 177 /* SyntaxKind.TypePredicate */: - return visitNode(cbNode, node.assertsModifier) || - visitNode(cbNode, node.parameterName) || - visitNode(cbNode, node.type); - case 181 /* SyntaxKind.TypeQuery */: - return visitNode(cbNode, node.exprName) || - visitNodes(cbNode, cbNodes, node.typeArguments); - case 182 /* SyntaxKind.TypeLiteral */: - return visitNodes(cbNode, cbNodes, node.members); - case 183 /* SyntaxKind.ArrayType */: - return visitNode(cbNode, node.elementType); - case 184 /* SyntaxKind.TupleType */: - return visitNodes(cbNode, cbNodes, node.elements); - case 187 /* SyntaxKind.UnionType */: - case 188 /* SyntaxKind.IntersectionType */: - return visitNodes(cbNode, cbNodes, node.types); - case 189 /* SyntaxKind.ConditionalType */: - return visitNode(cbNode, node.checkType) || - visitNode(cbNode, node.extendsType) || - visitNode(cbNode, node.trueType) || - visitNode(cbNode, node.falseType); - case 190 /* SyntaxKind.InferType */: - return visitNode(cbNode, node.typeParameter); - case 200 /* SyntaxKind.ImportType */: - return visitNode(cbNode, node.argument) || - visitNode(cbNode, node.assertions) || - visitNode(cbNode, node.qualifier) || - visitNodes(cbNode, cbNodes, node.typeArguments); - case 295 /* SyntaxKind.ImportTypeAssertionContainer */: - return visitNode(cbNode, node.assertClause); - case 191 /* SyntaxKind.ParenthesizedType */: - case 193 /* SyntaxKind.TypeOperator */: - return visitNode(cbNode, node.type); - case 194 /* SyntaxKind.IndexedAccessType */: - return visitNode(cbNode, node.objectType) || - visitNode(cbNode, node.indexType); - case 195 /* SyntaxKind.MappedType */: - return visitNode(cbNode, node.readonlyToken) || - visitNode(cbNode, node.typeParameter) || - visitNode(cbNode, node.nameType) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type) || - visitNodes(cbNode, cbNodes, node.members); - case 196 /* SyntaxKind.LiteralType */: - return visitNode(cbNode, node.literal); - case 197 /* SyntaxKind.NamedTupleMember */: - return visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 202 /* SyntaxKind.ArrayBindingPattern */: - return visitNodes(cbNode, cbNodes, node.elements); - case 204 /* SyntaxKind.ArrayLiteralExpression */: - return visitNodes(cbNode, cbNodes, node.elements); - case 205 /* SyntaxKind.ObjectLiteralExpression */: - return visitNodes(cbNode, cbNodes, node.properties); - case 206 /* SyntaxKind.PropertyAccessExpression */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.questionDotToken) || - visitNode(cbNode, node.name); - case 207 /* SyntaxKind.ElementAccessExpression */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.questionDotToken) || - visitNode(cbNode, node.argumentExpression); - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.questionDotToken) || - visitNodes(cbNode, cbNodes, node.typeArguments) || - visitNodes(cbNode, cbNodes, node.arguments); - case 210 /* SyntaxKind.TaggedTemplateExpression */: - return visitNode(cbNode, node.tag) || - visitNode(cbNode, node.questionDotToken) || - visitNodes(cbNode, cbNodes, node.typeArguments) || - visitNode(cbNode, node.template); - case 211 /* SyntaxKind.TypeAssertionExpression */: - return visitNode(cbNode, node.type) || - visitNode(cbNode, node.expression); - case 212 /* SyntaxKind.ParenthesizedExpression */: - return visitNode(cbNode, node.expression); - case 215 /* SyntaxKind.DeleteExpression */: - return visitNode(cbNode, node.expression); - case 216 /* SyntaxKind.TypeOfExpression */: - return visitNode(cbNode, node.expression); - case 217 /* SyntaxKind.VoidExpression */: - return visitNode(cbNode, node.expression); - case 219 /* SyntaxKind.PrefixUnaryExpression */: - return visitNode(cbNode, node.operand); - case 224 /* SyntaxKind.YieldExpression */: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); - case 218 /* SyntaxKind.AwaitExpression */: - return visitNode(cbNode, node.expression); - case 220 /* SyntaxKind.PostfixUnaryExpression */: - return visitNode(cbNode, node.operand); - case 221 /* SyntaxKind.BinaryExpression */: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.operatorToken) || - visitNode(cbNode, node.right); - case 229 /* SyntaxKind.AsExpression */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.type); - case 230 /* SyntaxKind.NonNullExpression */: - return visitNode(cbNode, node.expression); - case 231 /* SyntaxKind.MetaProperty */: - return visitNode(cbNode, node.name); - case 222 /* SyntaxKind.ConditionalExpression */: - return visitNode(cbNode, node.condition) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.whenTrue) || - visitNode(cbNode, node.colonToken) || - visitNode(cbNode, node.whenFalse); - case 225 /* SyntaxKind.SpreadElement */: - return visitNode(cbNode, node.expression); - case 235 /* SyntaxKind.Block */: - case 262 /* SyntaxKind.ModuleBlock */: - return visitNodes(cbNode, cbNodes, node.statements); - case 305 /* SyntaxKind.SourceFile */: - return visitNodes(cbNode, cbNodes, node.statements) || - visitNode(cbNode, node.endOfFileToken); - case 237 /* SyntaxKind.VariableStatement */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.declarationList); - case 255 /* SyntaxKind.VariableDeclarationList */: - return visitNodes(cbNode, cbNodes, node.declarations); - case 238 /* SyntaxKind.ExpressionStatement */: - return visitNode(cbNode, node.expression); - case 239 /* SyntaxKind.IfStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.thenStatement) || - visitNode(cbNode, node.elseStatement); - case 240 /* SyntaxKind.DoStatement */: - return visitNode(cbNode, node.statement) || - visitNode(cbNode, node.expression); - case 241 /* SyntaxKind.WhileStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 242 /* SyntaxKind.ForStatement */: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.condition) || - visitNode(cbNode, node.incrementor) || - visitNode(cbNode, node.statement); - case 243 /* SyntaxKind.ForInStatement */: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 244 /* SyntaxKind.ForOfStatement */: - return visitNode(cbNode, node.awaitModifier) || - visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 245 /* SyntaxKind.ContinueStatement */: - case 246 /* SyntaxKind.BreakStatement */: - return visitNode(cbNode, node.label); - case 247 /* SyntaxKind.ReturnStatement */: - return visitNode(cbNode, node.expression); - case 248 /* SyntaxKind.WithStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 249 /* SyntaxKind.SwitchStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 263 /* SyntaxKind.CaseBlock */: - return visitNodes(cbNode, cbNodes, node.clauses); - case 289 /* SyntaxKind.CaseClause */: - return visitNode(cbNode, node.expression) || - visitNodes(cbNode, cbNodes, node.statements); - case 290 /* SyntaxKind.DefaultClause */: - return visitNodes(cbNode, cbNodes, node.statements); - case 250 /* SyntaxKind.LabeledStatement */: - return visitNode(cbNode, node.label) || - visitNode(cbNode, node.statement); - case 251 /* SyntaxKind.ThrowStatement */: - return visitNode(cbNode, node.expression); - case 252 /* SyntaxKind.TryStatement */: - return visitNode(cbNode, node.tryBlock) || - visitNode(cbNode, node.catchClause) || - visitNode(cbNode, node.finallyBlock); - case 292 /* SyntaxKind.CatchClause */: - return visitNode(cbNode, node.variableDeclaration) || - visitNode(cbNode, node.block); - case 165 /* SyntaxKind.Decorator */: - return visitNode(cbNode, node.expression); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.heritageClauses) || - visitNodes(cbNode, cbNodes, node.members); - case 258 /* SyntaxKind.InterfaceDeclaration */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.heritageClauses) || - visitNodes(cbNode, cbNodes, node.members); - case 259 /* SyntaxKind.TypeAliasDeclaration */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNode(cbNode, node.type); - case 260 /* SyntaxKind.EnumDeclaration */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.members); - case 299 /* SyntaxKind.EnumMember */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 261 /* SyntaxKind.ModuleDeclaration */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); - case 266 /* SyntaxKind.ImportDeclaration */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.importClause) || - visitNode(cbNode, node.moduleSpecifier) || - visitNode(cbNode, node.assertClause); - case 267 /* SyntaxKind.ImportClause */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.namedBindings); - case 293 /* SyntaxKind.AssertClause */: - return visitNodes(cbNode, cbNodes, node.elements); - case 294 /* SyntaxKind.AssertEntry */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.value); - case 264 /* SyntaxKind.NamespaceExportDeclaration */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNode(cbNode, node.name); - case 268 /* SyntaxKind.NamespaceImport */: - return visitNode(cbNode, node.name); - case 274 /* SyntaxKind.NamespaceExport */: - return visitNode(cbNode, node.name); - case 269 /* SyntaxKind.NamedImports */: - case 273 /* SyntaxKind.NamedExports */: - return visitNodes(cbNode, cbNodes, node.elements); - case 272 /* SyntaxKind.ExportDeclaration */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.exportClause) || - visitNode(cbNode, node.moduleSpecifier) || - visitNode(cbNode, node.assertClause); - case 270 /* SyntaxKind.ImportSpecifier */: - case 275 /* SyntaxKind.ExportSpecifier */: - return visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.name); - case 271 /* SyntaxKind.ExportAssignment */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.expression); - case 223 /* SyntaxKind.TemplateExpression */: - return visitNode(cbNode, node.head) || - visitNodes(cbNode, cbNodes, node.templateSpans); - case 233 /* SyntaxKind.TemplateSpan */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.literal); - case 198 /* SyntaxKind.TemplateLiteralType */: - return visitNode(cbNode, node.head) || - visitNodes(cbNode, cbNodes, node.templateSpans); - case 199 /* SyntaxKind.TemplateLiteralTypeSpan */: - return visitNode(cbNode, node.type) || - visitNode(cbNode, node.literal); - case 162 /* SyntaxKind.ComputedPropertyName */: - return visitNode(cbNode, node.expression); - case 291 /* SyntaxKind.HeritageClause */: - return visitNodes(cbNode, cbNodes, node.types); - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: - return visitNode(cbNode, node.expression) || - visitNodes(cbNode, cbNodes, node.typeArguments); - case 277 /* SyntaxKind.ExternalModuleReference */: - return visitNode(cbNode, node.expression); - case 276 /* SyntaxKind.MissingDeclaration */: - return visitNodes(cbNode, cbNodes, node.illegalDecorators) || - visitNodes(cbNode, cbNodes, node.modifiers); - case 351 /* SyntaxKind.CommaListExpression */: - return visitNodes(cbNode, cbNodes, node.elements); - case 278 /* SyntaxKind.JsxElement */: - return visitNode(cbNode, node.openingElement) || - visitNodes(cbNode, cbNodes, node.children) || - visitNode(cbNode, node.closingElement); - case 282 /* SyntaxKind.JsxFragment */: - return visitNode(cbNode, node.openingFragment) || - visitNodes(cbNode, cbNodes, node.children) || - visitNode(cbNode, node.closingFragment); - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 280 /* SyntaxKind.JsxOpeningElement */: - return visitNode(cbNode, node.tagName) || - visitNodes(cbNode, cbNodes, node.typeArguments) || - visitNode(cbNode, node.attributes); - case 286 /* SyntaxKind.JsxAttributes */: - return visitNodes(cbNode, cbNodes, node.properties); - case 285 /* SyntaxKind.JsxAttribute */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 287 /* SyntaxKind.JsxSpreadAttribute */: - return visitNode(cbNode, node.expression); - case 288 /* SyntaxKind.JsxExpression */: - return visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.expression); - case 281 /* SyntaxKind.JsxClosingElement */: - return visitNode(cbNode, node.tagName); - case 185 /* SyntaxKind.OptionalType */: - case 186 /* SyntaxKind.RestType */: - case 309 /* SyntaxKind.JSDocTypeExpression */: - case 315 /* SyntaxKind.JSDocNonNullableType */: - case 314 /* SyntaxKind.JSDocNullableType */: - case 316 /* SyntaxKind.JSDocOptionalType */: - case 318 /* SyntaxKind.JSDocVariadicType */: - return visitNode(cbNode, node.type); - case 317 /* SyntaxKind.JSDocFunctionType */: - return visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 320 /* SyntaxKind.JSDoc */: - return (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) - || visitNodes(cbNode, cbNodes, node.tags); - case 346 /* SyntaxKind.JSDocSeeTag */: - return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.name) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); - case 310 /* SyntaxKind.JSDocNameReference */: - return visitNode(cbNode, node.name); - case 311 /* SyntaxKind.JSDocMemberName */: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.right); - case 340 /* SyntaxKind.JSDocParameterTag */: - case 347 /* SyntaxKind.JSDocPropertyTag */: - return visitNode(cbNode, node.tagName) || - (node.isNameFirst - ? visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) - : visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))); - case 330 /* SyntaxKind.JSDocAuthorTag */: - return visitNode(cbNode, node.tagName) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); - case 329 /* SyntaxKind.JSDocImplementsTag */: - return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); - case 328 /* SyntaxKind.JSDocAugmentsTag */: - return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); - case 344 /* SyntaxKind.JSDocTemplateTag */: - return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.constraint) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); - case 345 /* SyntaxKind.JSDocTypedefTag */: - return visitNode(cbNode, node.tagName) || - (node.typeExpression && - node.typeExpression.kind === 309 /* SyntaxKind.JSDocTypeExpression */ - ? visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) - : visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))); - case 338 /* SyntaxKind.JSDocCallbackTag */: - return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); - case 341 /* SyntaxKind.JSDocReturnTag */: - case 343 /* SyntaxKind.JSDocTypeTag */: - case 342 /* SyntaxKind.JSDocThisTag */: - case 339 /* SyntaxKind.JSDocEnumTag */: - return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.typeExpression) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); - case 323 /* SyntaxKind.JSDocSignature */: - return ts.forEach(node.typeParameters, cbNode) || - ts.forEach(node.parameters, cbNode) || - visitNode(cbNode, node.type); - case 324 /* SyntaxKind.JSDocLink */: - case 325 /* SyntaxKind.JSDocLinkCode */: - case 326 /* SyntaxKind.JSDocLinkPlain */: - return visitNode(cbNode, node.name); - case 322 /* SyntaxKind.JSDocTypeLiteral */: - return ts.forEach(node.jsDocPropertyTags, cbNode); - case 327 /* SyntaxKind.JSDocTag */: - case 332 /* SyntaxKind.JSDocClassTag */: - case 333 /* SyntaxKind.JSDocPublicTag */: - case 334 /* SyntaxKind.JSDocPrivateTag */: - case 335 /* SyntaxKind.JSDocProtectedTag */: - case 336 /* SyntaxKind.JSDocReadonlyTag */: - case 331 /* SyntaxKind.JSDocDeprecatedTag */: - return visitNode(cbNode, node.tagName) - || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); - case 350 /* SyntaxKind.PartiallyEmittedExpression */: - return visitNode(cbNode, node.expression); - } + var fn = forEachChildTable[node.kind]; + return fn === undefined ? undefined : fn(node, cbNode, cbNodes); } ts.forEachChild = forEachChild; /** @internal */ @@ -31752,7 +32032,7 @@ var ts; continue; return res; } - if (current.kind >= 161 /* SyntaxKind.FirstNode */) { + if (current.kind >= 163 /* SyntaxKind.FirstNode */) { // add children in reverse order to the queue, so popping gives the first child for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { var child = _a[_i]; @@ -31862,13 +32142,11 @@ var ts; var scanner = ts.createScanner(99 /* ScriptTarget.Latest */, /*skipTrivia*/ true); var disallowInAndDecoratorContext = 4096 /* NodeFlags.DisallowInContext */ | 16384 /* NodeFlags.DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name function countNode(node) { nodeCount++; return node; @@ -32577,7 +32855,7 @@ var ts; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token() === 132 /* SyntaxKind.AwaitKeyword */ && inAwaitContext()) { + if (token() === 133 /* SyntaxKind.AwaitKeyword */ && inAwaitContext()) { return false; } return token() > 116 /* SyntaxKind.LastReservedWord */; @@ -32823,7 +33101,7 @@ var ts; ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) : kind === 8 /* SyntaxKind.NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) : kind === 10 /* SyntaxKind.StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) : - kind === 276 /* SyntaxKind.MissingDeclaration */ ? factory.createMissingDeclaration() : + kind === 279 /* SyntaxKind.MissingDeclaration */ ? factory.createMissingDeclaration() : factory.createToken(kind); return finishNode(result, pos); } @@ -32844,8 +33122,9 @@ var ts; // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); var text = internIdentifier(scanner.getTokenValue()); + var hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape(); nextTokenWithoutCheck(); - return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos); + return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind, hasExtendedUnicodeEscape), pos); } if (token() === 80 /* SyntaxKind.PrivateIdentifier */) { parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); @@ -32922,7 +33201,7 @@ var ts; } function parsePrivateIdentifier() { var pos = getNodePos(); - var node = factory.createPrivateIdentifier(internPrivateIdentifier(scanner.getTokenText())); + var node = factory.createPrivateIdentifier(internPrivateIdentifier(scanner.getTokenValue())); nextToken(); return finishNode(node, pos); } @@ -32946,15 +33225,16 @@ var ts; if (token() === 88 /* SyntaxKind.DefaultKeyword */) { return lookAhead(nextTokenCanFollowDefaultKeyword); } - if (token() === 152 /* SyntaxKind.TypeKeyword */) { + if (token() === 154 /* SyntaxKind.TypeKeyword */) { return lookAhead(nextTokenCanFollowExportModifier); } return canFollowExportModifier(); case 88 /* SyntaxKind.DefaultKeyword */: return nextTokenCanFollowDefaultKeyword(); + case 127 /* SyntaxKind.AccessorKeyword */: case 124 /* SyntaxKind.StaticKeyword */: - case 136 /* SyntaxKind.GetKeyword */: - case 149 /* SyntaxKind.SetKeyword */: + case 137 /* SyntaxKind.GetKeyword */: + case 151 /* SyntaxKind.SetKeyword */: nextToken(); return canFollowModifier(); default: @@ -32963,7 +33243,7 @@ var ts; } function canFollowExportModifier() { return token() !== 41 /* SyntaxKind.AsteriskToken */ - && token() !== 127 /* SyntaxKind.AsKeyword */ + && token() !== 128 /* SyntaxKind.AsKeyword */ && token() !== 18 /* SyntaxKind.OpenBraceToken */ && canFollowModifier(); } @@ -32986,7 +33266,7 @@ var ts; return token() === 84 /* SyntaxKind.ClassKeyword */ || token() === 98 /* SyntaxKind.FunctionKeyword */ || token() === 118 /* SyntaxKind.InterfaceKeyword */ || (token() === 126 /* SyntaxKind.AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 131 /* SyntaxKind.AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + (token() === 132 /* SyntaxKind.AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -33366,20 +33646,20 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 171 /* SyntaxKind.Constructor */: - case 176 /* SyntaxKind.IndexSignature */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 234 /* SyntaxKind.SemicolonClassElement */: + case 173 /* SyntaxKind.Constructor */: + case 178 /* SyntaxKind.IndexSignature */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 237 /* SyntaxKind.SemicolonClassElement */: return true; - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. var methodDeclaration = node; var nameIsConstructor = methodDeclaration.name.kind === 79 /* SyntaxKind.Identifier */ && - methodDeclaration.name.originalKeywordKind === 134 /* SyntaxKind.ConstructorKeyword */; + methodDeclaration.name.originalKeywordKind === 135 /* SyntaxKind.ConstructorKeyword */; return !nameIsConstructor; } } @@ -33388,8 +33668,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: return true; } } @@ -33398,58 +33678,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 237 /* SyntaxKind.VariableStatement */: - case 235 /* SyntaxKind.Block */: - case 239 /* SyntaxKind.IfStatement */: - case 238 /* SyntaxKind.ExpressionStatement */: - case 251 /* SyntaxKind.ThrowStatement */: - case 247 /* SyntaxKind.ReturnStatement */: - case 249 /* SyntaxKind.SwitchStatement */: - case 246 /* SyntaxKind.BreakStatement */: - case 245 /* SyntaxKind.ContinueStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 242 /* SyntaxKind.ForStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 248 /* SyntaxKind.WithStatement */: - case 236 /* SyntaxKind.EmptyStatement */: - case 252 /* SyntaxKind.TryStatement */: - case 250 /* SyntaxKind.LabeledStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 253 /* SyntaxKind.DebuggerStatement */: - case 266 /* SyntaxKind.ImportDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 272 /* SyntaxKind.ExportDeclaration */: - case 271 /* SyntaxKind.ExportAssignment */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 240 /* SyntaxKind.VariableStatement */: + case 238 /* SyntaxKind.Block */: + case 242 /* SyntaxKind.IfStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: + case 254 /* SyntaxKind.ThrowStatement */: + case 250 /* SyntaxKind.ReturnStatement */: + case 252 /* SyntaxKind.SwitchStatement */: + case 249 /* SyntaxKind.BreakStatement */: + case 248 /* SyntaxKind.ContinueStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 251 /* SyntaxKind.WithStatement */: + case 239 /* SyntaxKind.EmptyStatement */: + case 255 /* SyntaxKind.TryStatement */: + case 253 /* SyntaxKind.LabeledStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 256 /* SyntaxKind.DebuggerStatement */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: + case 274 /* SyntaxKind.ExportAssignment */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 299 /* SyntaxKind.EnumMember */; + return node.kind === 302 /* SyntaxKind.EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 175 /* SyntaxKind.ConstructSignature */: - case 168 /* SyntaxKind.MethodSignature */: - case 176 /* SyntaxKind.IndexSignature */: - case 166 /* SyntaxKind.PropertySignature */: - case 174 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 170 /* SyntaxKind.MethodSignature */: + case 178 /* SyntaxKind.IndexSignature */: + case 168 /* SyntaxKind.PropertySignature */: + case 176 /* SyntaxKind.CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 254 /* SyntaxKind.VariableDeclaration */) { + if (node.kind !== 257 /* SyntaxKind.VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -33470,7 +33750,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 164 /* SyntaxKind.Parameter */) { + if (node.kind !== 166 /* SyntaxKind.Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -33763,14 +34043,14 @@ var ts; // If true, we should abort parsing an error function. function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return ts.nodeIsMissing(node.typeName); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: { + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 191 /* SyntaxKind.ParenthesizedType */: + case 193 /* SyntaxKind.ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -33849,7 +34129,7 @@ var ts; function parseJSDocType() { scanner.setInJSDocType(true); var pos = getNodePos(); - if (parseOptional(141 /* SyntaxKind.ModuleKeyword */)) { + if (parseOptional(142 /* SyntaxKind.ModuleKeyword */)) { // TODO(rbuckton): We never set the type for a JSDocNamepathType. What should we put here? var moduleTag = factory.createJSDocNamepathType(/*type*/ undefined); terminate: while (true) { @@ -34065,14 +34345,14 @@ var ts; function parseSignatureMember(kind) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); - if (kind === 175 /* SyntaxKind.ConstructSignature */) { + if (kind === 177 /* SyntaxKind.ConstructSignature */) { parseExpected(103 /* SyntaxKind.NewKeyword */); } var typeParameters = parseTypeParameters(); var parameters = parseParameters(4 /* SignatureFlags.Type */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ true); parseTypeMemberSemicolon(); - var node = kind === 174 /* SyntaxKind.CallSignature */ + var node = kind === 176 /* SyntaxKind.CallSignature */ ? factory.createCallSignature(typeParameters, parameters, type) : factory.createConstructSignature(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -34166,8 +34446,8 @@ var ts; // Return true if we have the start of a signature member if (token() === 20 /* SyntaxKind.OpenParenToken */ || token() === 29 /* SyntaxKind.LessThanToken */ || - token() === 136 /* SyntaxKind.GetKeyword */ || - token() === 149 /* SyntaxKind.SetKeyword */) { + token() === 137 /* SyntaxKind.GetKeyword */ || + token() === 151 /* SyntaxKind.SetKeyword */) { return true; } var idToken = false; @@ -34199,19 +34479,19 @@ var ts; } function parseTypeMember() { if (token() === 20 /* SyntaxKind.OpenParenToken */ || token() === 29 /* SyntaxKind.LessThanToken */) { - return parseSignatureMember(174 /* SyntaxKind.CallSignature */); + return parseSignatureMember(176 /* SyntaxKind.CallSignature */); } if (token() === 103 /* SyntaxKind.NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(175 /* SyntaxKind.ConstructSignature */); + return parseSignatureMember(177 /* SyntaxKind.ConstructSignature */); } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); - if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */, 4 /* SignatureFlags.Type */); + if (parseContextualModifier(137 /* SyntaxKind.GetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 174 /* SyntaxKind.GetAccessor */, 4 /* SignatureFlags.Type */); } - if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */, 4 /* SignatureFlags.Type */); + if (parseContextualModifier(151 /* SyntaxKind.SetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 175 /* SyntaxKind.SetAccessor */, 4 /* SignatureFlags.Type */); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); @@ -34252,9 +34532,9 @@ var ts; function isStartOfMappedType() { nextToken(); if (token() === 39 /* SyntaxKind.PlusToken */ || token() === 40 /* SyntaxKind.MinusToken */) { - return nextToken() === 145 /* SyntaxKind.ReadonlyKeyword */; + return nextToken() === 146 /* SyntaxKind.ReadonlyKeyword */; } - if (token() === 145 /* SyntaxKind.ReadonlyKeyword */) { + if (token() === 146 /* SyntaxKind.ReadonlyKeyword */) { nextToken(); } return token() === 22 /* SyntaxKind.OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 101 /* SyntaxKind.InKeyword */; @@ -34270,15 +34550,15 @@ var ts; var pos = getNodePos(); parseExpected(18 /* SyntaxKind.OpenBraceToken */); var readonlyToken; - if (token() === 145 /* SyntaxKind.ReadonlyKeyword */ || token() === 39 /* SyntaxKind.PlusToken */ || token() === 40 /* SyntaxKind.MinusToken */) { + if (token() === 146 /* SyntaxKind.ReadonlyKeyword */ || token() === 39 /* SyntaxKind.PlusToken */ || token() === 40 /* SyntaxKind.MinusToken */) { readonlyToken = parseTokenNode(); - if (readonlyToken.kind !== 145 /* SyntaxKind.ReadonlyKeyword */) { - parseExpected(145 /* SyntaxKind.ReadonlyKeyword */); + if (readonlyToken.kind !== 146 /* SyntaxKind.ReadonlyKeyword */) { + parseExpected(146 /* SyntaxKind.ReadonlyKeyword */); } } parseExpected(22 /* SyntaxKind.OpenBracketToken */); var typeParameter = parseMappedTypeParameter(); - var nameType = parseOptional(127 /* SyntaxKind.AsKeyword */) ? parseType() : undefined; + var nameType = parseOptional(128 /* SyntaxKind.AsKeyword */) ? parseType() : undefined; parseExpected(23 /* SyntaxKind.CloseBracketToken */); var questionToken; if (token() === 57 /* SyntaxKind.QuestionToken */ || token() === 39 /* SyntaxKind.PlusToken */ || token() === 40 /* SyntaxKind.MinusToken */) { @@ -34392,7 +34672,7 @@ var ts; var openBracePosition = scanner.getTokenPos(); parseExpected(18 /* SyntaxKind.OpenBraceToken */); var multiLine = scanner.hasPrecedingLineBreak(); - parseExpected(129 /* SyntaxKind.AssertKeyword */); + parseExpected(130 /* SyntaxKind.AssertKeyword */); parseExpected(58 /* SyntaxKind.ColonToken */); var clause = parseAssertClause(/*skipAssertKeyword*/ true); if (!parseExpected(19 /* SyntaxKind.CloseBraceToken */)) { @@ -34425,16 +34705,16 @@ var ts; } function parseNonArrayType() { switch (token()) { - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 150 /* SyntaxKind.StringKeyword */: - case 147 /* SyntaxKind.NumberKeyword */: - case 158 /* SyntaxKind.BigIntKeyword */: - case 151 /* SyntaxKind.SymbolKeyword */: - case 133 /* SyntaxKind.BooleanKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: - case 148 /* SyntaxKind.ObjectKeyword */: + case 131 /* SyntaxKind.AnyKeyword */: + case 157 /* SyntaxKind.UnknownKeyword */: + case 152 /* SyntaxKind.StringKeyword */: + case 148 /* SyntaxKind.NumberKeyword */: + case 160 /* SyntaxKind.BigIntKeyword */: + case 153 /* SyntaxKind.SymbolKeyword */: + case 134 /* SyntaxKind.BooleanKeyword */: + case 155 /* SyntaxKind.UndefinedKeyword */: + case 144 /* SyntaxKind.NeverKeyword */: + case 149 /* SyntaxKind.ObjectKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); case 66 /* SyntaxKind.AsteriskEqualsToken */: @@ -34467,7 +34747,7 @@ var ts; return parseTokenNode(); case 108 /* SyntaxKind.ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token() === 139 /* SyntaxKind.IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 140 /* SyntaxKind.IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { @@ -34484,7 +34764,7 @@ var ts; return parseParenthesizedType(); case 100 /* SyntaxKind.ImportKeyword */: return parseImportType(); - case 128 /* SyntaxKind.AssertsKeyword */: + case 129 /* SyntaxKind.AssertsKeyword */: return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference(); case 15 /* SyntaxKind.TemplateHead */: return parseTemplateType(); @@ -34494,21 +34774,21 @@ var ts; } function isStartOfType(inStartOfParameter) { switch (token()) { - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 150 /* SyntaxKind.StringKeyword */: - case 147 /* SyntaxKind.NumberKeyword */: - case 158 /* SyntaxKind.BigIntKeyword */: - case 133 /* SyntaxKind.BooleanKeyword */: - case 145 /* SyntaxKind.ReadonlyKeyword */: - case 151 /* SyntaxKind.SymbolKeyword */: - case 154 /* SyntaxKind.UniqueKeyword */: + case 131 /* SyntaxKind.AnyKeyword */: + case 157 /* SyntaxKind.UnknownKeyword */: + case 152 /* SyntaxKind.StringKeyword */: + case 148 /* SyntaxKind.NumberKeyword */: + case 160 /* SyntaxKind.BigIntKeyword */: + case 134 /* SyntaxKind.BooleanKeyword */: + case 146 /* SyntaxKind.ReadonlyKeyword */: + case 153 /* SyntaxKind.SymbolKeyword */: + case 156 /* SyntaxKind.UniqueKeyword */: case 114 /* SyntaxKind.VoidKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: + case 155 /* SyntaxKind.UndefinedKeyword */: case 104 /* SyntaxKind.NullKeyword */: case 108 /* SyntaxKind.ThisKeyword */: case 112 /* SyntaxKind.TypeOfKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: + case 144 /* SyntaxKind.NeverKeyword */: case 18 /* SyntaxKind.OpenBraceToken */: case 22 /* SyntaxKind.OpenBracketToken */: case 29 /* SyntaxKind.LessThanToken */: @@ -34520,14 +34800,14 @@ var ts; case 9 /* SyntaxKind.BigIntLiteral */: case 110 /* SyntaxKind.TrueKeyword */: case 95 /* SyntaxKind.FalseKeyword */: - case 148 /* SyntaxKind.ObjectKeyword */: + case 149 /* SyntaxKind.ObjectKeyword */: case 41 /* SyntaxKind.AsteriskToken */: case 57 /* SyntaxKind.QuestionToken */: case 53 /* SyntaxKind.ExclamationToken */: case 25 /* SyntaxKind.DotDotDotToken */: - case 137 /* SyntaxKind.InferKeyword */: + case 138 /* SyntaxKind.InferKeyword */: case 100 /* SyntaxKind.ImportKeyword */: - case 128 /* SyntaxKind.AssertsKeyword */: + case 129 /* SyntaxKind.AssertsKeyword */: case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: case 15 /* SyntaxKind.TemplateHead */: return true; @@ -34604,17 +34884,17 @@ var ts; } function parseInferType() { var pos = getNodePos(); - parseExpected(137 /* SyntaxKind.InferKeyword */); + parseExpected(138 /* SyntaxKind.InferKeyword */); return finishNode(factory.createInferTypeNode(parseTypeParameterOfInferType()), pos); } function parseTypeOperatorOrHigher() { var operator = token(); switch (operator) { - case 140 /* SyntaxKind.KeyOfKeyword */: - case 154 /* SyntaxKind.UniqueKeyword */: - case 145 /* SyntaxKind.ReadonlyKeyword */: + case 141 /* SyntaxKind.KeyOfKeyword */: + case 156 /* SyntaxKind.UniqueKeyword */: + case 146 /* SyntaxKind.ReadonlyKeyword */: return parseTypeOperator(operator); - case 137 /* SyntaxKind.InferKeyword */: + case 138 /* SyntaxKind.InferKeyword */: return parseInferType(); } return allowConditionalTypesAnd(parsePostfixTypeOrHigher); @@ -34734,16 +35014,16 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 139 /* SyntaxKind.IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 140 /* SyntaxKind.IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } } function parseAssertsTypePredicate() { var pos = getNodePos(); - var assertsModifier = parseExpectedToken(128 /* SyntaxKind.AssertsKeyword */); + var assertsModifier = parseExpectedToken(129 /* SyntaxKind.AssertsKeyword */); var parameterName = token() === 108 /* SyntaxKind.ThisKeyword */ ? parseThisTypeNode() : parseIdentifier(); - var type = parseOptional(139 /* SyntaxKind.IsKeyword */) ? parseType() : undefined; + var type = parseOptional(140 /* SyntaxKind.IsKeyword */) ? parseType() : undefined; return finishNode(factory.createTypePredicateNode(assertsModifier, parameterName, type), pos); } function parseType() { @@ -34813,7 +35093,7 @@ var ts; case 45 /* SyntaxKind.PlusPlusToken */: case 46 /* SyntaxKind.MinusMinusToken */: case 29 /* SyntaxKind.LessThanToken */: - case 132 /* SyntaxKind.AwaitKeyword */: + case 133 /* SyntaxKind.AwaitKeyword */: case 125 /* SyntaxKind.YieldKeyword */: case 80 /* SyntaxKind.PrivateIdentifier */: // Yield/await always starts an expression. Either it is an identifier (in which case @@ -35001,7 +35281,7 @@ var ts; // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token() === 20 /* SyntaxKind.OpenParenToken */ || token() === 29 /* SyntaxKind.LessThanToken */ || token() === 131 /* SyntaxKind.AsyncKeyword */) { + if (token() === 20 /* SyntaxKind.OpenParenToken */ || token() === 29 /* SyntaxKind.LessThanToken */ || token() === 132 /* SyntaxKind.AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } if (token() === 38 /* SyntaxKind.EqualsGreaterThanToken */) { @@ -35014,7 +35294,7 @@ var ts; return 0 /* Tristate.False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 131 /* SyntaxKind.AsyncKeyword */) { + if (token() === 132 /* SyntaxKind.AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* Tristate.False */; @@ -35058,8 +35338,8 @@ var ts; // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. - if (ts.isModifierKind(second) && second !== 131 /* SyntaxKind.AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { - if (nextToken() === 127 /* SyntaxKind.AsKeyword */) { + if (ts.isModifierKind(second) && second !== 132 /* SyntaxKind.AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + if (nextToken() === 128 /* SyntaxKind.AsKeyword */) { // https://github.com/microsoft/TypeScript/issues/44466 return 0 /* Tristate.False */; } @@ -35141,7 +35421,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction) { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 131 /* SyntaxKind.AsyncKeyword */) { + if (token() === 132 /* SyntaxKind.AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* Tristate.True */) { var pos = getNodePos(); var asyncModifier = parseModifiersForArrowFunction(); @@ -35155,7 +35435,7 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 131 /* SyntaxKind.AsyncKeyword */) { + if (token() === 132 /* SyntaxKind.AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" @@ -35221,7 +35501,7 @@ var ts; // // So we need just a bit of lookahead to ensure that it can only be a signature. var unwrappedType = type; - while ((unwrappedType === null || unwrappedType === void 0 ? void 0 : unwrappedType.kind) === 191 /* SyntaxKind.ParenthesizedType */) { + while ((unwrappedType === null || unwrappedType === void 0 ? void 0 : unwrappedType.kind) === 193 /* SyntaxKind.ParenthesizedType */) { unwrappedType = unwrappedType.type; // Skip parens if need be } var hasJSDocFunctionType = unwrappedType && ts.isJSDocFunctionType(unwrappedType); @@ -35316,7 +35596,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand, pos); } function isInOrOfKeyword(t) { - return t === 101 /* SyntaxKind.InKeyword */ || t === 160 /* SyntaxKind.OfKeyword */; + return t === 101 /* SyntaxKind.InKeyword */ || t === 162 /* SyntaxKind.OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand, pos) { while (true) { @@ -35354,7 +35634,7 @@ var ts; if (token() === 101 /* SyntaxKind.InKeyword */ && inDisallowInContext()) { break; } - if (token() === 127 /* SyntaxKind.AsKeyword */) { + if (token() === 128 /* SyntaxKind.AsKeyword */ || token() === 150 /* SyntaxKind.SatisfiesKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -35364,8 +35644,10 @@ var ts; break; } else { + var keywordKind = token(); nextToken(); - leftOperand = makeAsExpression(leftOperand, parseType()); + leftOperand = keywordKind === 150 /* SyntaxKind.SatisfiesKeyword */ ? makeSatisfiesExpression(leftOperand, parseType()) : + makeAsExpression(leftOperand, parseType()); } } else { @@ -35380,6 +35662,9 @@ var ts; } return ts.getBinaryOperatorPrecedence(token()) > 0; } + function makeSatisfiesExpression(left, right) { + return finishNode(factory.createSatisfiesExpression(left, right), left.pos); + } function makeBinaryExpression(left, operatorToken, right, pos) { return finishNode(factory.createBinaryExpression(left, operatorToken, right), pos); } @@ -35403,7 +35688,7 @@ var ts; return finishNode(factory.createVoidExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos); } function isAwaitExpression() { - if (token() === 132 /* SyntaxKind.AwaitKeyword */) { + if (token() === 133 /* SyntaxKind.AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -35456,7 +35741,7 @@ var ts; if (token() === 42 /* SyntaxKind.AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 211 /* SyntaxKind.TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 213 /* SyntaxKind.TypeAssertionExpression */) { parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -35497,7 +35782,7 @@ var ts; // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); - case 132 /* SyntaxKind.AwaitKeyword */: + case 133 /* SyntaxKind.AwaitKeyword */: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -35527,7 +35812,7 @@ var ts; case 89 /* SyntaxKind.DeleteKeyword */: case 112 /* SyntaxKind.TypeOfKeyword */: case 114 /* SyntaxKind.VoidKeyword */: - case 132 /* SyntaxKind.AwaitKeyword */: + case 133 /* SyntaxKind.AwaitKeyword */: return false; case 29 /* SyntaxKind.LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression @@ -35710,11 +35995,11 @@ var ts; var pos = getNodePos(); var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 280 /* SyntaxKind.JsxOpeningElement */) { + if (opening.kind === 283 /* SyntaxKind.JsxOpeningElement */) { var children = parseJsxChildren(opening); var closingElement = void 0; var lastChild = children[children.length - 1]; - if ((lastChild === null || lastChild === void 0 ? void 0 : lastChild.kind) === 278 /* SyntaxKind.JsxElement */ + if ((lastChild === null || lastChild === void 0 ? void 0 : lastChild.kind) === 281 /* SyntaxKind.JsxElement */ && !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName) && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName)) { // when an unclosed JsxOpeningElement incorrectly parses its parent's JsxClosingElement, @@ -35740,11 +36025,11 @@ var ts; } result = finishNode(factory.createJsxElement(opening, children, closingElement), pos); } - else if (opening.kind === 283 /* SyntaxKind.JsxOpeningFragment */) { + else if (opening.kind === 286 /* SyntaxKind.JsxOpeningFragment */) { result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); } else { - ts.Debug.assert(opening.kind === 279 /* SyntaxKind.JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 282 /* SyntaxKind.JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -35814,7 +36099,7 @@ var ts; break; list.push(child); if (ts.isJsxOpeningElement(openingTag) - && (child === null || child === void 0 ? void 0 : child.kind) === 278 /* SyntaxKind.JsxElement */ + && (child === null || child === void 0 ? void 0 : child.kind) === 281 /* SyntaxKind.JsxElement */ && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName) && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName)) { // stop after parsing a mismatched child like
...(
) in order to reattach the
higher @@ -36059,7 +36344,7 @@ var ts; } if (isTemplateStartOfTaggedTemplate()) { // Absorb type arguments into TemplateExpression when preceding expression is ExpressionWithTypeArguments - expression = !questionDotToken && expression.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */ ? + expression = !questionDotToken && expression.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */ ? parseTaggedTemplateRest(pos, expression.expression, questionDotToken, expression.typeArguments) : parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ undefined); continue; @@ -36106,7 +36391,7 @@ var ts; } if (typeArguments || token() === 20 /* SyntaxKind.OpenParenToken */) { // Absorb type arguments into CallExpression when preceding expression is ExpressionWithTypeArguments - if (!questionDotToken && expression.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */) { + if (!questionDotToken && expression.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */) { typeArguments = expression.typeArguments; expression = expression.expression; } @@ -36192,7 +36477,7 @@ var ts; return parseArrayLiteralExpression(); case 18 /* SyntaxKind.OpenBraceToken */: return parseObjectLiteralExpression(); - case 131 /* SyntaxKind.AsyncKeyword */: + case 132 /* SyntaxKind.AsyncKeyword */: // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. // If we encounter `async [no LineTerminator here] function` then this is an async // function; otherwise, its an identifier. @@ -36259,11 +36544,11 @@ var ts; } var decorators = parseDecorators(); var modifiers = parseModifiers(); - if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); + if (parseContextualModifier(137 /* SyntaxKind.GetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 174 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } - if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); + if (parseContextualModifier(151 /* SyntaxKind.SetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 175 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } var asteriskToken = parseOptionalToken(41 /* SyntaxKind.AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -36351,7 +36636,7 @@ var ts; var expression = parseMemberExpressionRest(expressionPos, parsePrimaryExpression(), /*allowOptionalChain*/ false); var typeArguments; // Absorb type arguments into NewExpression when preceding expression is ExpressionWithTypeArguments - if (expression.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */) { + if (expression.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */) { typeArguments = expression.typeArguments; expression = expression.expression; } @@ -36455,7 +36740,7 @@ var ts; var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(97 /* SyntaxKind.ForKeyword */); - var awaitToken = parseOptionalToken(132 /* SyntaxKind.AwaitKeyword */); + var awaitToken = parseOptionalToken(133 /* SyntaxKind.AwaitKeyword */); parseExpected(20 /* SyntaxKind.OpenParenToken */); var initializer; if (token() !== 26 /* SyntaxKind.SemicolonToken */) { @@ -36467,7 +36752,7 @@ var ts; } } var node; - if (awaitToken ? parseExpected(160 /* SyntaxKind.OfKeyword */) : parseOptional(160 /* SyntaxKind.OfKeyword */)) { + if (awaitToken ? parseExpected(162 /* SyntaxKind.OfKeyword */) : parseOptional(162 /* SyntaxKind.OfKeyword */)) { var expression = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); parseExpected(21 /* SyntaxKind.CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); @@ -36494,10 +36779,10 @@ var ts; function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(kind === 246 /* SyntaxKind.BreakStatement */ ? 81 /* SyntaxKind.BreakKeyword */ : 86 /* SyntaxKind.ContinueKeyword */); + parseExpected(kind === 249 /* SyntaxKind.BreakStatement */ ? 81 /* SyntaxKind.BreakKeyword */ : 86 /* SyntaxKind.ContinueKeyword */); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); - var node = kind === 246 /* SyntaxKind.BreakStatement */ + var node = kind === 249 /* SyntaxKind.BreakStatement */ ? factory.createBreakStatement(label) : factory.createContinueStatement(label); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -36688,25 +36973,26 @@ var ts; // // could be legal, it would add complexity for very little gain. case 118 /* SyntaxKind.InterfaceKeyword */: - case 152 /* SyntaxKind.TypeKeyword */: + case 154 /* SyntaxKind.TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); - case 141 /* SyntaxKind.ModuleKeyword */: - case 142 /* SyntaxKind.NamespaceKeyword */: + case 142 /* SyntaxKind.ModuleKeyword */: + case 143 /* SyntaxKind.NamespaceKeyword */: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); case 126 /* SyntaxKind.AbstractKeyword */: - case 131 /* SyntaxKind.AsyncKeyword */: - case 135 /* SyntaxKind.DeclareKeyword */: + case 127 /* SyntaxKind.AccessorKeyword */: + case 132 /* SyntaxKind.AsyncKeyword */: + case 136 /* SyntaxKind.DeclareKeyword */: case 121 /* SyntaxKind.PrivateKeyword */: case 122 /* SyntaxKind.ProtectedKeyword */: case 123 /* SyntaxKind.PublicKeyword */: - case 145 /* SyntaxKind.ReadonlyKeyword */: + case 146 /* SyntaxKind.ReadonlyKeyword */: nextToken(); // ASI takes effect for this modifier. if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 157 /* SyntaxKind.GlobalKeyword */: + case 159 /* SyntaxKind.GlobalKeyword */: nextToken(); return token() === 18 /* SyntaxKind.OpenBraceToken */ || token() === 79 /* SyntaxKind.Identifier */ || token() === 93 /* SyntaxKind.ExportKeyword */; case 100 /* SyntaxKind.ImportKeyword */: @@ -36715,12 +37001,12 @@ var ts; token() === 18 /* SyntaxKind.OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); case 93 /* SyntaxKind.ExportKeyword */: var currentToken_1 = nextToken(); - if (currentToken_1 === 152 /* SyntaxKind.TypeKeyword */) { + if (currentToken_1 === 154 /* SyntaxKind.TypeKeyword */) { currentToken_1 = lookAhead(nextToken); } if (currentToken_1 === 63 /* SyntaxKind.EqualsToken */ || currentToken_1 === 41 /* SyntaxKind.AsteriskToken */ || currentToken_1 === 18 /* SyntaxKind.OpenBraceToken */ || currentToken_1 === 88 /* SyntaxKind.DefaultKeyword */ || - currentToken_1 === 127 /* SyntaxKind.AsKeyword */) { + currentToken_1 === 128 /* SyntaxKind.AsKeyword */) { return true; } continue; @@ -36768,20 +37054,21 @@ var ts; case 85 /* SyntaxKind.ConstKeyword */: case 93 /* SyntaxKind.ExportKeyword */: return isStartOfDeclaration(); - case 131 /* SyntaxKind.AsyncKeyword */: - case 135 /* SyntaxKind.DeclareKeyword */: + case 132 /* SyntaxKind.AsyncKeyword */: + case 136 /* SyntaxKind.DeclareKeyword */: case 118 /* SyntaxKind.InterfaceKeyword */: - case 141 /* SyntaxKind.ModuleKeyword */: - case 142 /* SyntaxKind.NamespaceKeyword */: - case 152 /* SyntaxKind.TypeKeyword */: - case 157 /* SyntaxKind.GlobalKeyword */: + case 142 /* SyntaxKind.ModuleKeyword */: + case 143 /* SyntaxKind.NamespaceKeyword */: + case 154 /* SyntaxKind.TypeKeyword */: + case 159 /* SyntaxKind.GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; + case 127 /* SyntaxKind.AccessorKeyword */: case 123 /* SyntaxKind.PublicKeyword */: case 121 /* SyntaxKind.PrivateKeyword */: case 122 /* SyntaxKind.ProtectedKeyword */: case 124 /* SyntaxKind.StaticKeyword */: - case 145 /* SyntaxKind.ReadonlyKeyword */: + case 146 /* SyntaxKind.ReadonlyKeyword */: // When these don't start a declaration, they may be the start of a class member if an identifier // immediately follows. Otherwise they're an identifier in an expression statement. return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); @@ -36824,9 +37111,9 @@ var ts; case 97 /* SyntaxKind.ForKeyword */: return parseForOrForInOrForOfStatement(); case 86 /* SyntaxKind.ContinueKeyword */: - return parseBreakOrContinueStatement(245 /* SyntaxKind.ContinueStatement */); + return parseBreakOrContinueStatement(248 /* SyntaxKind.ContinueStatement */); case 81 /* SyntaxKind.BreakKeyword */: - return parseBreakOrContinueStatement(246 /* SyntaxKind.BreakStatement */); + return parseBreakOrContinueStatement(249 /* SyntaxKind.BreakStatement */); case 105 /* SyntaxKind.ReturnKeyword */: return parseReturnStatement(); case 116 /* SyntaxKind.WithKeyword */: @@ -36845,12 +37132,12 @@ var ts; return parseDebuggerStatement(); case 59 /* SyntaxKind.AtToken */: return parseDeclaration(); - case 131 /* SyntaxKind.AsyncKeyword */: + case 132 /* SyntaxKind.AsyncKeyword */: case 118 /* SyntaxKind.InterfaceKeyword */: - case 152 /* SyntaxKind.TypeKeyword */: - case 141 /* SyntaxKind.ModuleKeyword */: - case 142 /* SyntaxKind.NamespaceKeyword */: - case 135 /* SyntaxKind.DeclareKeyword */: + case 154 /* SyntaxKind.TypeKeyword */: + case 142 /* SyntaxKind.ModuleKeyword */: + case 143 /* SyntaxKind.NamespaceKeyword */: + case 136 /* SyntaxKind.DeclareKeyword */: case 85 /* SyntaxKind.ConstKeyword */: case 92 /* SyntaxKind.EnumKeyword */: case 93 /* SyntaxKind.ExportKeyword */: @@ -36859,9 +37146,10 @@ var ts; case 122 /* SyntaxKind.ProtectedKeyword */: case 123 /* SyntaxKind.PublicKeyword */: case 126 /* SyntaxKind.AbstractKeyword */: + case 127 /* SyntaxKind.AccessorKeyword */: case 124 /* SyntaxKind.StaticKeyword */: - case 145 /* SyntaxKind.ReadonlyKeyword */: - case 157 /* SyntaxKind.GlobalKeyword */: + case 146 /* SyntaxKind.ReadonlyKeyword */: + case 159 /* SyntaxKind.GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -36870,7 +37158,7 @@ var ts; return parseExpressionOrLabeledStatement(); } function isDeclareModifier(modifier) { - return modifier.kind === 135 /* SyntaxKind.DeclareKeyword */; + return modifier.kind === 136 /* SyntaxKind.DeclareKeyword */; } function parseDeclaration() { // `parseListElement` attempted to get the reused node at this position, @@ -36916,13 +37204,13 @@ var ts; return parseClassDeclaration(pos, hasJSDoc, decorators, modifiers); case 118 /* SyntaxKind.InterfaceKeyword */: return parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers); - case 152 /* SyntaxKind.TypeKeyword */: + case 154 /* SyntaxKind.TypeKeyword */: return parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers); case 92 /* SyntaxKind.EnumKeyword */: return parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers); - case 157 /* SyntaxKind.GlobalKeyword */: - case 141 /* SyntaxKind.ModuleKeyword */: - case 142 /* SyntaxKind.NamespaceKeyword */: + case 159 /* SyntaxKind.GlobalKeyword */: + case 142 /* SyntaxKind.ModuleKeyword */: + case 143 /* SyntaxKind.NamespaceKeyword */: return parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers); case 100 /* SyntaxKind.ImportKeyword */: return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -36932,7 +37220,7 @@ var ts; case 88 /* SyntaxKind.DefaultKeyword */: case 63 /* SyntaxKind.EqualsToken */: return parseExportAssignment(pos, hasJSDoc, decorators, modifiers); - case 127 /* SyntaxKind.AsKeyword */: + case 128 /* SyntaxKind.AsKeyword */: return parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers); default: return parseExportDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -36941,7 +37229,7 @@ var ts; if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var missing = createMissingNode(276 /* SyntaxKind.MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(279 /* SyntaxKind.MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); missing.illegalDecorators = decorators; missing.modifiers = modifiers; @@ -37067,7 +37355,7 @@ var ts; // this context. // The checker will then give an error that there is an empty declaration list. var declarations; - if (token() === 160 /* SyntaxKind.OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 162 /* SyntaxKind.OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { declarations = createMissingList(); } else { @@ -37095,9 +37383,9 @@ var ts; parseExpected(98 /* SyntaxKind.FunctionKeyword */); var asteriskToken = parseOptionalToken(41 /* SyntaxKind.AsteriskToken */); // We don't parse the name here in await context, instead we will report a grammar error in the checker. - var name = modifierFlags & 512 /* ModifierFlags.Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier(); + var name = modifierFlags & 1024 /* ModifierFlags.Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier(); var isGenerator = asteriskToken ? 1 /* SignatureFlags.Yield */ : 0 /* SignatureFlags.None */; - var isAsync = modifierFlags & 256 /* ModifierFlags.Async */ ? 2 /* SignatureFlags.Await */ : 0 /* SignatureFlags.None */; + var isAsync = modifierFlags & 512 /* ModifierFlags.Async */ ? 2 /* SignatureFlags.Await */ : 0 /* SignatureFlags.None */; var typeParameters = parseTypeParameters(); if (modifierFlags & 1 /* ModifierFlags.Export */) setAwaitContext(/*value*/ true); @@ -37110,8 +37398,8 @@ var ts; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseConstructorName() { - if (token() === 134 /* SyntaxKind.ConstructorKeyword */) { - return parseExpected(134 /* SyntaxKind.ConstructorKeyword */); + if (token() === 135 /* SyntaxKind.ConstructorKeyword */) { + return parseExpected(135 /* SyntaxKind.ConstructorKeyword */); } if (token() === 10 /* SyntaxKind.StringLiteral */ && lookAhead(nextToken) === 20 /* SyntaxKind.OpenParenToken */) { return tryParse(function () { @@ -37173,7 +37461,7 @@ var ts; var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(flags); - var node = kind === 172 /* SyntaxKind.GetAccessor */ + var node = kind === 174 /* SyntaxKind.GetAccessor */ ? factory.createGetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, type, body) : factory.createSetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors @@ -37217,7 +37505,7 @@ var ts; // If we were able to get any potential identifier... if (idToken !== undefined) { // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. - if (!ts.isKeyword(idToken) || idToken === 149 /* SyntaxKind.SetKeyword */ || idToken === 136 /* SyntaxKind.GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 151 /* SyntaxKind.SetKeyword */ || idToken === 137 /* SyntaxKind.GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along @@ -37260,7 +37548,7 @@ var ts; return body; } function parseDecoratorExpression() { - if (inAwaitContext() && token() === 132 /* SyntaxKind.AwaitKeyword */) { + if (inAwaitContext() && token() === 133 /* SyntaxKind.AwaitKeyword */) { // `@await` is is disallowed in an [Await] context, but can cause parsing to go off the rails // This simply parses the missing identifier and moves on. var pos = getNodePos(); @@ -37338,10 +37626,10 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 131 /* SyntaxKind.AsyncKeyword */) { + if (token() === 132 /* SyntaxKind.AsyncKeyword */) { var pos = getNodePos(); nextToken(); - var modifier = finishNode(factory.createToken(131 /* SyntaxKind.AsyncKeyword */), pos); + var modifier = finishNode(factory.createToken(132 /* SyntaxKind.AsyncKeyword */), pos); modifiers = createNodeArray([modifier], pos); } return modifiers; @@ -37358,13 +37646,13 @@ var ts; if (token() === 124 /* SyntaxKind.StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) { return parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers); } - if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); + if (parseContextualModifier(137 /* SyntaxKind.GetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 174 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } - if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); + if (parseContextualModifier(151 /* SyntaxKind.SetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 175 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } - if (token() === 134 /* SyntaxKind.ConstructorKeyword */ || token() === 10 /* SyntaxKind.StringLiteral */) { + if (token() === 135 /* SyntaxKind.ConstructorKeyword */ || token() === 10 /* SyntaxKind.StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); if (constructorDeclaration) { return constructorDeclaration; @@ -37401,10 +37689,10 @@ var ts; return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 226 /* SyntaxKind.ClassExpression */); + return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 228 /* SyntaxKind.ClassExpression */); } function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) { - return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 257 /* SyntaxKind.ClassDeclaration */); + return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 260 /* SyntaxKind.ClassDeclaration */); } function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) { var savedAwaitContext = inAwaitContext(); @@ -37426,7 +37714,7 @@ var ts; members = createMissingList(); } setAwaitContext(savedAwaitContext); - var node = kind === 257 /* SyntaxKind.ClassDeclaration */ + var node = kind === 260 /* SyntaxKind.ClassDeclaration */ ? factory.createClassDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members) : factory.createClassExpression(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -37463,7 +37751,7 @@ var ts; function parseExpressionWithTypeArguments() { var pos = getNodePos(); var expression = parseLeftHandSideExpressionOrHigher(); - if (expression.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */) { + if (expression.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */) { return expression; } var typeArguments = tryParseTypeArguments(); @@ -37490,11 +37778,11 @@ var ts; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) { - parseExpected(152 /* SyntaxKind.TypeKeyword */); + parseExpected(154 /* SyntaxKind.TypeKeyword */); var name = parseIdentifier(); var typeParameters = parseTypeParameters(); parseExpected(63 /* SyntaxKind.EqualsToken */); - var type = token() === 138 /* SyntaxKind.IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType(); + var type = token() === 139 /* SyntaxKind.IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType(); parseSemicolon(); var node = factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type); node.illegalDecorators = decorators; @@ -37553,7 +37841,7 @@ var ts; function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { var flags = 0; var name; - if (token() === 157 /* SyntaxKind.GlobalKeyword */) { + if (token() === 159 /* SyntaxKind.GlobalKeyword */) { // parse 'global' as name of global scope augmentation name = parseIdentifier(); flags |= 1024 /* NodeFlags.GlobalAugmentation */; @@ -37575,15 +37863,15 @@ var ts; } function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { var flags = 0; - if (token() === 157 /* SyntaxKind.GlobalKeyword */) { + if (token() === 159 /* SyntaxKind.GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers); } - else if (parseOptional(142 /* SyntaxKind.NamespaceKeyword */)) { + else if (parseOptional(143 /* SyntaxKind.NamespaceKeyword */)) { flags |= 16 /* NodeFlags.Namespace */; } else { - parseExpected(141 /* SyntaxKind.ModuleKeyword */); + parseExpected(142 /* SyntaxKind.ModuleKeyword */); if (token() === 10 /* SyntaxKind.StringLiteral */) { return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers); } @@ -37591,7 +37879,7 @@ var ts; return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags); } function isExternalModuleReference() { - return token() === 146 /* SyntaxKind.RequireKeyword */ && + return token() === 147 /* SyntaxKind.RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -37604,8 +37892,8 @@ var ts; return nextToken() === 43 /* SyntaxKind.SlashToken */; } function parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers) { - parseExpected(127 /* SyntaxKind.AsKeyword */); - parseExpected(142 /* SyntaxKind.NamespaceKeyword */); + parseExpected(128 /* SyntaxKind.AsKeyword */); + parseExpected(143 /* SyntaxKind.NamespaceKeyword */); var name = parseIdentifier(); parseSemicolon(); var node = factory.createNamespaceExportDeclaration(name); @@ -37623,7 +37911,7 @@ var ts; identifier = parseIdentifier(); } var isTypeOnly = false; - if (token() !== 156 /* SyntaxKind.FromKeyword */ && + if (token() !== 158 /* SyntaxKind.FromKeyword */ && (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" && (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) { isTypeOnly = true; @@ -37641,11 +37929,11 @@ var ts; token() === 18 /* SyntaxKind.OpenBraceToken */ // import { ) { importClause = parseImportClause(identifier, afterImportPos, isTypeOnly); - parseExpected(156 /* SyntaxKind.FromKeyword */); + parseExpected(158 /* SyntaxKind.FromKeyword */); } var moduleSpecifier = parseModuleSpecifier(); var assertClause; - if (token() === 129 /* SyntaxKind.AssertKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 130 /* SyntaxKind.AssertKeyword */ && !scanner.hasPrecedingLineBreak()) { assertClause = parseAssertClause(); } parseSemicolon(); @@ -37663,7 +37951,7 @@ var ts; function parseAssertClause(skipAssertKeyword) { var pos = getNodePos(); if (!skipAssertKeyword) { - parseExpected(129 /* SyntaxKind.AssertKeyword */); + parseExpected(130 /* SyntaxKind.AssertKeyword */); } var openBracePosition = scanner.getTokenPos(); if (parseExpected(18 /* SyntaxKind.OpenBraceToken */)) { @@ -37688,7 +37976,7 @@ var ts; function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() { // In `import id ___`, the current token decides whether to produce // an ImportDeclaration or ImportEqualsDeclaration. - return token() === 27 /* SyntaxKind.CommaToken */ || token() === 156 /* SyntaxKind.FromKeyword */; + return token() === 27 /* SyntaxKind.CommaToken */ || token() === 158 /* SyntaxKind.FromKeyword */; } function parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly) { parseExpected(63 /* SyntaxKind.EqualsToken */); @@ -37711,7 +37999,7 @@ var ts; var namedBindings; if (!identifier || parseOptional(27 /* SyntaxKind.CommaToken */)) { - namedBindings = token() === 41 /* SyntaxKind.AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(269 /* SyntaxKind.NamedImports */); + namedBindings = token() === 41 /* SyntaxKind.AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(272 /* SyntaxKind.NamedImports */); } return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos); } @@ -37722,7 +38010,7 @@ var ts; } function parseExternalModuleReference() { var pos = getNodePos(); - parseExpected(146 /* SyntaxKind.RequireKeyword */); + parseExpected(147 /* SyntaxKind.RequireKeyword */); parseExpected(20 /* SyntaxKind.OpenParenToken */); var expression = parseModuleSpecifier(); parseExpected(21 /* SyntaxKind.CloseParenToken */); @@ -37746,7 +38034,7 @@ var ts; // * as ImportedBinding var pos = getNodePos(); parseExpected(41 /* SyntaxKind.AsteriskToken */); - parseExpected(127 /* SyntaxKind.AsKeyword */); + parseExpected(128 /* SyntaxKind.AsKeyword */); var name = parseIdentifier(); return finishNode(factory.createNamespaceImport(name), pos); } @@ -37759,17 +38047,17 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - var node = kind === 269 /* SyntaxKind.NamedImports */ + var node = kind === 272 /* SyntaxKind.NamedImports */ ? factory.createNamedImports(parseBracketedList(23 /* ParsingContext.ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* SyntaxKind.OpenBraceToken */, 19 /* SyntaxKind.CloseBraceToken */)) : factory.createNamedExports(parseBracketedList(23 /* ParsingContext.ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* SyntaxKind.OpenBraceToken */, 19 /* SyntaxKind.CloseBraceToken */)); return finishNode(node, pos); } function parseExportSpecifier() { var hasJSDoc = hasPrecedingJSDocComment(); - return withJSDoc(parseImportOrExportSpecifier(275 /* SyntaxKind.ExportSpecifier */), hasJSDoc); + return withJSDoc(parseImportOrExportSpecifier(278 /* SyntaxKind.ExportSpecifier */), hasJSDoc); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(270 /* SyntaxKind.ImportSpecifier */); + return parseImportOrExportSpecifier(273 /* SyntaxKind.ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var pos = getNodePos(); @@ -37794,10 +38082,10 @@ var ts; // import { type as } from "mod"; - isTypeOnly: true, name: as // import { type as as } from "mod"; - isTypeOnly: false, name: as, propertyName: type // import { type as as as } from "mod"; - isTypeOnly: true, name: as, propertyName: as - if (token() === 127 /* SyntaxKind.AsKeyword */) { + if (token() === 128 /* SyntaxKind.AsKeyword */) { // { type as ...? } var firstAs = parseIdentifierName(); - if (token() === 127 /* SyntaxKind.AsKeyword */) { + if (token() === 128 /* SyntaxKind.AsKeyword */) { // { type as as ...? } var secondAs = parseIdentifierName(); if (ts.tokenIsIdentifierOrKeyword(token())) { @@ -37832,15 +38120,15 @@ var ts; name = parseNameWithKeywordCheck(); } } - if (canParseAsKeyword && token() === 127 /* SyntaxKind.AsKeyword */) { + if (canParseAsKeyword && token() === 128 /* SyntaxKind.AsKeyword */) { propertyName = name; - parseExpected(127 /* SyntaxKind.AsKeyword */); + parseExpected(128 /* SyntaxKind.AsKeyword */); name = parseNameWithKeywordCheck(); } - if (kind === 270 /* SyntaxKind.ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 273 /* SyntaxKind.ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } - var node = kind === 270 /* SyntaxKind.ImportSpecifier */ + var node = kind === 273 /* SyntaxKind.ImportSpecifier */ ? factory.createImportSpecifier(isTypeOnly, propertyName, name) : factory.createExportSpecifier(isTypeOnly, propertyName, name); return finishNode(node, pos); @@ -37860,26 +38148,26 @@ var ts; var exportClause; var moduleSpecifier; var assertClause; - var isTypeOnly = parseOptional(152 /* SyntaxKind.TypeKeyword */); + var isTypeOnly = parseOptional(154 /* SyntaxKind.TypeKeyword */); var namespaceExportPos = getNodePos(); if (parseOptional(41 /* SyntaxKind.AsteriskToken */)) { - if (parseOptional(127 /* SyntaxKind.AsKeyword */)) { + if (parseOptional(128 /* SyntaxKind.AsKeyword */)) { exportClause = parseNamespaceExport(namespaceExportPos); } - parseExpected(156 /* SyntaxKind.FromKeyword */); + parseExpected(158 /* SyntaxKind.FromKeyword */); moduleSpecifier = parseModuleSpecifier(); } else { - exportClause = parseNamedImportsOrExports(273 /* SyntaxKind.NamedExports */); + exportClause = parseNamedImportsOrExports(276 /* SyntaxKind.NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === 156 /* SyntaxKind.FromKeyword */ || (token() === 10 /* SyntaxKind.StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(156 /* SyntaxKind.FromKeyword */); + if (token() === 158 /* SyntaxKind.FromKeyword */ || (token() === 10 /* SyntaxKind.StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(158 /* SyntaxKind.FromKeyword */); moduleSpecifier = parseModuleSpecifier(); } } - if (moduleSpecifier && token() === 129 /* SyntaxKind.AssertKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (moduleSpecifier && token() === 130 /* SyntaxKind.AssertKeyword */ && !scanner.hasPrecedingLineBreak()) { assertClause = parseAssertClause(); } parseSemicolon(); @@ -38492,9 +38780,9 @@ var ts; } function isObjectOrObjectArrayTypeReference(node) { switch (node.kind) { - case 148 /* SyntaxKind.ObjectKeyword */: + case 149 /* SyntaxKind.ObjectKeyword */: return true; - case 183 /* SyntaxKind.ArrayType */: + case 185 /* SyntaxKind.ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments; @@ -38526,12 +38814,12 @@ var ts; var child = void 0; var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { - if (child.kind === 340 /* SyntaxKind.JSDocParameterTag */ || child.kind === 347 /* SyntaxKind.JSDocPropertyTag */) { + if (child.kind === 343 /* SyntaxKind.JSDocParameterTag */ || child.kind === 350 /* SyntaxKind.JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 183 /* SyntaxKind.ArrayType */), pos); + var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 185 /* SyntaxKind.ArrayType */), pos); return finishNode(factory.createJSDocTypeExpression(literal), pos); } } @@ -38649,7 +38937,7 @@ var ts; var hasChildren = false; while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { hasChildren = true; - if (child.kind === 343 /* SyntaxKind.JSDocTypeTag */) { + if (child.kind === 346 /* SyntaxKind.JSDocTypeTag */) { if (childTypeTag) { var lastError = parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); if (lastError) { @@ -38666,7 +38954,7 @@ var ts; } } if (hasChildren) { - var isArrayType = typeExpression && typeExpression.type.kind === 183 /* SyntaxKind.ArrayType */; + var isArrayType = typeExpression && typeExpression.type.kind === 185 /* SyntaxKind.ArrayType */; var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType); typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : @@ -38718,7 +39006,7 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(59 /* SyntaxKind.AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 341 /* SyntaxKind.JSDocReturnTag */) { + if (tag && tag.kind === 344 /* SyntaxKind.JSDocReturnTag */) { return tag; } } @@ -38753,7 +39041,7 @@ var ts; case 59 /* SyntaxKind.AtToken */: if (canParseTag) { var child = tryParseChildTag(target, indent); - if (child && (child.kind === 340 /* SyntaxKind.JSDocParameterTag */ || child.kind === 347 /* SyntaxKind.JSDocPropertyTag */) && + if (child && (child.kind === 343 /* SyntaxKind.JSDocParameterTag */ || child.kind === 350 /* SyntaxKind.JSDocPropertyTag */) && target !== 4 /* PropertyLikeParse.CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -39725,6 +40013,7 @@ var ts; ["es2019.object", "lib.es2019.object.d.ts"], ["es2019.string", "lib.es2019.string.d.ts"], ["es2019.symbol", "lib.es2019.symbol.d.ts"], + ["es2019.intl", "lib.es2019.intl.d.ts"], ["es2020.bigint", "lib.es2020.bigint.d.ts"], ["es2020.date", "lib.es2020.date.d.ts"], ["es2020.promise", "lib.es2020.promise.d.ts"], @@ -39845,6 +40134,7 @@ var ts; shortName: "h", type: "boolean", showInSimplifiedHelpView: true, + isCommandLineOnly: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_this_message, defaultValueDescription: false, @@ -39853,6 +40143,8 @@ var ts; name: "help", shortName: "?", type: "boolean", + isCommandLineOnly: true, + category: ts.Diagnostics.Command_line_Options, defaultValueDescription: false, }, { @@ -41584,7 +41876,7 @@ var ts; var _a; var rootExpression = (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression; var knownRootOptions = reportOptionsErrors ? getTsconfigRootOptionsMap() : undefined; - if (rootExpression && rootExpression.kind !== 205 /* SyntaxKind.ObjectLiteralExpression */) { + if (rootExpression && rootExpression.kind !== 207 /* SyntaxKind.ObjectLiteralExpression */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, rootExpression, ts.Diagnostics.The_root_value_of_a_0_file_must_be_an_object, ts.getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json")); // Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by // synthesizing a top-level array literal expression. There's a reasonable chance the first element of that @@ -41624,7 +41916,7 @@ var ts; function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; var _loop_4 = function (element) { - if (element.kind !== 296 /* SyntaxKind.PropertyAssignment */) { + if (element.kind !== 299 /* SyntaxKind.PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); return "continue"; } @@ -41718,13 +42010,13 @@ var ts; case 8 /* SyntaxKind.NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return validateValue(Number(valueExpression.text)); - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: if (valueExpression.operator !== 40 /* SyntaxKind.MinusToken */ || valueExpression.operand.kind !== 8 /* SyntaxKind.NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return validateValue(-Number(valueExpression.operand.text)); - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -41741,7 +42033,7 @@ var ts; return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined)); } - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element)); } @@ -41973,12 +42265,23 @@ var ts; } function writeConfigurations() { // Filter applicable options to place in the file - var categorizedOptions = ts.createMultiMap(); + var categorizedOptions = new ts.Map(); + // Set allowed categories in order + categorizedOptions.set(ts.Diagnostics.Projects, []); + categorizedOptions.set(ts.Diagnostics.Language_and_Environment, []); + categorizedOptions.set(ts.Diagnostics.Modules, []); + categorizedOptions.set(ts.Diagnostics.JavaScript_Support, []); + categorizedOptions.set(ts.Diagnostics.Emit, []); + categorizedOptions.set(ts.Diagnostics.Interop_Constraints, []); + categorizedOptions.set(ts.Diagnostics.Type_Checking, []); + categorizedOptions.set(ts.Diagnostics.Completeness, []); for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { var option = optionDeclarations_1[_i]; - var category = option.category; if (isAllowedOptionForOutput(option)) { - categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + var listForCategory = categorizedOptions.get(option.category); + if (!listForCategory) + categorizedOptions.set(option.category, listForCategory = []); + listForCategory.push(option); } } // Serialize all options and their descriptions @@ -41989,7 +42292,7 @@ var ts; if (entries.length !== 0) { entries.push({ value: "" }); } - entries.push({ value: "/* ".concat(category, " */") }); + entries.push({ value: "/* ".concat(ts.getLocaleSpecificMessage(category), " */") }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -42925,7 +43228,7 @@ var ts; function convertCompilerOptionsForTelemetry(opts) { var out = {}; for (var key in opts) { - if (opts.hasOwnProperty(key)) { + if (ts.hasProperty(opts, key)) { var type = getOptionFromName(key); if (type !== undefined) { // Ignore unknown options out[key] = getOptionValueWithEmptyStrings(opts[key], type); @@ -42991,7 +43294,7 @@ var ts; function withPackageId(packageInfo, r) { var packageId; if (r && packageInfo) { - var packageJsonContent = packageInfo.packageJsonContent; + var packageJsonContent = packageInfo.contents.packageJsonContent; if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") { packageId = { name: packageJsonContent.name, @@ -44031,6 +44334,9 @@ var ts; requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; + if (traceEnabled && ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) <= ts.ModuleResolutionKind.NodeNext) { + trace(host, ts.Diagnostics.Resolving_in_0_mode_with_conditions_1, features & NodeResolutionFeatures.EsmMode ? "ESM" : "CJS", conditions.map(function (c) { return "'".concat(c, "'"); }).join(", ")); + } var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { @@ -44310,16 +44616,16 @@ var ts; function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined; - var packageJsonContent = packageInfo && packageInfo.packageJsonContent; - var versionPaths = packageInfo && packageInfo.versionPaths; + var packageJsonContent = packageInfo && packageInfo.contents.packageJsonContent; + var versionPaths = packageInfo && packageInfo.contents.versionPaths; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } /* @internal */ function getEntrypointsFromPackageJsonInfo(packageJsonInfo, options, host, cache, resolveJs) { - if (!resolveJs && packageJsonInfo.resolvedEntrypoints !== undefined) { + if (!resolveJs && packageJsonInfo.contents.resolvedEntrypoints !== undefined) { // Cached value excludes resolutions to JS files - those could be // cached separately, but they're used rarely. - return packageJsonInfo.resolvedEntrypoints; + return packageJsonInfo.contents.resolvedEntrypoints; } var entrypoints; var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript; @@ -44328,13 +44634,13 @@ var ts; requireState.conditions = ["node", "require", "types"]; requireState.requestContainingDirectory = packageJsonInfo.packageDirectory; var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, - /*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths); + /*onlyRecordFailures*/ false, requireState, packageJsonInfo.contents.packageJsonContent, packageJsonInfo.contents.versionPaths); entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path); - if (features & NodeResolutionFeatures.Exports && packageJsonInfo.packageJsonContent.exports) { + if (features & NodeResolutionFeatures.Exports && packageJsonInfo.contents.packageJsonContent.exports) { for (var _i = 0, _a = [["node", "import", "types"], ["node", "require", "types"]]; _i < _a.length; _i++) { var conditions = _a[_i]; var exportState = __assign(__assign({}, requireState), { failedLookupLocations: [], conditions: conditions }); - var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.packageJsonContent.exports, exportState, extensions); + var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, exportState, extensions); if (exportResolutions) { for (var _b = 0, exportResolutions_1 = exportResolutions; _b < exportResolutions_1.length; _b++) { var resolution = exportResolutions_1[_b]; @@ -44343,7 +44649,7 @@ var ts; } } } - return packageJsonInfo.resolvedEntrypoints = entrypoints || false; + return packageJsonInfo.contents.resolvedEntrypoints = entrypoints || false; } ts.getEntrypointsFromPackageJsonInfo = getEntrypointsFromPackageJsonInfo; function loadEntrypointsFromExportMap(scope, exports, state, extensions) { @@ -44447,7 +44753,9 @@ var ts; if (traceEnabled) trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); state.affectingLocations.push(packageJsonPath); - return existing; + return existing.packageDirectory === packageDirectory ? + existing : + { packageDirectory: packageDirectory, contents: existing.contents }; } else { if (existing && traceEnabled) @@ -44463,7 +44771,7 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined }; + var result = { packageDirectory: packageDirectory, contents: { packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined } }; (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); state.affectingLocations.push(packageJsonPath); return result; @@ -44588,17 +44896,16 @@ var ts; } function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) { var _a, _b; - var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; - var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); + var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a)); var scope = getPackageScopeForPath(directoryPath, state); - if (!scope || !scope.packageJsonContent.exports) { + if (!scope || !scope.contents.packageJsonContent.exports) { return undefined; } - if (typeof scope.packageJsonContent.name !== "string") { + if (typeof scope.contents.packageJsonContent.name !== "string") { return undefined; } var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry - var nameParts = ts.getPathComponents(scope.packageJsonContent.name); + var nameParts = ts.getPathComponents(scope.contents.packageJsonContent.name); if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) { return undefined; } @@ -44606,30 +44913,30 @@ var ts; return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : ".".concat(ts.directorySeparator).concat(trailingParts.join(ts.directorySeparator)), state, cache, redirectedReference); } function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) { - if (!scope.packageJsonContent.exports) { + if (!scope.contents.packageJsonContent.exports) { return undefined; } if (subpath === ".") { var mainExport = void 0; - if (typeof scope.packageJsonContent.exports === "string" || Array.isArray(scope.packageJsonContent.exports) || (typeof scope.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.packageJsonContent.exports))) { - mainExport = scope.packageJsonContent.exports; + if (typeof scope.contents.packageJsonContent.exports === "string" || Array.isArray(scope.contents.packageJsonContent.exports) || (typeof scope.contents.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.contents.packageJsonContent.exports))) { + mainExport = scope.contents.packageJsonContent.exports; } - else if (ts.hasProperty(scope.packageJsonContent.exports, ".")) { - mainExport = scope.packageJsonContent.exports["."]; + else if (ts.hasProperty(scope.contents.packageJsonContent.exports, ".")) { + mainExport = scope.contents.packageJsonContent.exports["."]; } if (mainExport) { var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false); - return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false, "."); } } - else if (allKeysStartWithDot(scope.packageJsonContent.exports)) { - if (typeof scope.packageJsonContent.exports !== "object") { + else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) { + if (typeof scope.contents.packageJsonContent.exports !== "object") { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory); } return toSearchResult(/*value*/ undefined); } - var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.packageJsonContent.exports, scope, /*isImports*/ false); + var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.contents.packageJsonContent.exports, scope, /*isImports*/ false); if (result) { return result; } @@ -44647,8 +44954,7 @@ var ts; } return toSearchResult(/*value*/ undefined); } - var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; - var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); + var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a)); var scope = getPackageScopeForPath(directoryPath, state); if (!scope) { if (state.traceEnabled) { @@ -44656,13 +44962,13 @@ var ts; } return toSearchResult(/*value*/ undefined); } - if (!scope.packageJsonContent.imports) { + if (!scope.contents.packageJsonContent.imports) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory); } return toSearchResult(/*value*/ undefined); } - var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.packageJsonContent.imports, scope, /*isImports*/ true); + var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.contents.packageJsonContent.imports, scope, /*isImports*/ true); if (result) { return result; } @@ -44700,7 +45006,7 @@ var ts; var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!ts.endsWith(moduleName, ts.directorySeparator) && moduleName.indexOf("*") === -1 && ts.hasProperty(lookupTable, moduleName)) { var target = lookupTable[moduleName]; - return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName); } var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), comparePatternKeys); for (var _i = 0, expandingKeys_1 = expandingKeys; _i < expandingKeys_1.length; _i++) { @@ -44709,17 +45015,17 @@ var ts; var target = lookupTable[potentialTarget]; var starPos = potentialTarget.indexOf("*"); var subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.endsWith(potentialTarget, "*") && ts.startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length - 1); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.startsWith(moduleName, potentialTarget)) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false, potentialTarget); } } function matchesPatternWithTrailer(target, name) { @@ -44736,7 +45042,7 @@ var ts; */ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) { return loadModuleFromTargetImportOrExport; - function loadModuleFromTargetImportOrExport(target, subpath, pattern) { + function loadModuleFromTargetImportOrExport(target, subpath, pattern, key) { if (typeof target === "string") { if (!pattern && subpath.length > 0 && !ts.endsWith(target, "/")) { if (state.traceEnabled) { @@ -44747,6 +45053,8 @@ var ts; if (!ts.startsWith(target, "./")) { if (isImports && !ts.startsWith(target, "../") && !ts.startsWith(target, "/") && !ts.isRootedDiskPath(target)) { var combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath; + traceIfEnabled(state, ts.Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup); + traceIfEnabled(state, ts.Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/"); var result = nodeModuleNameResolverWorker(state.features, combinedLookup, scope.packageDirectory + "/", state.compilerOptions, state.host, cache, [extensions], redirectedReference); return toSearchResult(result.resolvedModule ? { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId, originalPath: result.resolvedModule.originalPath } : undefined); } @@ -44773,6 +45081,9 @@ var ts; } return toSearchResult(/*value*/ undefined); } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath); + } var finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); var inputLink = tryLoadInputFileForPath(finalPath, subpath, ts.combinePaths(scope.packageDirectory, "package.json"), isImports); if (inputLink) @@ -44782,14 +45093,18 @@ var ts; else if (typeof target === "object" && target !== null) { // eslint-disable-line no-null/no-null if (!Array.isArray(target)) { for (var _i = 0, _a = ts.getOwnKeys(target); _i < _a.length; _i++) { - var key = _a[_i]; - if (key === "default" || state.conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(state.conditions, key)) { - var subTarget = target[key]; - var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern); + var condition = _a[_i]; + if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) { + traceIfEnabled(state, ts.Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition); + var subTarget = target[condition]; + var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key); if (result) { return result; } } + else { + traceIfEnabled(state, ts.Diagnostics.Saw_non_matching_condition_0, condition); + } } return undefined; } @@ -44802,7 +45117,7 @@ var ts; } for (var _b = 0, target_2 = target; _b < target_2.length; _b++) { var elem = target_2[_b]; - var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern); + var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern, key); if (result) { return result; } @@ -44997,6 +45312,7 @@ var ts; } } function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state, cache, redirectedReference) { + var _a; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state); @@ -45007,22 +45323,16 @@ var ts; if (fromFile) { return noPackageId(fromFile); } - var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths); + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.contents.packageJsonContent, packageInfo.contents.versionPaths); return withPackageId(packageInfo, fromDirectory); } } - var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; var loader = function (extensions, candidate, onlyRecordFailures, state) { - var _a; - // package exports are higher priority than file/directory lookups (and, if there's exports present, blocks them) - if (packageInfo && packageInfo.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) { - return (_a = loadModuleFromExports(packageInfo, extensions, ts.combinePaths(".", rest), state, cache, redirectedReference)) === null || _a === void 0 ? void 0 : _a.value; - } var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths); + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.contents.packageJsonContent, packageInfo && packageInfo.contents.versionPaths); if (!pathAndExtension && packageInfo // eslint-disable-next-line no-null/no-null - && (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null) + && (packageInfo.contents.packageJsonContent.exports === undefined || packageInfo.contents.packageJsonContent.exports === null) && state.features & NodeResolutionFeatures.EsmMode) { // EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume // a default `index.js` entrypoint if no `main` or `exports` are present @@ -45030,19 +45340,24 @@ var ts; } return withPackageId(packageInfo, pathAndExtension); }; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var _b = parsePackageName(moduleName), packageName = _b.packageName, rest = _b.rest; + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + if (rest !== "") { + // Previous `packageInfo` may have been from a nested package.json; ensure we have the one from the package root now. packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state); - if (packageInfo && packageInfo.versionPaths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest); - } - var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); - var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state); - if (fromPaths) { - return fromPaths.value; - } + } + // package exports are higher priority than file/directory/typesVersions lookups and (and, if there's exports present, blocks them) + if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) { + return (_a = loadModuleFromExports(packageInfo, extensions, ts.combinePaths(".", rest), state, cache, redirectedReference)) === null || _a === void 0 ? void 0 : _a.value; + } + if (rest !== "" && packageInfo && packageInfo.contents.versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.contents.versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.contents.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; } } return loader(extensions, candidate, !nodeModulesDirectoryExists, state); @@ -45218,6 +45533,15 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } + function traceIfEnabled(state, diagnostic) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (state.traceEnabled) { + trace.apply(void 0, __spreadArray([state.host, diagnostic], args, false)); + } + } })(ts || (ts = {})); /* @internal */ var ts; @@ -45252,26 +45576,26 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return 0 /* ModuleInstanceState.NonInstantiated */; // 2. const enum declarations - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: if (ts.isEnumConst(node)) { return 2 /* ModuleInstanceState.ConstEnumOnly */; } break; // 3. non-exported import declarations - case 266 /* SyntaxKind.ImportDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: if (!(ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */))) { return 0 /* ModuleInstanceState.NonInstantiated */; } break; // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: var exportDeclaration = node; - if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 273 /* SyntaxKind.NamedExports */) { + if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 276 /* SyntaxKind.NamedExports */) { var state = 0 /* ModuleInstanceState.NonInstantiated */; for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -45287,7 +45611,7 @@ var ts; } break; // 5. other uninstantiated module declarations. - case 262 /* SyntaxKind.ModuleBlock */: { + case 265 /* SyntaxKind.ModuleBlock */: { var state_1 = 0 /* ModuleInstanceState.NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateCached(n, visited); @@ -45309,7 +45633,7 @@ var ts; }); return state_1; } - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return getModuleInstanceState(node, visited); case 79 /* SyntaxKind.Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should @@ -45510,7 +45834,7 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.kind === 271 /* SyntaxKind.ExportAssignment */) { + if (node.kind === 274 /* SyntaxKind.ExportAssignment */) { return node.isExportEquals ? "export=" /* InternalSymbolName.ExportEquals */ : "default" /* InternalSymbolName.Default */; } var name = ts.getNameOfDeclaration(node); @@ -45519,7 +45843,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"".concat(moduleName, "\"")); } - if (name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (name.kind === 164 /* SyntaxKind.ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteralLike(nameExpression)) { @@ -45545,36 +45869,36 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return "__constructor" /* InternalSymbolName.Constructor */; - case 179 /* SyntaxKind.FunctionType */: - case 174 /* SyntaxKind.CallSignature */: - case 323 /* SyntaxKind.JSDocSignature */: + case 181 /* SyntaxKind.FunctionType */: + case 176 /* SyntaxKind.CallSignature */: + case 326 /* SyntaxKind.JSDocSignature */: return "__call" /* InternalSymbolName.Call */; - case 180 /* SyntaxKind.ConstructorType */: - case 175 /* SyntaxKind.ConstructSignature */: + case 182 /* SyntaxKind.ConstructorType */: + case 177 /* SyntaxKind.ConstructSignature */: return "__new" /* InternalSymbolName.New */; - case 176 /* SyntaxKind.IndexSignature */: + case 178 /* SyntaxKind.IndexSignature */: return "__index" /* InternalSymbolName.Index */; - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: return "__export" /* InternalSymbolName.ExportStar */; - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: // json file should behave as // module.exports = ... return "export=" /* InternalSymbolName.ExportEquals */; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: if (ts.getAssignmentDeclarationKind(node) === 2 /* AssignmentDeclarationKind.ModuleExports */) { // module.exports = ... return "export=" /* InternalSymbolName.ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 317 /* SyntaxKind.JSDocFunctionType */: + case 320 /* SyntaxKind.JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* InternalSymbolName.New */ : "__call" /* InternalSymbolName.Call */); - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind), ", expected JSDocFunctionType"); }); + ts.Debug.assert(node.parent.kind === 320 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind), ", expected JSDocFunctionType"); }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -45593,7 +45917,7 @@ var ts; */ function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod, isComputedName) { ts.Debug.assert(isComputedName || !ts.hasDynamicName(node)); - var isDefaultExport = ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default"; + var isDefaultExport = ts.hasSyntacticModifier(node, 1024 /* ModifierFlags.Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default"; // The exported symbol for an export default function/class node is always named "default" var name = isComputedName ? "__computed" /* InternalSymbolName.Computed */ : isDefaultExport && parent ? "default" /* InternalSymbolName.Default */ @@ -45676,7 +46000,7 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 271 /* SyntaxKind.ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 274 /* SyntaxKind.ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; multipleDefaultExports_1 = true; @@ -45715,7 +46039,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */) || jsdocTreatAsExported(node); if (symbolFlags & 2097152 /* SymbolFlags.Alias */) { - if (node.kind === 275 /* SyntaxKind.ExportSpecifier */ || (node.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 278 /* SyntaxKind.ExportSpecifier */ || (node.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -45740,7 +46064,7 @@ var ts; if (ts.isJSDocTypeAlias(node)) ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* NodeFlags.ExportContext */)) { - if (!container.locals || (ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */) && !getDeclarationName(node))) { + if (!container.locals || (ts.hasSyntacticModifier(node, 1024 /* ModifierFlags.Default */) && !getDeclarationName(node))) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } var exportKind = symbolFlags & 111551 /* SymbolFlags.Value */ ? 1048576 /* SymbolFlags.ExportValue */ : 0; @@ -45804,7 +46128,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* ContainerFlags.IsContainer */) { - if (node.kind !== 214 /* SyntaxKind.ArrowFunction */) { + if (node.kind !== 216 /* SyntaxKind.ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -45826,10 +46150,10 @@ var ts; var saveActiveLabelList = activeLabelList; var saveHasExplicitReturn = hasExplicitReturn; var isImmediatelyInvoked = (containerFlags & 16 /* ContainerFlags.IsFunctionExpression */ && - !ts.hasSyntacticModifier(node, 256 /* ModifierFlags.Async */) && + !ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Async */) && !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node)) || - node.kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */; + node.kind === 172 /* SyntaxKind.ClassStaticBlockDeclaration */; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isImmediatelyInvoked) { @@ -45840,7 +46164,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isImmediatelyInvoked || node.kind === 171 /* SyntaxKind.Constructor */ || (ts.isInJSFile(node) && (node.kind === 256 /* SyntaxKind.FunctionDeclaration */ || node.kind === 213 /* SyntaxKind.FunctionExpression */)) ? createBranchLabel() : undefined; + currentReturnTarget = isImmediatelyInvoked || node.kind === 173 /* SyntaxKind.Constructor */ || (ts.isInJSFile(node) && (node.kind === 259 /* SyntaxKind.FunctionDeclaration */ || node.kind === 215 /* SyntaxKind.FunctionExpression */)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -45855,14 +46179,14 @@ var ts; node.flags |= 512 /* NodeFlags.HasExplicitReturn */; node.endFlowNode = currentFlow; } - if (node.kind === 305 /* SyntaxKind.SourceFile */) { + if (node.kind === 308 /* SyntaxKind.SourceFile */) { node.flags |= emitFlags; node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 171 /* SyntaxKind.Constructor */ || node.kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ || (ts.isInJSFile(node) && (node.kind === 256 /* SyntaxKind.FunctionDeclaration */ || node.kind === 213 /* SyntaxKind.FunctionExpression */))) { + if (node.kind === 173 /* SyntaxKind.Constructor */ || node.kind === 172 /* SyntaxKind.ClassStaticBlockDeclaration */ || (ts.isInJSFile(node) && (node.kind === 259 /* SyntaxKind.FunctionDeclaration */ || node.kind === 215 /* SyntaxKind.FunctionExpression */))) { node.returnFlowNode = currentFlow; } } @@ -45889,8 +46213,8 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 256 /* SyntaxKind.FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 256 /* SyntaxKind.FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 259 /* SyntaxKind.FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 259 /* SyntaxKind.FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -45913,59 +46237,59 @@ var ts; inAssignmentPattern = saveInAssignmentPattern; return; } - if (node.kind >= 237 /* SyntaxKind.FirstStatement */ && node.kind <= 253 /* SyntaxKind.LastStatement */ && !options.allowUnreachableCode) { + if (node.kind >= 240 /* SyntaxKind.FirstStatement */ && node.kind <= 256 /* SyntaxKind.LastStatement */ && !options.allowUnreachableCode) { node.flowNode = currentFlow; } switch (node.kind) { - case 241 /* SyntaxKind.WhileStatement */: + case 244 /* SyntaxKind.WhileStatement */: bindWhileStatement(node); break; - case 240 /* SyntaxKind.DoStatement */: + case 243 /* SyntaxKind.DoStatement */: bindDoStatement(node); break; - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: bindForStatement(node); break; - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: bindForInOrForOfStatement(node); break; - case 239 /* SyntaxKind.IfStatement */: + case 242 /* SyntaxKind.IfStatement */: bindIfStatement(node); break; - case 247 /* SyntaxKind.ReturnStatement */: - case 251 /* SyntaxKind.ThrowStatement */: + case 250 /* SyntaxKind.ReturnStatement */: + case 254 /* SyntaxKind.ThrowStatement */: bindReturnOrThrow(node); break; - case 246 /* SyntaxKind.BreakStatement */: - case 245 /* SyntaxKind.ContinueStatement */: + case 249 /* SyntaxKind.BreakStatement */: + case 248 /* SyntaxKind.ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 252 /* SyntaxKind.TryStatement */: + case 255 /* SyntaxKind.TryStatement */: bindTryStatement(node); break; - case 249 /* SyntaxKind.SwitchStatement */: + case 252 /* SyntaxKind.SwitchStatement */: bindSwitchStatement(node); break; - case 263 /* SyntaxKind.CaseBlock */: + case 266 /* SyntaxKind.CaseBlock */: bindCaseBlock(node); break; - case 289 /* SyntaxKind.CaseClause */: + case 292 /* SyntaxKind.CaseClause */: bindCaseClause(node); break; - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: bindExpressionStatement(node); break; - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: bindLabeledStatement(node); break; - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: if (ts.isDestructuringAssignment(node)) { // Carry over whether we are in an assignment pattern to // binary expressions that could actually be an initializer @@ -45975,47 +46299,50 @@ var ts; } bindBinaryExpressionFlow(node); break; - case 215 /* SyntaxKind.DeleteExpression */: + case 217 /* SyntaxKind.DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 222 /* SyntaxKind.ConditionalExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: bindAccessExpressionFlow(node); break; - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: bindCallExpressionFlow(node); break; - case 230 /* SyntaxKind.NonNullExpression */: + case 232 /* SyntaxKind.NonNullExpression */: bindNonNullExpressionFlow(node); break; - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 339 /* SyntaxKind.JSDocEnumTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 305 /* SyntaxKind.SourceFile */: { + case 308 /* SyntaxKind.SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 235 /* SyntaxKind.Block */: - case 262 /* SyntaxKind.ModuleBlock */: + case 238 /* SyntaxKind.Block */: + case 265 /* SyntaxKind.ModuleBlock */: bindEachFunctionsFirst(node.statements); break; - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: bindBindingElementFlow(node); break; - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 225 /* SyntaxKind.SpreadElement */: + case 166 /* SyntaxKind.Parameter */: + bindParameterFlow(node); + break; + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 227 /* SyntaxKind.SpreadElement */: // Carry over whether we are in an assignment pattern of Object and Array literals // as well as their children that are valid assignment targets. inAssignmentPattern = saveInAssignmentPattern; @@ -46032,19 +46359,19 @@ var ts; case 79 /* SyntaxKind.Identifier */: case 80 /* SyntaxKind.PrivateIdentifier */: case 108 /* SyntaxKind.ThisKeyword */: - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return containsNarrowableReference(expr); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return hasNarrowableArgument(expr); - case 212 /* SyntaxKind.ParenthesizedExpression */: - case 230 /* SyntaxKind.NonNullExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: + case 232 /* SyntaxKind.NonNullExpression */: return isNarrowingExpression(expr.expression); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: return expr.operator === 53 /* SyntaxKind.ExclamationToken */ && isNarrowingExpression(expr.operand); - case 216 /* SyntaxKind.TypeOfExpression */: + case 218 /* SyntaxKind.TypeOfExpression */: return isNarrowingExpression(expr.expression); } return false; @@ -46068,7 +46395,7 @@ var ts; } } } - if (expr.expression.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && + if (expr.expression.kind === 208 /* SyntaxKind.PropertyAccessExpression */ && containsNarrowableReference(expr.expression.expression)) { return true; } @@ -46101,9 +46428,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: switch (expr.operatorToken.kind) { case 63 /* SyntaxKind.EqualsToken */: return isNarrowableOperand(expr.left); @@ -46179,26 +46506,26 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 239 /* SyntaxKind.IfStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 240 /* SyntaxKind.DoStatement */: + case 242 /* SyntaxKind.IfStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 243 /* SyntaxKind.DoStatement */: return parent.expression === node; - case 242 /* SyntaxKind.ForStatement */: - case 222 /* SyntaxKind.ConditionalExpression */: + case 245 /* SyntaxKind.ForStatement */: + case 224 /* SyntaxKind.ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 212 /* SyntaxKind.ParenthesizedExpression */) { + if (node.kind === 214 /* SyntaxKind.ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 219 /* SyntaxKind.PrefixUnaryExpression */ && node.operator === 53 /* SyntaxKind.ExclamationToken */) { + else if (node.kind === 221 /* SyntaxKind.PrefixUnaryExpression */ && node.operator === 53 /* SyntaxKind.ExclamationToken */) { node = node.operand; } else { - return node.kind === 221 /* SyntaxKind.BinaryExpression */ && (node.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */ || + return node.kind === 223 /* SyntaxKind.BinaryExpression */ && (node.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */ || node.operatorToken.kind === 56 /* SyntaxKind.BarBarToken */ || node.operatorToken.kind === 60 /* SyntaxKind.QuestionQuestionToken */); } @@ -46244,7 +46571,7 @@ var ts; } function setContinueTarget(node, target) { var label = activeLabelList; - while (label && node.parent.kind === 250 /* SyntaxKind.LabeledStatement */) { + while (label && node.parent.kind === 253 /* SyntaxKind.LabeledStatement */) { label.continueTarget = target; label = label.next; node = node.parent; @@ -46295,12 +46622,12 @@ var ts; bind(node.expression); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 244 /* SyntaxKind.ForOfStatement */) { + if (node.kind === 247 /* SyntaxKind.ForOfStatement */) { bind(node.awaitModifier); } addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 255 /* SyntaxKind.VariableDeclarationList */) { + if (node.initializer.kind !== 258 /* SyntaxKind.VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -46322,7 +46649,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 247 /* SyntaxKind.ReturnStatement */) { + if (node.kind === 250 /* SyntaxKind.ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -46339,7 +46666,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 246 /* SyntaxKind.BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 249 /* SyntaxKind.BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -46444,7 +46771,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 290 /* SyntaxKind.DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 293 /* SyntaxKind.DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). Note, we no longer need // this property in control flow analysis, it's there only for backwards compatibility. @@ -46492,7 +46819,7 @@ var ts; function maybeBindExpressionFlowIfCall(node) { // A top level or comma expression call expression with a dotted function name and at least one argument // is potentially an assertion and is therefore included in the control flow. - if (node.kind === 208 /* SyntaxKind.CallExpression */) { + if (node.kind === 210 /* SyntaxKind.CallExpression */) { var call = node; if (call.expression.kind !== 106 /* SyntaxKind.SuperKeyword */ && ts.isDottedName(call.expression)) { currentFlow = createFlowCall(currentFlow, call); @@ -46518,7 +46845,7 @@ var ts; currentFlow = finishFlowLabel(postStatementLabel); } function bindDestructuringTargetFlow(node) { - if (node.kind === 221 /* SyntaxKind.BinaryExpression */ && node.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { + if (node.kind === 223 /* SyntaxKind.BinaryExpression */ && node.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -46529,10 +46856,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowMutation(16 /* FlowFlags.Assignment */, currentFlow, node); } - else if (node.kind === 204 /* SyntaxKind.ArrayLiteralExpression */) { + else if (node.kind === 206 /* SyntaxKind.ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 225 /* SyntaxKind.SpreadElement */) { + if (e.kind === 227 /* SyntaxKind.SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -46540,16 +46867,16 @@ var ts; } } } - else if (node.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { + else if (node.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 296 /* SyntaxKind.PropertyAssignment */) { + if (p.kind === 299 /* SyntaxKind.PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */) { + else if (p.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 298 /* SyntaxKind.SpreadAssignment */) { + else if (p.kind === 301 /* SyntaxKind.SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -46686,7 +47013,7 @@ var ts; var operator = node.operatorToken.kind; if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 63 /* SyntaxKind.EqualsToken */ && node.left.kind === 207 /* SyntaxKind.ElementAccessExpression */) { + if (operator === 63 /* SyntaxKind.EqualsToken */ && node.left.kind === 209 /* SyntaxKind.ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowMutation(256 /* FlowFlags.ArrayMutation */, currentFlow, node); @@ -46714,7 +47041,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + if (node.expression.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -46752,24 +47079,42 @@ var ts; } } function bindBindingElementFlow(node) { - if (ts.isBindingPattern(node.name)) { - // When evaluating a binding pattern, the initializer is evaluated before the binding pattern, per: - // - https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-iteratorbindinginitialization - // - `BindingElement: BindingPattern Initializer?` - // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization - // - `BindingElement: BindingPattern Initializer?` - bind(node.dotDotDotToken); - bind(node.propertyName); - bind(node.initializer); - bind(node.name); + // When evaluating a binding pattern, the initializer is evaluated before the binding pattern, per: + // - https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-iteratorbindinginitialization + // - `BindingElement: BindingPattern Initializer?` + // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization + // - `BindingElement: BindingPattern Initializer?` + bind(node.dotDotDotToken); + bind(node.propertyName); + bindInitializer(node.initializer); + bind(node.name); + } + function bindParameterFlow(node) { + bindEach(node.modifiers); + bind(node.dotDotDotToken); + bind(node.questionToken); + bind(node.type); + bindInitializer(node.initializer); + bind(node.name); + } + // a BindingElement/Parameter does not have side effects if initializers are not evaluated and used. (see GH#49759) + function bindInitializer(node) { + if (!node) { + return; } - else { - bindEachChild(node); + var entryFlow = currentFlow; + bind(node); + if (entryFlow === unreachableFlow || entryFlow === currentFlow) { + return; } + var exitFlow = createBranchLabel(); + addAntecedent(exitFlow, entryFlow); + addAntecedent(exitFlow, currentFlow); + currentFlow = finishFlowLabel(exitFlow); } function bindJSDocTypeAlias(node) { bind(node.tagName); - if (node.kind !== 339 /* SyntaxKind.JSDocEnumTag */ && node.fullName) { + if (node.kind !== 342 /* SyntaxKind.JSDocEnumTag */ && node.fullName) { // don't bind the type name yet; that's delayed until delayedBindJSDocTypedefTag ts.setParent(node.fullName, node); ts.setParentRecursive(node.fullName, /*incremental*/ false); @@ -46781,7 +47126,7 @@ var ts; function bindJSDocClassTag(node) { bindEachChild(node); var host = ts.getHostSignatureFromJSDoc(node); - if (host && host.kind !== 169 /* SyntaxKind.MethodDeclaration */) { + if (host && host.kind !== 171 /* SyntaxKind.MethodDeclaration */) { addDeclarationToSymbol(host.symbol, host, 32 /* SymbolFlags.Class */); } } @@ -46794,15 +47139,15 @@ var ts; } function bindOptionalChainRest(node) { switch (node.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: bind(node.questionDotToken); bind(node.name); break; - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: bind(node.questionDotToken); bind(node.argumentExpression); break; - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: bind(node.questionDotToken); bindEach(node.typeArguments); bindEach(node.arguments); @@ -46867,7 +47212,7 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = ts.skipParentheses(node.expression); - if (expr.kind === 213 /* SyntaxKind.FunctionExpression */ || expr.kind === 214 /* SyntaxKind.ArrowFunction */) { + if (expr.kind === 215 /* SyntaxKind.FunctionExpression */ || expr.kind === 216 /* SyntaxKind.ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -46879,7 +47224,7 @@ var ts; } } } - if (node.expression.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + if (node.expression.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { var propertyAccess = node.expression; if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowMutation(256 /* FlowFlags.ArrayMutation */, currentFlow, node); @@ -46888,55 +47233,55 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 226 /* SyntaxKind.ClassExpression */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 182 /* SyntaxKind.TypeLiteral */: - case 322 /* SyntaxKind.JSDocTypeLiteral */: - case 286 /* SyntaxKind.JsxAttributes */: + case 228 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 184 /* SyntaxKind.TypeLiteral */: + case 325 /* SyntaxKind.JSDocTypeLiteral */: + case 289 /* SyntaxKind.JsxAttributes */: return 1 /* ContainerFlags.IsContainer */; - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: return 1 /* ContainerFlags.IsContainer */ | 64 /* ContainerFlags.IsInterface */; - case 261 /* SyntaxKind.ModuleDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 195 /* SyntaxKind.MappedType */: - case 176 /* SyntaxKind.IndexSignature */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 197 /* SyntaxKind.MappedType */: + case 178 /* SyntaxKind.IndexSignature */: return 1 /* ContainerFlags.IsContainer */ | 32 /* ContainerFlags.HasLocals */; - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: return 1 /* ContainerFlags.IsContainer */ | 4 /* ContainerFlags.IsControlFlowContainer */ | 32 /* ContainerFlags.HasLocals */; - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 169 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethodOrAccessor(node)) { return 1 /* ContainerFlags.IsContainer */ | 4 /* ContainerFlags.IsControlFlowContainer */ | 32 /* ContainerFlags.HasLocals */ | 8 /* ContainerFlags.IsFunctionLike */ | 128 /* ContainerFlags.IsObjectLiteralOrClassExpressionMethodOrAccessor */; } // falls through - case 171 /* SyntaxKind.Constructor */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 174 /* SyntaxKind.CallSignature */: - case 323 /* SyntaxKind.JSDocSignature */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 179 /* SyntaxKind.FunctionType */: - case 175 /* SyntaxKind.ConstructSignature */: - case 180 /* SyntaxKind.ConstructorType */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 326 /* SyntaxKind.JSDocSignature */: + case 320 /* SyntaxKind.JSDocFunctionType */: + case 181 /* SyntaxKind.FunctionType */: + case 177 /* SyntaxKind.ConstructSignature */: + case 182 /* SyntaxKind.ConstructorType */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: return 1 /* ContainerFlags.IsContainer */ | 4 /* ContainerFlags.IsControlFlowContainer */ | 32 /* ContainerFlags.HasLocals */ | 8 /* ContainerFlags.IsFunctionLike */; - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: return 1 /* ContainerFlags.IsContainer */ | 4 /* ContainerFlags.IsControlFlowContainer */ | 32 /* ContainerFlags.HasLocals */ | 8 /* ContainerFlags.IsFunctionLike */ | 16 /* ContainerFlags.IsFunctionExpression */; - case 262 /* SyntaxKind.ModuleBlock */: + case 265 /* SyntaxKind.ModuleBlock */: return 4 /* ContainerFlags.IsControlFlowContainer */; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: return node.initializer ? 4 /* ContainerFlags.IsControlFlowContainer */ : 0; - case 292 /* SyntaxKind.CatchClause */: - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 263 /* SyntaxKind.CaseBlock */: + case 295 /* SyntaxKind.CatchClause */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 266 /* SyntaxKind.CaseBlock */: return 2 /* ContainerFlags.IsBlockScopedContainer */; - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -46969,46 +47314,46 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 226 /* SyntaxKind.ClassExpression */: - case 257 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 182 /* SyntaxKind.TypeLiteral */: - case 322 /* SyntaxKind.JSDocTypeLiteral */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 286 /* SyntaxKind.JsxAttributes */: + case 184 /* SyntaxKind.TypeLiteral */: + case 325 /* SyntaxKind.JSDocTypeLiteral */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 289 /* SyntaxKind.JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 323 /* SyntaxKind.JSDocSignature */: - case 176 /* SyntaxKind.IndexSignature */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 195 /* SyntaxKind.MappedType */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 326 /* SyntaxKind.JSDocSignature */: + case 178 /* SyntaxKind.IndexSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 320 /* SyntaxKind.JSDocFunctionType */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 197 /* SyntaxKind.MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -47116,10 +47461,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -47216,7 +47561,7 @@ var ts; node.originalKeywordKind <= 125 /* SyntaxKind.LastFutureReservedWord */) { file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } - else if (node.originalKeywordKind === 132 /* SyntaxKind.AwaitKeyword */) { + else if (node.originalKeywordKind === 133 /* SyntaxKind.AwaitKeyword */) { if (ts.isExternalModule(file) && ts.isInTopLevelContext(node)) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, ts.declarationNameToString(node))); } @@ -47318,8 +47663,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ScriptTarget.ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 305 /* SyntaxKind.SourceFile */ && - blockScopeContainer.kind !== 261 /* SyntaxKind.ModuleDeclaration */ && + if (blockScopeContainer.kind !== 308 /* SyntaxKind.SourceFile */ && + blockScopeContainer.kind !== 264 /* SyntaxKind.ModuleDeclaration */ && !ts.isFunctionLikeOrClassStaticBlockDeclaration(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -47416,7 +47761,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 160 /* SyntaxKind.LastToken */) { + if (node.kind > 162 /* SyntaxKind.LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -47492,23 +47837,23 @@ var ts; } // falls through case 108 /* SyntaxKind.ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkContextualIdentifier(node); - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: if (currentFlow && ts.isPartOfTypeQuery(node)) { node.flowNode = currentFlow; } break; - case 231 /* SyntaxKind.MetaProperty */: + case 233 /* SyntaxKind.MetaProperty */: case 106 /* SyntaxKind.SuperKeyword */: node.flowNode = currentFlow; break; case 80 /* SyntaxKind.PrivateIdentifier */: return checkPrivateIdentifier(node); - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: var expr = node; if (currentFlow && isNarrowableReference(expr)) { expr.flowNode = currentFlow; @@ -47523,7 +47868,7 @@ var ts; declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* SymbolFlags.FunctionScopedVariable */ | 134217728 /* SymbolFlags.ModuleExports */, 111550 /* SymbolFlags.FunctionScopedVariableExcludes */); } break; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* AssignmentDeclarationKind.ExportsProperty */: @@ -47559,78 +47904,78 @@ var ts; ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return checkStrictModeCatchClause(node); - case 215 /* SyntaxKind.DeleteExpression */: + case 217 /* SyntaxKind.DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* SyntaxKind.NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 248 /* SyntaxKind.WithStatement */: + case 251 /* SyntaxKind.WithStatement */: return checkStrictModeWithStatement(node); - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: return checkStrictModeLabeledStatement(node); - case 192 /* SyntaxKind.ThisType */: + case 194 /* SyntaxKind.ThisType */: seenThisKeyword = true; return; - case 177 /* SyntaxKind.TypePredicate */: + case 179 /* SyntaxKind.TypePredicate */: break; // Binding the children will handle everything - case 163 /* SyntaxKind.TypeParameter */: + case 165 /* SyntaxKind.TypeParameter */: return bindTypeParameter(node); - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return bindParameter(node); - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: return bindPropertyWorker(node); - case 296 /* SyntaxKind.PropertyAssignment */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* SymbolFlags.Property */, 0 /* SymbolFlags.PropertyExcludes */); - case 299 /* SyntaxKind.EnumMember */: + case 302 /* SyntaxKind.EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* SymbolFlags.EnumMember */, 900095 /* SymbolFlags.EnumMemberExcludes */); - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 176 /* SyntaxKind.IndexSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 178 /* SyntaxKind.IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* SymbolFlags.Signature */, 0 /* SymbolFlags.None */); - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. return bindPropertyOrMethodOrAccessor(node, 8192 /* SymbolFlags.Method */ | (node.questionToken ? 16777216 /* SymbolFlags.Optional */ : 0 /* SymbolFlags.None */), ts.isObjectLiteralMethod(node) ? 0 /* SymbolFlags.PropertyExcludes */ : 103359 /* SymbolFlags.MethodExcludes */); - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return bindFunctionDeclaration(node); - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* SymbolFlags.Constructor */, /*symbolExcludes:*/ 0 /* SymbolFlags.None */); - case 172 /* SyntaxKind.GetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: return bindPropertyOrMethodOrAccessor(node, 32768 /* SymbolFlags.GetAccessor */, 46015 /* SymbolFlags.GetAccessorExcludes */); - case 173 /* SyntaxKind.SetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SymbolFlags.SetAccessor */, 78783 /* SymbolFlags.SetAccessorExcludes */); - case 179 /* SyntaxKind.FunctionType */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 323 /* SyntaxKind.JSDocSignature */: - case 180 /* SyntaxKind.ConstructorType */: + case 181 /* SyntaxKind.FunctionType */: + case 320 /* SyntaxKind.JSDocFunctionType */: + case 326 /* SyntaxKind.JSDocSignature */: + case 182 /* SyntaxKind.ConstructorType */: return bindFunctionOrConstructorType(node); - case 182 /* SyntaxKind.TypeLiteral */: - case 322 /* SyntaxKind.JSDocTypeLiteral */: - case 195 /* SyntaxKind.MappedType */: + case 184 /* SyntaxKind.TypeLiteral */: + case 325 /* SyntaxKind.JSDocTypeLiteral */: + case 197 /* SyntaxKind.MappedType */: return bindAnonymousTypeWorker(node); - case 332 /* SyntaxKind.JSDocClassTag */: + case 335 /* SyntaxKind.JSDocClassTag */: return bindJSDocClassTag(node); - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: return bindFunctionExpression(node); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: var assignmentKind = ts.getAssignmentDeclarationKind(node); switch (assignmentKind) { case 7 /* AssignmentDeclarationKind.ObjectDefinePropertyValue */: @@ -47649,70 +47994,73 @@ var ts; } break; // Members of classes, interfaces, and modules - case 226 /* SyntaxKind.ClassExpression */: - case 257 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* SymbolFlags.Interface */, 788872 /* SymbolFlags.InterfaceExcludes */); - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* SymbolFlags.TypeAlias */, 788968 /* SymbolFlags.TypeAliasExcludes */); - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return bindEnumDeclaration(node); - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 286 /* SyntaxKind.JsxAttributes */: + case 289 /* SyntaxKind.JsxAttributes */: return bindJsxAttributes(node); - case 285 /* SyntaxKind.JsxAttribute */: + case 288 /* SyntaxKind.JsxAttribute */: return bindJsxAttribute(node, 4 /* SymbolFlags.Property */, 0 /* SymbolFlags.PropertyExcludes */); // Imports and exports - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 268 /* SyntaxKind.NamespaceImport */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 275 /* SyntaxKind.ExportSpecifier */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 271 /* SyntaxKind.NamespaceImport */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* SymbolFlags.Alias */, 2097152 /* SymbolFlags.AliasExcludes */); - case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 267 /* SyntaxKind.NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 267 /* SyntaxKind.ImportClause */: + case 270 /* SyntaxKind.ImportClause */: return bindImportClause(node); - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: return bindExportDeclaration(node); - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: return bindExportAssignment(node); - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: if (!ts.isFunctionLikeOrClassStaticBlockDeclaration(node.parent)) { return; } // falls through - case 262 /* SyntaxKind.ModuleBlock */: + case 265 /* SyntaxKind.ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 340 /* SyntaxKind.JSDocParameterTag */: - if (node.parent.kind === 323 /* SyntaxKind.JSDocSignature */) { + case 343 /* SyntaxKind.JSDocParameterTag */: + if (node.parent.kind === 326 /* SyntaxKind.JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 322 /* SyntaxKind.JSDocTypeLiteral */) { + if (node.parent.kind !== 325 /* SyntaxKind.JSDocTypeLiteral */) { break; } // falls through - case 347 /* SyntaxKind.JSDocPropertyTag */: + case 350 /* SyntaxKind.JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 316 /* SyntaxKind.JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 319 /* SyntaxKind.JSDocOptionalType */ ? 4 /* SymbolFlags.Property */ | 16777216 /* SymbolFlags.Optional */ : 4 /* SymbolFlags.Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* SymbolFlags.PropertyExcludes */); - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 339 /* SyntaxKind.JSDocEnumTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } function bindPropertyWorker(node) { - return bindPropertyOrMethodOrAccessor(node, 4 /* SymbolFlags.Property */ | (node.questionToken ? 16777216 /* SymbolFlags.Optional */ : 0 /* SymbolFlags.None */), 0 /* SymbolFlags.PropertyExcludes */); + var isAutoAccessor = ts.isAutoAccessorPropertyDeclaration(node); + var includes = isAutoAccessor ? 98304 /* SymbolFlags.Accessor */ : 4 /* SymbolFlags.Property */; + var excludes = isAutoAccessor ? 13247 /* SymbolFlags.AccessorExcludes */ : 0 /* SymbolFlags.PropertyExcludes */; + return bindPropertyOrMethodOrAccessor(node, includes | (node.questionToken ? 16777216 /* SymbolFlags.Optional */ : 0 /* SymbolFlags.None */), excludes); } function bindAnonymousTypeWorker(node) { return bindAnonymousDeclaration(node, 2048 /* SymbolFlags.TypeLiteral */, "__type" /* InternalSymbolName.Type */); @@ -47872,8 +48220,8 @@ var ts; } var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { @@ -47895,12 +48243,12 @@ var ts; addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* SymbolFlags.Class */); } break; - case 171 /* SyntaxKind.Constructor */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; @@ -47912,7 +48260,7 @@ var ts; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* SymbolFlags.Property */ | 67108864 /* SymbolFlags.Assignment */, 0 /* SymbolFlags.None */, /*isReplaceableByMethod*/ true); } break; - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script if (ts.hasDynamicName(node)) { break; @@ -47941,7 +48289,7 @@ var ts; if (node.expression.kind === 108 /* SyntaxKind.ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 305 /* SyntaxKind.SourceFile */) { + else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 308 /* SyntaxKind.SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -47981,7 +48329,7 @@ var ts; } function bindObjectDefinePropertyAssignment(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); - var isToplevel = node.parent.parent.kind === 305 /* SyntaxKind.SourceFile */; + var isToplevel = node.parent.parent.kind === 308 /* SyntaxKind.SourceFile */; namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false); bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); } @@ -48090,8 +48438,8 @@ var ts; } function isTopLevelNamespaceAssignment(propertyAccess) { return ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 305 /* SyntaxKind.SourceFile */ - : propertyAccess.parent.parent.kind === 305 /* SyntaxKind.SourceFile */; + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 308 /* SyntaxKind.SourceFile */ + : propertyAccess.parent.parent.kind === 308 /* SyntaxKind.SourceFile */; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); @@ -48170,7 +48518,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 257 /* SyntaxKind.ClassDeclaration */) { + if (node.kind === 260 /* SyntaxKind.ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* SymbolFlags.Class */, 899503 /* SymbolFlags.ClassExcludes */); } else { @@ -48212,7 +48560,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - var possibleVariableDecl = node.kind === 254 /* SyntaxKind.VariableDeclaration */ ? node : node.parent.parent; + var possibleVariableDecl = node.kind === 257 /* SyntaxKind.VariableDeclaration */ ? node : node.parent.parent; if (ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && !ts.getJSDocTypeTag(node) && @@ -48240,7 +48588,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 340 /* SyntaxKind.JSDocParameterTag */ && container.kind !== 323 /* SyntaxKind.JSDocSignature */) { + if (node.kind === 343 /* SyntaxKind.JSDocParameterTag */ && container.kind !== 326 /* SyntaxKind.JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 16777216 /* NodeFlags.Ambient */)) { @@ -48317,7 +48665,7 @@ var ts; declareSymbolAndAddToSymbolTable(node, 262144 /* SymbolFlags.TypeParameter */, 526824 /* SymbolFlags.TypeParameterExcludes */); } } - else if (node.parent.kind === 190 /* SyntaxKind.InferType */) { + else if (node.parent.kind === 192 /* SyntaxKind.InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { @@ -48345,11 +48693,11 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 236 /* SyntaxKind.EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 239 /* SyntaxKind.EmptyStatement */) || // report error on class declarations - node.kind === 257 /* SyntaxKind.ClassDeclaration */ || + node.kind === 260 /* SyntaxKind.ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 261 /* SyntaxKind.ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); + (node.kind === 264 /* SyntaxKind.ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -48393,12 +48741,12 @@ var ts; } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return true; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* ModuleInstanceState.Instantiated */; - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return ts.hasSyntacticModifier(s, 2048 /* ModifierFlags.Const */); default: return false; @@ -48599,7 +48947,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 181 /* SyntaxKind.TypeQuery */) { + if (d.type && d.type.kind === 183 /* SyntaxKind.TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -48785,8 +49133,6 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; - IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; - IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var RecursionFlags; (function (RecursionFlags) { @@ -49021,6 +49367,7 @@ var ts; getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, getIndexInfoOfType: function (type, kind) { return getIndexInfoOfType(type, kind === 0 /* IndexKind.String */ ? stringType : numberType); }, getIndexInfosOfType: getIndexInfosOfType, + getIndexInfosOfIndexSymbol: getIndexInfosOfIndexSymbol, getSignaturesOfType: getSignaturesOfType, getIndexTypeOfType: function (type, kind) { return getIndexTypeOfType(type, kind === 0 /* IndexKind.String */ ? stringType : numberType); }, getIndexType: function (type) { return getIndexType(type); }, @@ -49046,6 +49393,7 @@ var ts; signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, symbolToEntityName: nodeBuilder.symbolToEntityName, symbolToExpression: nodeBuilder.symbolToExpression, + symbolToNode: nodeBuilder.symbolToNode, symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, @@ -49214,6 +49562,12 @@ var ts; getOptionalType: function () { return optionalType; }, getPromiseType: function () { return getGlobalPromiseType(/*reportErrors*/ false); }, getPromiseLikeType: function () { return getGlobalPromiseLikeType(/*reportErrors*/ false); }, + getAsyncIterableType: function () { + var type = getGlobalAsyncIterableType(/*reportErrors*/ false); + if (type === emptyGenericType) + return undefined; + return type; + }, isSymbolAccessible: isSymbolAccessible, isArrayType: isArrayType, isTupleType: isTupleType, @@ -49294,6 +49648,7 @@ var ts; isPropertyAccessible: isPropertyAccessible, getTypeOnlyAliasDeclaration: getTypeOnlyAliasDeclaration, getMemberOverrideModifierStatus: getMemberOverrideModifierStatus, + isTypeParameterPossiblyReferenced: isTypeParameterPossiblyReferenced, }; function runWithInferenceBlockedFromSourceNode(node, fn) { var containingCall = ts.findAncestor(node, ts.isCallLikeExpression); @@ -49351,6 +49706,7 @@ var ts; var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error"); var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved"); + var nonInferrableAnyType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 65536 /* ObjectFlags.ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* TypeFlags.Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); var nonNullUnknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); @@ -49412,7 +49768,8 @@ var ts; var emptyTypeLiteralSymbol = createSymbol(2048 /* SymbolFlags.TypeLiteral */, "__type" /* InternalSymbolName.Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); - var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray)]) : unknownType; + var unknownEmptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, unknownEmptyObjectType]) : unknownType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyGenericType.instantiations = new ts.Map(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); @@ -49527,6 +49884,8 @@ var ts; var deferredGlobalOmitSymbol; var deferredGlobalAwaitedSymbol; var deferredGlobalBigIntType; + var deferredGlobalNaNSymbol; + var deferredGlobalRecordSymbol; var allPotentiallyUnusedIdentifiers = new ts.Map(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -49716,10 +50075,10 @@ var ts; } // Issue errors globally var file = ts.getSourceFileOfNode(location); - addErrorOrSuggestion(isError, "message" in message ? ts.createFileDiagnostic(file, 0, 0, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForFileFromMessageChain(file, message)); // eslint-disable-line no-in-operator + addErrorOrSuggestion(isError, "message" in message ? ts.createFileDiagnostic(file, 0, 0, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForFileFromMessageChain(file, message)); // eslint-disable-line local/no-in-operator return; } - addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator + addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line local/no-in-operator } function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) { var diagnostic = error(location, message, arg0, arg1, arg2, arg3); @@ -49948,7 +50307,7 @@ var ts; if (unidirectional === void 0) { unidirectional = false; } source.forEach(function (sourceSymbol, id) { var targetSymbol = target.get(id); - target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : getMergedSymbol(sourceSymbol)); }); } function mergeModuleAugmentation(moduleName) { @@ -50036,7 +50395,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks()); } function isGlobalSourceFile(node) { - return node.kind === 305 /* SyntaxKind.SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 308 /* SyntaxKind.SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -50047,9 +50406,9 @@ var ts; return symbol; } if (symbol.flags & 2097152 /* SymbolFlags.Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { + var targetFlags = getAllSymbolFlags(symbol); + // `targetFlags` will be `SymbolFlags.All` if an error occurred in alias resolution; this avoids cascading errors + if (targetFlags & meaning) { return symbol; } } @@ -50095,17 +50454,17 @@ var ts; } if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { // declaration is before usage - if (declaration.kind === 203 /* SyntaxKind.BindingElement */) { + if (declaration.kind === 205 /* SyntaxKind.BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 203 /* SyntaxKind.BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 205 /* SyntaxKind.BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 254 /* SyntaxKind.VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 257 /* SyntaxKind.VariableDeclaration */), usage); } - else if (declaration.kind === 254 /* SyntaxKind.VariableDeclaration */) { + else if (declaration.kind === 257 /* SyntaxKind.VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -50135,12 +50494,12 @@ var ts; // or if usage is in a type context: // 1. inside a type query (typeof in type position) // 2. inside a jsdoc comment - if (usage.parent.kind === 275 /* SyntaxKind.ExportSpecifier */ || (usage.parent.kind === 271 /* SyntaxKind.ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 278 /* SyntaxKind.ExportSpecifier */ || (usage.parent.kind === 274 /* SyntaxKind.ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 271 /* SyntaxKind.ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 274 /* SyntaxKind.ExportAssignment */ && usage.isExportEquals) { return true; } if (!!(usage.flags & 8388608 /* NodeFlags.JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { @@ -50162,9 +50521,9 @@ var ts; } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { switch (declaration.parent.parent.kind) { - case 237 /* SyntaxKind.VariableStatement */: - case 242 /* SyntaxKind.ForStatement */: - case 244 /* SyntaxKind.ForOfStatement */: + case 240 /* SyntaxKind.VariableStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 247 /* SyntaxKind.ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, declContainer)) { @@ -50192,7 +50551,7 @@ var ts; var initializerOfProperty = propertyDeclaration.initializer === current; if (initializerOfProperty) { if (ts.isStatic(current.parent)) { - if (declaration.kind === 169 /* SyntaxKind.MethodDeclaration */) { + if (declaration.kind === 171 /* SyntaxKind.MethodDeclaration */) { return true; } if (ts.isPropertyDeclaration(declaration) && ts.getContainingClass(usage) === ts.getContainingClass(declaration)) { @@ -50207,7 +50566,7 @@ var ts; } } else { - var isDeclarationInstanceProperty = declaration.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !ts.isStatic(declaration); + var isDeclarationInstanceProperty = declaration.kind === 169 /* SyntaxKind.PropertyDeclaration */ && !ts.isStatic(declaration); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -50230,19 +50589,19 @@ var ts; return "quit"; } switch (node.kind) { - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return true; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: // even when stopping at any property declaration, they need to come from the same class return stopAtAnyPropertyDeclaration && (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent) ? "quit" : true; - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: switch (node.parent.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 175 /* SyntaxKind.SetAccessor */: return true; default: return false; @@ -50282,18 +50641,18 @@ var ts; } function requiresScopeChangeWorker(node) { switch (node.kind) { - case 214 /* SyntaxKind.ArrowFunction */: - case 213 /* SyntaxKind.FunctionExpression */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 171 /* SyntaxKind.Constructor */: + case 216 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 173 /* SyntaxKind.Constructor */: // do not descend into these return false; - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 296 /* SyntaxKind.PropertyAssignment */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 299 /* SyntaxKind.PropertyAssignment */: return requiresScopeChangeWorker(node.name); - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: // static properties in classes introduce temporary variables if (ts.hasStaticModifier(node)) { return target < 99 /* ScriptTarget.ESNext */ || !useDefineForClassFields; @@ -50322,12 +50681,13 @@ var ts; * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with * the given name can be found. * + * @param nameNotFoundMessage If defined, we will report errors found during resolve. * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggstions) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggestions) { if (excludeGlobals === void 0) { excludeGlobals = false; } - if (getSpellingSuggstions === void 0) { getSpellingSuggstions = true; } - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggstions, getSymbol); + if (getSpellingSuggestions === void 0) { getSpellingSuggestions = true; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggestions, getSymbol); } function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggestions, lookup) { var _a, _b, _c; @@ -50358,14 +50718,14 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 788968 /* SymbolFlags.Type */ && lastLocation.kind !== 320 /* SyntaxKind.JSDoc */) { + if (meaning & result.flags & 788968 /* SymbolFlags.Type */ && lastLocation.kind !== 323 /* SyntaxKind.JSDoc */) { useResult = result.flags & 262144 /* SymbolFlags.TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 164 /* SyntaxKind.Parameter */ || - lastLocation.kind === 340 /* SyntaxKind.JSDocParameterTag */ || - lastLocation.kind === 341 /* SyntaxKind.JSDocReturnTag */ || - lastLocation.kind === 163 /* SyntaxKind.TypeParameter */ + lastLocation.kind === 166 /* SyntaxKind.Parameter */ || + lastLocation.kind === 343 /* SyntaxKind.JSDocParameterTag */ || + lastLocation.kind === 344 /* SyntaxKind.JSDocReturnTag */ || + lastLocation.kind === 165 /* SyntaxKind.TypeParameter */ // local types not visible outside the function body : false; } @@ -50380,13 +50740,13 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 164 /* SyntaxKind.Parameter */ || + lastLocation.kind === 166 /* SyntaxKind.Parameter */ || (lastLocation === location.type && !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } } - else if (location.kind === 189 /* SyntaxKind.ConditionalType */) { + else if (location.kind === 191 /* SyntaxKind.ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -50401,14 +50761,14 @@ var ts; } withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: var moduleExports = ((_a = getSymbolOfNode(location)) === null || _a === void 0 ? void 0 : _a.exports) || emptySymbols; - if (location.kind === 305 /* SyntaxKind.SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 16777216 /* NodeFlags.Ambient */ && !ts.isGlobalScopeAugmentation(location))) { + if (location.kind === 308 /* SyntaxKind.SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 16777216 /* NodeFlags.Ambient */ && !ts.isGlobalScopeAugmentation(location))) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* InternalSymbolName.Default */)) { @@ -50432,7 +50792,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* SymbolFlags.Alias */ && - (ts.getDeclarationOfKind(moduleExport, 275 /* SyntaxKind.ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 274 /* SyntaxKind.NamespaceExport */))) { + (ts.getDeclarationOfKind(moduleExport, 278 /* SyntaxKind.ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 277 /* SyntaxKind.NamespaceExport */))) { break; } } @@ -50446,12 +50806,12 @@ var ts; } } break; - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: if (result = lookup(((_c = getSymbolOfNode(location)) === null || _c === void 0 ? void 0 : _c.exports) || emptySymbols, name, meaning & 8 /* SymbolFlags.EnumMember */)) { break loop; } break; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -50469,9 +50829,9 @@ var ts; } } break; - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would // trigger resolving late-bound names, which we may already be in the process of doing while we're here! @@ -50485,12 +50845,14 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type // parameter list is associated, with the exception of static member declarations in classes. - error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + } return undefined; } break loop; } - if (location.kind === 226 /* SyntaxKind.ClassExpression */ && meaning & 32 /* SymbolFlags.Class */) { + if (location.kind === 228 /* SyntaxKind.ClassExpression */ && meaning & 32 /* SymbolFlags.Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -50498,7 +50860,7 @@ var ts; } } break; - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 94 /* SyntaxKind.ExtendsKeyword */) { var container = location.parent.parent; @@ -50518,34 +50880,36 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 258 /* SyntaxKind.InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 261 /* SyntaxKind.InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* SymbolFlags.Type */)) { - error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + } return undefined; } } break; - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: // when targeting ES6 or higher there is no 'arguments' in an arrow function // for lower compile targets the resolved symbol is used to emit an error if (ts.getEmitScriptTarget(compilerOptions) >= 2 /* ScriptTarget.ES2015 */) { break; } // falls through - case 169 /* SyntaxKind.MethodDeclaration */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 256 /* SyntaxKind.FunctionDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 259 /* SyntaxKind.FunctionDeclaration */: if (meaning & 3 /* SymbolFlags.Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 213 /* SyntaxKind.FunctionExpression */: + case 215 /* SyntaxKind.FunctionExpression */: if (meaning & 3 /* SymbolFlags.Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -50558,7 +50922,7 @@ var ts; } } break; - case 165 /* SyntaxKind.Decorator */: + case 167 /* SyntaxKind.Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -50567,7 +50931,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 164 /* SyntaxKind.Parameter */) { + if (location.parent && location.parent.kind === 166 /* SyntaxKind.Parameter */) { location = location.parent; } // @@ -50582,20 +50946,20 @@ var ts; // declare function y(x: T): any; // @param(1 as T) // <-- T should resolve to the type alias outside of class C // class C {} - if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 257 /* SyntaxKind.ClassDeclaration */)) { + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 260 /* SyntaxKind.ClassDeclaration */)) { location = location.parent; } break; - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 339 /* SyntaxKind.JSDocEnumTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: // js type aliases do not resolve names from their host, so skip past it var root = ts.getJSDocRoot(location); if (root) { location = root.parent; } break; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (!associatedDeclarationForContainingInitializerOrBindingName) { @@ -50603,7 +50967,7 @@ var ts; } } break; - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) { @@ -50611,7 +50975,7 @@ var ts; } } break; - case 190 /* SyntaxKind.InferType */: + case 192 /* SyntaxKind.InferType */: if (meaning & 262144 /* SymbolFlags.TypeParameter */) { var parameterName = location.typeParameter.name; if (parameterName && name === parameterName.escapedText) { @@ -50637,7 +51001,7 @@ var ts; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 305 /* SyntaxKind.SourceFile */); + ts.Debug.assert(lastLocation.kind === 308 /* SyntaxKind.SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } @@ -50682,8 +51046,8 @@ var ts; !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && + !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; var suggestedLib = void 0; @@ -50724,7 +51088,7 @@ var ts; } return undefined; } - else if (checkAndReportErrorForInvalidInitializer()) { + else if (nameNotFoundMessage && checkAndReportErrorForInvalidInitializer()) { return undefined; } // Perform extra checks only if error reporting was requested @@ -50770,9 +51134,9 @@ var ts; } } if (result && errorLocation && meaning & 111551 /* SymbolFlags.Value */ && result.flags & 2097152 /* SymbolFlags.Alias */ && !(result.flags & 111551 /* SymbolFlags.Value */) && !ts.isValidTypeOnlyAliasUseSite(errorLocation)) { - var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result); + var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, 111551 /* SymbolFlags.Value */); if (typeOnlyDeclaration) { - var message = typeOnlyDeclaration.kind === 275 /* SyntaxKind.ExportSpecifier */ + var message = typeOnlyDeclaration.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; var unescapedName = ts.unescapeLeadingUnderscores(name); @@ -50786,31 +51150,31 @@ var ts; function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) { if (!typeOnlyDeclaration) return diagnostic; - return ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(typeOnlyDeclaration, typeOnlyDeclaration.kind === 275 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics._0_was_exported_here : ts.Diagnostics._0_was_imported_here, unescapedName)); + return ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(typeOnlyDeclaration, typeOnlyDeclaration.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics._0_was_exported_here : ts.Diagnostics._0_was_imported_here, unescapedName)); } function getIsDeferredContext(location, lastLocation) { - if (location.kind !== 214 /* SyntaxKind.ArrowFunction */ && location.kind !== 213 /* SyntaxKind.FunctionExpression */) { + if (location.kind !== 216 /* SyntaxKind.ArrowFunction */ && location.kind !== 215 /* SyntaxKind.FunctionExpression */) { // initializers in instance property declaration of class like entities are executed in constructor and thus deferred return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) || - (location.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !ts.isStatic(location))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred + (location.kind === 169 /* SyntaxKind.PropertyDeclaration */ && !ts.isStatic(location))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred } if (lastLocation && lastLocation === location.name) { return false; } // generator functions and async functions are not inlined in control flow when immediately invoked - if (location.asteriskToken || ts.hasSyntacticModifier(location, 256 /* ModifierFlags.Async */)) { + if (location.asteriskToken || ts.hasSyntacticModifier(location, 512 /* ModifierFlags.Async */)) { return true; } return !ts.getImmediatelyInvokedFunctionExpression(location); } function isSelfReferenceLocation(node) { switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: // For `namespace N { N; }` + case 259 /* SyntaxKind.FunctionDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -50823,7 +51187,7 @@ var ts; if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 163 /* SyntaxKind.TypeParameter */) { + if (decl.kind === 165 /* SyntaxKind.TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); @@ -50880,9 +51244,9 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 79 /* SyntaxKind.Identifier */: - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -50926,14 +51290,14 @@ var ts; return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown"; } function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) { - if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 275 /* SyntaxKind.ExportSpecifier */) { + if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 278 /* SyntaxKind.ExportSpecifier */) { error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name); return true; } return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { + if (meaning & 111551 /* SymbolFlags.Value */) { if (isPrimitiveTypeName(name)) { if (isExtendedByInterface(errorLocation)) { error(errorLocation, ts.Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes, ts.unescapeLeadingUnderscores(name)); @@ -50944,7 +51308,8 @@ var ts; return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); - if (symbol && !(symbol.flags & 1024 /* SymbolFlags.NamespaceModule */)) { + var allFlags = symbol && getAllSymbolFlags(symbol); + if (symbol && allFlags !== undefined && !(allFlags & 111551 /* SymbolFlags.Value */)) { var rawName = ts.unescapeLeadingUnderscores(name); if (isES2015OrLaterConstructorName(name)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName); @@ -50992,16 +51357,16 @@ var ts; } return false; } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~788968 /* SymbolFlags.Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) { + if (meaning & (111551 /* SymbolFlags.Value */ & ~788968 /* SymbolFlags.Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (788968 /* SymbolFlags.Type */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* SymbolFlags.ValueModule */ | 1024 /* SymbolFlags.NamespaceModule */) & ~788968 /* SymbolFlags.Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1536 /* SymbolFlags.Module */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -51017,7 +51382,7 @@ var ts; return; } // Block-scoped variables cannot be used before their definition - var declaration = (_a = result.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 260 /* SyntaxKind.EnumDeclaration */); }); + var declaration = (_a = result.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 263 /* SyntaxKind.EnumDeclaration */); }); if (declaration === undefined) return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); if (!(declaration.flags & 16777216 /* NodeFlags.Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -51054,13 +51419,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return node; - case 267 /* SyntaxKind.ImportClause */: + case 270 /* SyntaxKind.ImportClause */: return node.parent; - case 268 /* SyntaxKind.NamespaceImport */: + case 271 /* SyntaxKind.NamespaceImport */: return node.parent.parent; - case 270 /* SyntaxKind.ImportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -51085,24 +51450,24 @@ var ts; * const { x } = require ... */ function isAliasSymbolDeclaration(node) { - return node.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ - || node.kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ - || node.kind === 267 /* SyntaxKind.ImportClause */ && !!node.name - || node.kind === 268 /* SyntaxKind.NamespaceImport */ - || node.kind === 274 /* SyntaxKind.NamespaceExport */ - || node.kind === 270 /* SyntaxKind.ImportSpecifier */ - || node.kind === 275 /* SyntaxKind.ExportSpecifier */ - || node.kind === 271 /* SyntaxKind.ExportAssignment */ && ts.exportAssignmentIsAlias(node) + return node.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ + || node.kind === 267 /* SyntaxKind.NamespaceExportDeclaration */ + || node.kind === 270 /* SyntaxKind.ImportClause */ && !!node.name + || node.kind === 271 /* SyntaxKind.NamespaceImport */ + || node.kind === 277 /* SyntaxKind.NamespaceExport */ + || node.kind === 273 /* SyntaxKind.ImportSpecifier */ + || node.kind === 278 /* SyntaxKind.ExportSpecifier */ + || node.kind === 274 /* SyntaxKind.ExportAssignment */ && ts.exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* AssignmentDeclarationKind.ModuleExports */ && ts.exportAssignmentIsAlias(node) || ts.isAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */ && isAliasableOrJsExpression(node.parent.right) - || node.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ - || node.kind === 296 /* SyntaxKind.PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || node.kind === 254 /* SyntaxKind.VariableDeclaration */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) - || node.kind === 203 /* SyntaxKind.BindingElement */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); + || node.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */ + || node.kind === 299 /* SyntaxKind.PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) + || node.kind === 257 /* SyntaxKind.VariableDeclaration */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) + || node.kind === 205 /* SyntaxKind.BindingElement */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -51115,7 +51480,7 @@ var ts; ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : undefined; } - if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */) { + if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 280 /* SyntaxKind.ExternalModuleReference */) { var immediate = resolveExternalModuleName(node, ts.getExternalModuleRequireArgument(node) || ts.getExternalModuleImportEqualsDeclarationExpression(node)); var resolved_4 = resolveExternalModuleSymbol(immediate); markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false); @@ -51128,7 +51493,7 @@ var ts; function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) { if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false) && !node.isTypeOnly) { var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node)); - var isExport = typeOnlyDeclaration.kind === 275 /* SyntaxKind.ExportSpecifier */; + var isExport = typeOnlyDeclaration.kind === 278 /* SyntaxKind.ExportSpecifier */; var message = isExport ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type; @@ -51147,7 +51512,7 @@ var ts; return resolved; } function isSyntacticDefault(node) { - return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */) || ts.isExportSpecifier(node)); + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasSyntacticModifier(node, 1024 /* ModifierFlags.Default */) || ts.isExportSpecifier(node)); } function getUsageModeForExpression(usage) { return ts.isStringLiteralLike(usage) ? ts.getModeForUsageLocation(ts.getSourceFileOfNode(usage), usage) : undefined; @@ -51163,6 +51528,7 @@ var ts; var usageMode = file && getUsageModeForExpression(usage); if (file && usageMode !== undefined) { var result = isESMFormatImportImportingCommonjsFormatFile(usageMode, file.impliedNodeFormat); + // deno: removed condition in typescript here (https://github.com/microsoft/TypeScript/issues/51321) if (result) { return result; } @@ -51247,11 +51613,11 @@ var ts; } function getModuleSpecifierForImportOrExport(node) { switch (node.kind) { - case 267 /* SyntaxKind.ImportClause */: return node.parent.moduleSpecifier; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: return ts.isExternalModuleReference(node.moduleReference) ? node.moduleReference.expression : undefined; - case 268 /* SyntaxKind.NamespaceImport */: return node.parent.parent.moduleSpecifier; - case 270 /* SyntaxKind.ImportSpecifier */: return node.parent.parent.parent.moduleSpecifier; - case 275 /* SyntaxKind.ExportSpecifier */: return node.parent.parent.moduleSpecifier; + case 270 /* SyntaxKind.ImportClause */: return node.parent.moduleSpecifier; + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return ts.isExternalModuleReference(node.moduleReference) ? node.moduleReference.expression : undefined; + case 271 /* SyntaxKind.NamespaceImport */: return node.parent.parent.moduleSpecifier; + case 273 /* SyntaxKind.ImportSpecifier */: return node.parent.parent.parent.moduleSpecifier; + case 278 /* SyntaxKind.ExportSpecifier */: return node.parent.parent.moduleSpecifier; default: return ts.Debug.assertNever(node); } } @@ -51520,31 +51886,31 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 254 /* SyntaxKind.VariableDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 267 /* SyntaxKind.ImportClause */: + case 270 /* SyntaxKind.ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 268 /* SyntaxKind.NamespaceImport */: + case 271 /* SyntaxKind.NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 274 /* SyntaxKind.NamespaceExport */: + case 277 /* SyntaxKind.NamespaceExport */: return getTargetOfNamespaceExport(node, dontRecursivelyResolve); - case 270 /* SyntaxKind.ImportSpecifier */: - case 203 /* SyntaxKind.BindingElement */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 205 /* SyntaxKind.BindingElement */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 275 /* SyntaxKind.ExportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: return getTargetOfExportSpecifier(node, 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */, dontRecursivelyResolve); - case 271 /* SyntaxKind.ExportAssignment */: - case 221 /* SyntaxKind.BinaryExpression */: + case 274 /* SyntaxKind.ExportAssignment */: + case 223 /* SyntaxKind.BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 267 /* SyntaxKind.NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); - case 207 /* SyntaxKind.ElementAccessExpression */: - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -51591,6 +51957,52 @@ var ts; } return undefined; } + /** + * Gets combined flags of a `symbol` and all alias targets it resolves to. `resolveAlias` + * is typically recursive over chains of aliases, but stops mid-chain if an alias is merged + * with another exported symbol, e.g. + * ```ts + * // a.ts + * export const a = 0; + * // b.ts + * export { a } from "./a"; + * export type a = number; + * // c.ts + * import { a } from "./b"; + * ``` + * Calling `resolveAlias` on the `a` in c.ts would stop at the merged symbol exported + * from b.ts, even though there is still more alias to resolve. Consequently, if we were + * trying to determine if the `a` in c.ts has a value meaning, looking at the flags on + * the local symbol and on the symbol returned by `resolveAlias` is not enough. + * @returns SymbolFlags.All if `symbol` is an alias that ultimately resolves to `unknown`; + * combined flags of all alias targets otherwise. + */ + function getAllSymbolFlags(symbol) { + var flags = symbol.flags; + var seenSymbols; + while (symbol.flags & 2097152 /* SymbolFlags.Alias */) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return 67108863 /* SymbolFlags.All */; + } + // Optimizations - try to avoid creating or adding to + // `seenSymbols` if possible + if (target === symbol || (seenSymbols === null || seenSymbols === void 0 ? void 0 : seenSymbols.has(target))) { + break; + } + if (target.flags & 2097152 /* SymbolFlags.Alias */) { + if (seenSymbols) { + seenSymbols.add(target); + } + else { + seenSymbols = new ts.Set([symbol, target]); + } + } + flags |= target.flags; + symbol = target; + } + return flags; + } /** * Marks a symbol as type-only if its declaration is syntactically type-only. * If it is not itself marked type-only, but resolves to a type-only alias @@ -51636,19 +52048,25 @@ var ts; return !!aliasDeclarationLinks.typeOnlyDeclaration; } /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */ - function getTypeOnlyAliasDeclaration(symbol) { + function getTypeOnlyAliasDeclaration(symbol, include) { if (!(symbol.flags & 2097152 /* SymbolFlags.Alias */)) { return undefined; } var links = getSymbolLinks(symbol); - return links.typeOnlyDeclaration || undefined; + if (include === undefined) { + return links.typeOnlyDeclaration || undefined; + } + if (links.typeOnlyDeclaration) { + return getAllSymbolFlags(resolveAlias(links.typeOnlyDeclaration.symbol)) & include ? links.typeOnlyDeclaration : undefined; + } + return undefined; } function markExportAsReferenced(node) { var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol)); + ((getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -51668,8 +52086,7 @@ var ts; // This way a chain of imports can be elided if ultimately the final input is only used in a type // position. if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveSymbol(symbol); - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551 /* SymbolFlags.Value */) { // import foo = checkExpressionCached(node.moduleReference); } @@ -51696,18 +52113,18 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 79 /* SyntaxKind.Identifier */ || entityName.parent.kind === 161 /* SyntaxKind.QualifiedName */) { + if (entityName.kind === 79 /* SyntaxKind.Identifier */ || entityName.parent.kind === 163 /* SyntaxKind.QualifiedName */) { return resolveEntityName(entityName, 1920 /* SymbolFlags.Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */); return resolveEntityName(entityName, 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol, containingLocation) { - return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* SymbolFormatFlags.DoNotIncludeSymbolChain */ | 4 /* SymbolFormatFlags.AllowAnyNodeKind */); + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 32 /* SymbolFormatFlags.DoNotIncludeSymbolChain */ | 4 /* SymbolFormatFlags.AllowAnyNodeKind */); } function getContainingQualifiedNameNode(node) { while (ts.isQualifiedName(node.parent)) { @@ -51748,9 +52165,9 @@ var ts; return getMergedSymbol(symbolFromJSPrototype); } } - else if (name.kind === 161 /* SyntaxKind.QualifiedName */ || name.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { - var left = name.kind === 161 /* SyntaxKind.QualifiedName */ ? name.left : name.expression; - var right = name.kind === 161 /* SyntaxKind.QualifiedName */ ? name.right : name.name; + else if (name.kind === 163 /* SyntaxKind.QualifiedName */ || name.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { + var left = name.kind === 163 /* SyntaxKind.QualifiedName */ ? name.left : name.expression; + var right = name.kind === 163 /* SyntaxKind.QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -51808,7 +52225,7 @@ var ts; throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* CheckFlags.Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* SymbolFlags.Alias */ || name.parent.kind === 271 /* SyntaxKind.ExportAssignment */)) { + if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* SymbolFlags.Alias */ || name.parent.kind === 274 /* SyntaxKind.ExportAssignment */)) { markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true); } return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -51976,7 +52393,7 @@ var ts; if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) { var scope = currentSourceFile.packageJsonScope; var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined; - if (scope && !scope.packageJsonContent.type) { + if (scope && !scope.contents.packageJsonContent.type) { if (targetExt) { diagnosticDetails = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json")); @@ -52149,7 +52566,7 @@ var ts; var _a; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!suppressInteropError && !(symbol.flags & (1536 /* SymbolFlags.Module */ | 3 /* SymbolFlags.Variable */)) && !ts.getDeclarationOfKind(symbol, 305 /* SyntaxKind.SourceFile */)) { + if (!suppressInteropError && !(symbol.flags & (1536 /* SymbolFlags.Module */ | 3 /* SymbolFlags.Variable */)) && !ts.getDeclarationOfKind(symbol, 308 /* SyntaxKind.SourceFile */)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; @@ -52509,13 +52926,13 @@ var ts; } function symbolIsValue(symbol, includeTypeOnlyMembers) { return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || - symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + symbol.flags & 2097152 /* SymbolFlags.Alias */ && getAllSymbolFlags(symbol) & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { var member = members_3[_i]; - if (member.kind === 171 /* SyntaxKind.Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 173 /* SyntaxKind.Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -52623,12 +53040,12 @@ var ts; } } switch (location.kind) { - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: var sym = getSymbolOfNode(location); // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred @@ -52637,9 +53054,9 @@ var ts; return { value: result }; } break; - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: // Type parameters are bound into `members` lists so they can merge across declarations // This is troublesome, since in all other respects, they behave like locals :cries: // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol @@ -52740,7 +53157,7 @@ var ts; && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details - && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 275 /* SyntaxKind.ExportSpecifier */))) { + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); if (candidate) { @@ -52788,8 +53205,10 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 275 /* SyntaxKind.ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { + var shouldResolveAlias = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */)); + symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + var flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + if (flags & meaning) { qualify = true; return true; } @@ -52803,10 +53222,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: continue; default: return false; @@ -52936,10 +53355,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 305 /* SyntaxKind.SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 308 /* SyntaxKind.SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 305 /* SyntaxKind.SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 308 /* SyntaxKind.SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -53007,14 +53426,14 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 181 /* SyntaxKind.TypeQuery */ || - entityName.parent.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */ && !ts.isPartOfTypeNode(entityName.parent) || - entityName.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (entityName.parent.kind === 183 /* SyntaxKind.TypeQuery */ || + entityName.parent.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */ && !ts.isPartOfTypeNode(entityName.parent) || + entityName.parent.kind === 164 /* SyntaxKind.ComputedPropertyName */) { // Typeof value meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; } - else if (entityName.kind === 161 /* SyntaxKind.QualifiedName */ || entityName.kind === 206 /* SyntaxKind.PropertyAccessExpression */ || - entityName.parent.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { + else if (entityName.kind === 163 /* SyntaxKind.QualifiedName */ || entityName.kind === 208 /* SyntaxKind.PropertyAccessExpression */ || + entityName.parent.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* SymbolFlags.Namespace */; @@ -53050,15 +53469,18 @@ var ts; if (flags & 8 /* SymbolFormatFlags.UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope */; } - if (flags & 16 /* SymbolFormatFlags.DoNotIncludeSymbolChain */) { + if (flags & 32 /* SymbolFormatFlags.DoNotIncludeSymbolChain */) { nodeFlags |= 134217728 /* NodeBuilderFlags.DoNotIncludeSymbolChain */; } - var builder = flags & 4 /* SymbolFormatFlags.AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + if (flags & 16 /* SymbolFormatFlags.WriteComputedProps */) { + nodeFlags |= 1073741824 /* NodeBuilderFlags.WriteComputedProps */; + } + var builder = flags & 4 /* SymbolFormatFlags.AllowAnyNodeKind */ ? nodeBuilder.symbolToNode : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 // add neverAsciiEscape for GH#39027 - var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 305 /* SyntaxKind.SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); + var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 308 /* SyntaxKind.SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* EmitHint.Unspecified */, entity, /*sourceFile*/ sourceFile, writer); return writer; @@ -53070,10 +53492,10 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* TypeFormatFlags.WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* SignatureKind.Construct */ ? 180 /* SyntaxKind.ConstructorType */ : 179 /* SyntaxKind.FunctionType */; + sigOutput = kind === 1 /* SignatureKind.Construct */ ? 182 /* SyntaxKind.ConstructorType */ : 181 /* SyntaxKind.FunctionType */; } else { - sigOutput = kind === 1 /* SignatureKind.Construct */ ? 175 /* SyntaxKind.ConstructSignature */ : 174 /* SyntaxKind.CallSignature */; + sigOutput = kind === 1 /* SignatureKind.Construct */ ? 177 /* SyntaxKind.ConstructSignature */ : 176 /* SyntaxKind.CallSignature */; } var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* NodeBuilderFlags.IgnoreErrors */ | 512 /* NodeBuilderFlags.WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); @@ -53153,7 +53575,25 @@ var ts; symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) { return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); }); }, + symbolToNode: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToNode(symbol, context, meaning); }); + }, }; + function symbolToNode(symbol, context, meaning) { + if (context.flags & 1073741824 /* NodeBuilderFlags.WriteComputedProps */) { + if (symbol.valueDeclaration) { + var name = ts.getNameOfDeclaration(symbol.valueDeclaration); + if (name && ts.isComputedPropertyName(name)) + return name; + } + var nameType = getSymbolLinks(symbol).nameType; + if (nameType && nameType.flags & (1024 /* TypeFlags.EnumLiteral */ | 8192 /* TypeFlags.UniqueESSymbol */)) { + context.enclosingDeclaration = nameType.symbol.valueDeclaration; + return ts.factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, meaning)); + } + } + return symbolToExpression(symbol, context, meaning); + } function withContext(enclosingDeclaration, flags, tracker, cb) { var _a, _b; ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* NodeFlags.Synthesized */) === 0); @@ -53238,7 +53678,7 @@ var ts; return undefined; // TODO: GH#18217 } context.approximateLength += 3; - return ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */); + return ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */); } if (!(context.flags & 536870912 /* NodeBuilderFlags.NoTypeReduction */)) { type = getReducedType(type); @@ -53248,29 +53688,29 @@ var ts; return ts.factory.createTypeReferenceNode(symbolToEntityNameNode(type.aliasSymbol), mapToTypeNodes(type.aliasTypeArguments, context)); } if (type === unresolvedType) { - return ts.addSyntheticLeadingComment(ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */), 3 /* SyntaxKind.MultiLineCommentTrivia */, "unresolved"); + return ts.addSyntheticLeadingComment(ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */), 3 /* SyntaxKind.MultiLineCommentTrivia */, "unresolved"); } context.approximateLength += 3; - return ts.factory.createKeywordTypeNode(type === intrinsicMarkerType ? 138 /* SyntaxKind.IntrinsicKeyword */ : 130 /* SyntaxKind.AnyKeyword */); + return ts.factory.createKeywordTypeNode(type === intrinsicMarkerType ? 139 /* SyntaxKind.IntrinsicKeyword */ : 131 /* SyntaxKind.AnyKeyword */); } if (type.flags & 2 /* TypeFlags.Unknown */) { - return ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */); + return ts.factory.createKeywordTypeNode(157 /* SyntaxKind.UnknownKeyword */); } if (type.flags & 4 /* TypeFlags.String */) { context.approximateLength += 6; - return ts.factory.createKeywordTypeNode(150 /* SyntaxKind.StringKeyword */); + return ts.factory.createKeywordTypeNode(152 /* SyntaxKind.StringKeyword */); } if (type.flags & 8 /* TypeFlags.Number */) { context.approximateLength += 6; - return ts.factory.createKeywordTypeNode(147 /* SyntaxKind.NumberKeyword */); + return ts.factory.createKeywordTypeNode(148 /* SyntaxKind.NumberKeyword */); } if (type.flags & 64 /* TypeFlags.BigInt */) { context.approximateLength += 6; - return ts.factory.createKeywordTypeNode(158 /* SyntaxKind.BigIntKeyword */); + return ts.factory.createKeywordTypeNode(160 /* SyntaxKind.BigIntKeyword */); } if (type.flags & 16 /* TypeFlags.Boolean */ && !type.aliasSymbol) { context.approximateLength += 7; - return ts.factory.createKeywordTypeNode(133 /* SyntaxKind.BooleanKeyword */); + return ts.factory.createKeywordTypeNode(134 /* SyntaxKind.BooleanKeyword */); } if (type.flags & 1024 /* TypeFlags.EnumLiteral */ && !(type.flags & 1048576 /* TypeFlags.Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); @@ -53324,7 +53764,7 @@ var ts; } } context.approximateLength += 13; - return ts.factory.createTypeOperatorNode(154 /* SyntaxKind.UniqueKeyword */, ts.factory.createKeywordTypeNode(151 /* SyntaxKind.SymbolKeyword */)); + return ts.factory.createTypeOperatorNode(156 /* SyntaxKind.UniqueKeyword */, ts.factory.createKeywordTypeNode(153 /* SyntaxKind.SymbolKeyword */)); } if (type.flags & 16384 /* TypeFlags.Void */) { context.approximateLength += 4; @@ -53332,7 +53772,7 @@ var ts; } if (type.flags & 32768 /* TypeFlags.Undefined */) { context.approximateLength += 9; - return ts.factory.createKeywordTypeNode(153 /* SyntaxKind.UndefinedKeyword */); + return ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UndefinedKeyword */); } if (type.flags & 65536 /* TypeFlags.Null */) { context.approximateLength += 4; @@ -53340,15 +53780,15 @@ var ts; } if (type.flags & 131072 /* TypeFlags.Never */) { context.approximateLength += 5; - return ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */); + return ts.factory.createKeywordTypeNode(144 /* SyntaxKind.NeverKeyword */); } if (type.flags & 4096 /* TypeFlags.ESSymbol */) { context.approximateLength += 6; - return ts.factory.createKeywordTypeNode(151 /* SyntaxKind.SymbolKeyword */); + return ts.factory.createKeywordTypeNode(153 /* SyntaxKind.SymbolKeyword */); } if (type.flags & 67108864 /* TypeFlags.NonPrimitive */) { context.approximateLength += 6; - return ts.factory.createKeywordTypeNode(148 /* SyntaxKind.ObjectKeyword */); + return ts.factory.createKeywordTypeNode(149 /* SyntaxKind.ObjectKeyword */); } if (ts.isThisTypeParameter(type)) { if (context.flags & 4194304 /* NodeBuilderFlags.InObjectTypeLiteral */) { @@ -53437,7 +53877,7 @@ var ts; var indexedType = type.type; context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); - return ts.factory.createTypeOperatorNode(140 /* SyntaxKind.KeyOfKeyword */, indexTypeNode); + return ts.factory.createTypeOperatorNode(141 /* SyntaxKind.KeyOfKeyword */, indexTypeNode); } if (type.flags & 134217728 /* TypeFlags.TemplateLiteral */) { var texts_1 = type.texts; @@ -53489,7 +53929,7 @@ var ts; // On the other hand, // checkType extends infer T extends checkType ? T extends extendsType ? trueType : falseType : never; // may also work with `infer ... extends ...` in, but would produce declarations only compatible with the latest TS. - return ts.factory.createConditionalTypeNode(checkTypeNode, ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName))), ts.factory.createConditionalTypeNode(ts.factory.createTypeReferenceNode(ts.factory.cloneNode(name)), typeToTypeNodeHelper(type.checkType, context), ts.factory.createConditionalTypeNode(newTypeVariable, extendsTypeNode_1, trueTypeNode_1, falseTypeNode_1), ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)), ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); + return ts.factory.createConditionalTypeNode(checkTypeNode, ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName))), ts.factory.createConditionalTypeNode(ts.factory.createTypeReferenceNode(ts.factory.cloneNode(name)), typeToTypeNodeHelper(type.checkType, context), ts.factory.createConditionalTypeNode(newTypeVariable, extendsTypeNode_1, trueTypeNode_1, falseTypeNode_1), ts.factory.createKeywordTypeNode(144 /* SyntaxKind.NeverKeyword */)), ts.factory.createKeywordTypeNode(144 /* SyntaxKind.NeverKeyword */)); } var saveInferTypeParameters = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; @@ -53531,7 +53971,7 @@ var ts; var name = typeParameterToName(newParam, context); newTypeVariable = ts.factory.createTypeReferenceNode(name); } - appropriateConstraintTypeNode = ts.factory.createTypeOperatorNode(140 /* SyntaxKind.KeyOfKeyword */, newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + appropriateConstraintTypeNode = ts.factory.createTypeOperatorNode(141 /* SyntaxKind.KeyOfKeyword */, newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); } else { appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); @@ -53547,7 +53987,7 @@ var ts; // wrap it with a conditional like `SomeModifiersType extends infer U ? {..the mapped type...} : never` to ensure the resulting // type stays homomorphic var originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode(type.declaration.typeParameter.constraint.type)) || unknownType, type.mapper); - return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 /* TypeFlags.Unknown */ ? undefined : typeToTypeNodeHelper(originalConstraint, context))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); + return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 /* TypeFlags.Unknown */ ? undefined : typeToTypeNodeHelper(originalConstraint, context))), result, ts.factory.createKeywordTypeNode(144 /* SyntaxKind.NeverKeyword */)); } return result; } @@ -53595,7 +54035,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* SymbolFlags.Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 305 /* SyntaxKind.SourceFile */ || declaration.parent.kind === 262 /* SyntaxKind.ModuleBlock */; + return declaration.parent.kind === 308 /* SyntaxKind.SourceFile */ || declaration.parent.kind === 265 /* SyntaxKind.ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -53684,12 +54124,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 179 /* SyntaxKind.FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 181 /* SyntaxKind.FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 180 /* SyntaxKind.ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 182 /* SyntaxKind.ConstructorType */, context); return signatureNode; } } @@ -53732,7 +54172,7 @@ var ts; } var elementType = typeToTypeNodeHelper(typeArguments[0], context); var arrayType = ts.factory.createArrayTypeNode(elementType); - return type.target === globalArrayType ? arrayType : ts.factory.createTypeOperatorNode(145 /* SyntaxKind.ReadonlyKeyword */, arrayType); + return type.target === globalArrayType ? arrayType : ts.factory.createTypeOperatorNode(146 /* SyntaxKind.ReadonlyKeyword */, arrayType); } else if (type.target.objectFlags & 8 /* ObjectFlags.Tuple */) { typeArguments = ts.sameMap(typeArguments, function (t, i) { return removeMissingType(t, !!(type.target.elementFlags[i] & 2 /* ElementFlags.Optional */)); }); @@ -53757,12 +54197,12 @@ var ts; } } var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode(tupleConstituentNodes), 1 /* EmitFlags.SingleLine */); - return type.target.readonly ? ts.factory.createTypeOperatorNode(145 /* SyntaxKind.ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode; + return type.target.readonly ? ts.factory.createTypeOperatorNode(146 /* SyntaxKind.ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode; } } if (context.encounteredError || (context.flags & 524288 /* NodeBuilderFlags.AllowEmptyTuple */)) { var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode([]), 1 /* EmitFlags.SingleLine */); - return type.target.readonly ? ts.factory.createTypeOperatorNode(145 /* SyntaxKind.ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode; + return type.target.readonly ? ts.factory.createTypeOperatorNode(146 /* SyntaxKind.ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode; } context.encounteredError = true; return undefined; // TODO: GH#18217 @@ -53869,13 +54309,13 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 174 /* SyntaxKind.CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 176 /* SyntaxKind.CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; if (signature.flags & 4 /* SignatureFlags.Abstract */) continue; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 175 /* SyntaxKind.ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 177 /* SyntaxKind.ConstructSignature */, context)); } for (var _d = 0, _e = resolvedType.indexInfos; _d < _e.length; _d++) { var info = _e[_d]; @@ -53912,7 +54352,7 @@ var ts; if (!(context.flags & 1 /* NodeBuilderFlags.NoTruncation */)) { return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("..."), /*typeArguments*/ undefined); } - return ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */); + return ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */); } function shouldUsePlaceholderForProperty(propertySymbol, context) { var _a; @@ -53962,7 +54402,7 @@ var ts; var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* TypeFlags.Undefined */); }), 0 /* SignatureKind.Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 168 /* SyntaxKind.MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 170 /* SyntaxKind.MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); typeElements.push(preserveCommentsOn(methodDeclaration)); } } @@ -53976,12 +54416,12 @@ var ts; context.reverseMappedStack || (context.reverseMappedStack = []); context.reverseMappedStack.push(propertySymbol); } - propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */); + propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */); if (propertyIsReverseMapped) { context.reverseMappedStack.pop(); } } - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(146 /* SyntaxKind.ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; } @@ -53990,8 +54430,8 @@ var ts; } function preserveCommentsOn(node) { var _a; - if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 347 /* SyntaxKind.JSDocPropertyTag */; })) { - var d = (_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 347 /* SyntaxKind.JSDocPropertyTag */; }); + if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 350 /* SyntaxKind.JSDocPropertyTag */; })) { + var d = (_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 350 /* SyntaxKind.JSDocPropertyTag */; }); var commentText = ts.getTextOfJSDocComment(d.comment); if (commentText) { ts.setSyntheticLeadingComments(node, [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); @@ -54090,7 +54530,7 @@ var ts; context.encounteredError = true; } context.approximateLength += (name.length + 4); - return ts.factory.createIndexSignature(indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + return ts.factory.createIndexSignature(indexInfo.isReadonly ? [ts.factory.createToken(146 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { var _a, _b, _c, _d; @@ -54108,7 +54548,7 @@ var ts; } var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it - var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* CheckFlags.RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 171 /* SyntaxKind.Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); + var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* CheckFlags.RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 173 /* SyntaxKind.Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); var thisParameter = context.flags & 33554432 /* NodeBuilderFlags.OmitThisParameter */ ? undefined : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { parameters.unshift(thisParameter); @@ -54117,7 +54557,7 @@ var ts; var typePredicate = getTypePredicateOfSignature(signature); if (typePredicate) { var assertsModifier = typePredicate.kind === 2 /* TypePredicateKind.AssertsThis */ || typePredicate.kind === 3 /* TypePredicateKind.AssertsIdentifier */ ? - ts.factory.createToken(128 /* SyntaxKind.AssertsKeyword */) : + ts.factory.createToken(129 /* SyntaxKind.AssertsKeyword */) : undefined; var parameterName = typePredicate.kind === 1 /* TypePredicateKind.Identifier */ || typePredicate.kind === 3 /* TypePredicateKind.AssertsIdentifier */ ? ts.setEmitFlags(ts.factory.createIdentifier(typePredicate.parameterName), 16777216 /* EmitFlags.NoAsciiEscaping */) : @@ -54131,28 +54571,28 @@ var ts; returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); } else if (!suppressAny) { - returnTypeNode = ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */); + returnTypeNode = ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */); } } var modifiers = options === null || options === void 0 ? void 0 : options.modifiers; - if ((kind === 180 /* SyntaxKind.ConstructorType */) && signature.flags & 4 /* SignatureFlags.Abstract */) { + if ((kind === 182 /* SyntaxKind.ConstructorType */) && signature.flags & 4 /* SignatureFlags.Abstract */) { var flags = ts.modifiersToFlags(modifiers); - modifiers = ts.factory.createModifiersFromModifierFlags(flags | 128 /* ModifierFlags.Abstract */); + modifiers = ts.factory.createModifiersFromModifierFlags(flags | 256 /* ModifierFlags.Abstract */); } - var node = kind === 174 /* SyntaxKind.CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : - kind === 175 /* SyntaxKind.ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : - kind === 168 /* SyntaxKind.MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(modifiers, parameters, /*body*/ undefined) : - kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(modifiers, parameters, returnTypeNode) : - kind === 317 /* SyntaxKind.JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : - kind === 179 /* SyntaxKind.FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 180 /* SyntaxKind.ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 213 /* SyntaxKind.FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : - kind === 214 /* SyntaxKind.ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : + var node = kind === 176 /* SyntaxKind.CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : + kind === 177 /* SyntaxKind.ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : + kind === 170 /* SyntaxKind.MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : + kind === 171 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 173 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(modifiers, parameters, /*body*/ undefined) : + kind === 174 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 175 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 178 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(modifiers, parameters, returnTypeNode) : + kind === 320 /* SyntaxKind.JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : + kind === 181 /* SyntaxKind.FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 182 /* SyntaxKind.ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 259 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 215 /* SyntaxKind.FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : + kind === 216 /* SyntaxKind.ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); if (typeArguments) { node.typeArguments = ts.factory.createNodeArray(typeArguments); @@ -54189,9 +54629,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 164 /* SyntaxKind.Parameter */); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 166 /* SyntaxKind.Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 340 /* SyntaxKind.JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 343 /* SyntaxKind.JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -54203,7 +54643,7 @@ var ts; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 79 /* SyntaxKind.Identifier */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216 /* EmitFlags.NoAsciiEscaping */) : - parameterDeclaration.name.kind === 161 /* SyntaxKind.QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* EmitFlags.NoAsciiEscaping */) : + parameterDeclaration.name.kind === 163 /* SyntaxKind.QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* EmitFlags.NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); @@ -54214,22 +54654,15 @@ var ts; context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { - return elideInitializerAndPropertyRenamingAndSetEmitFlags(node); - function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { trackComputedName(node.expression, context.enclosingDeclaration, context); } - var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags); + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); if (ts.isBindingElement(visited)) { - if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) { - visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, - /* propertyName*/ undefined, visited.propertyName, - /*initializer*/ undefined); - } - else { - visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, - /*initializer*/ undefined); - } + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, + /*initializer*/ undefined); } if (!ts.nodeIsSynthesized(visited)) { visited = ts.factory.cloneNode(visited); @@ -54374,11 +54807,11 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context, overrideImportMode) { var _a; - var file = ts.getDeclarationOfKind(symbol, 305 /* SyntaxKind.SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 308 /* SyntaxKind.SourceFile */); if (!file) { var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); if (equivalentFileSymbol) { - file = ts.getDeclarationOfKind(equivalentFileSymbol, 305 /* SyntaxKind.SourceFile */); + file = ts.getDeclarationOfKind(equivalentFileSymbol, 308 /* SyntaxKind.SourceFile */); } } if (file && file.moduleName !== undefined) { @@ -54846,17 +55279,17 @@ var ts; return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed; function visitExistingNodeTreeSymbols(node) { // We don't _actually_ support jsdoc namepath types, emit `any` instead - if (ts.isJSDocAllType(node) || node.kind === 319 /* SyntaxKind.JSDocNamepathType */) { - return ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */); + if (ts.isJSDocAllType(node) || node.kind === 322 /* SyntaxKind.JSDocNamepathType */) { + return ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */); } if (ts.isJSDocUnknownType(node)) { - return ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */); + return ts.factory.createKeywordTypeNode(157 /* SyntaxKind.UnknownKeyword */); } if (ts.isJSDocNullableType(node)) { return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createLiteralTypeNode(ts.factory.createNull())]); } if (ts.isJSDocOptionalType(node)) { - return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createKeywordTypeNode(153 /* SyntaxKind.UndefinedKeyword */)]); + return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UndefinedKeyword */)]); } if (ts.isJSDocNonNullableType(node)) { return ts.visitNode(node.type, visitExistingNodeTreeSymbols); @@ -54870,11 +55303,11 @@ var ts; var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText); var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined; return ts.factory.createPropertySignature( - /*modifiers*/ undefined, name, t.isBracketed || t.typeExpression && ts.isJSDocOptionalType(t.typeExpression.type) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, overrideTypeNode || (t.typeExpression && ts.visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols)) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); + /*modifiers*/ undefined, name, t.isBracketed || t.typeExpression && ts.isJSDocOptionalType(t.typeExpression.type) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, overrideTypeNode || (t.typeExpression && ts.visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols)) || ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */)); })); } if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") { - return ts.setOriginalNode(ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */), node); + return ts.setOriginalNode(ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */), node); } if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature( @@ -54889,12 +55322,12 @@ var ts; return ts.factory.createConstructorTypeNode( /*modifiers*/ undefined, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); + /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */)); } else { return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration( /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); + /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */)); } } if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(node, 788968 /* SymbolFlags.Type */, /*ignoreErrors*/ true))) { @@ -54962,8 +55395,8 @@ var ts; } } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { - var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 169 /* SyntaxKind.MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 171 /* SyntaxKind.MethodDeclaration */, /*useAcessors*/ true); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 170 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -55087,7 +55520,7 @@ var ts; // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it var indices = ts.indicesOf(statements); var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); }); - if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) { + if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return ts.canHaveExportModifier(statements[i]); })) { for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) { var index_1 = associatedIndices_1[_i]; statements[index_1] = addExportModifier(statements[index_1]); @@ -55121,15 +55554,6 @@ var ts; } return statements; } - function canHaveExportModifier(node) { - return ts.isEnumDeclaration(node) || - ts.isVariableStatement(node) || - ts.isFunctionDeclaration(node) || - ts.isClassDeclaration(node) || - (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) || - ts.isInterfaceDeclaration(node) || - isTypeDeclaration(node); - } function addExportModifier(node) { var flags = (ts.getEffectiveModifierFlags(node) | 1 /* ModifierFlags.Export */) & ~2 /* ModifierFlags.Ambient */; return ts.factory.updateModifiers(node, flags); @@ -55201,7 +55625,7 @@ var ts; if (needsPostExportDefault || needsExportDeclaration) { isPrivate = true; } - var modifierFlags = (!isPrivate ? 1 /* ModifierFlags.Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* ModifierFlags.Default */ : 0); + var modifierFlags = (!isPrivate ? 1 /* ModifierFlags.Export */ : 0) | (isDefault && !needsPostExportDefault ? 1024 /* ModifierFlags.Default */ : 0); var isConstMergedWithNS = symbol.flags & 1536 /* SymbolFlags.Module */ && symbol.flags & (2 /* SymbolFlags.BlockScopedVariable */ | 1 /* SymbolFlags.FunctionScopedVariable */ | 4 /* SymbolFlags.Property */) && symbol.escapedName !== "export=" /* InternalSymbolName.ExportEquals */; @@ -55218,6 +55642,7 @@ var ts; && symbol.escapedName !== "export=" /* InternalSymbolName.ExportEquals */ && !(symbol.flags & 4194304 /* SymbolFlags.Prototype */) && !(symbol.flags & 32 /* SymbolFlags.Class */) + && !(symbol.flags & 8192 /* SymbolFlags.Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { if (propertyAsAlias) { var createdExport = serializeMaybeAliasAssignment(symbol); @@ -55375,7 +55800,7 @@ var ts; (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* ModifierFlags.Export */ && enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && - canHaveExportModifier(node)) { + ts.canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* ModifierFlags.Export */; } @@ -55385,8 +55810,8 @@ var ts; // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= 2 /* ModifierFlags.Ambient */; } - if ((additionalModifierFlags & 512 /* ModifierFlags.Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) { - newModifierFlags |= 512 /* ModifierFlags.Default */; + if ((additionalModifierFlags & 1024 /* ModifierFlags.Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) { + newModifierFlags |= 1024 /* ModifierFlags.Default */; } if (newModifierFlags) { node = ts.factory.updateModifiers(node, newModifierFlags | ts.getEffectiveModifierFlags(node)); @@ -55420,8 +55845,8 @@ var ts; var baseTypes = getBaseTypes(interfaceType); var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined; var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); }); - var callSignatures = serializeSignatures(0 /* SignatureKind.Call */, interfaceType, baseType, 174 /* SyntaxKind.CallSignature */); - var constructSignatures = serializeSignatures(1 /* SignatureKind.Construct */, interfaceType, baseType, 175 /* SyntaxKind.ConstructSignature */); + var callSignatures = serializeSignatures(0 /* SignatureKind.Call */, interfaceType, baseType, 176 /* SyntaxKind.CallSignature */); + var constructSignatures = serializeSignatures(1 /* SignatureKind.Construct */, interfaceType, baseType, 177 /* SyntaxKind.ConstructSignature */); var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* SymbolFlags.Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( @@ -55431,7 +55856,7 @@ var ts; return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { - return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* SymbolFlags.Value */); }); + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(getAllSymbolFlags(resolveSymbol(m)) & 111551 /* SymbolFlags.Value */); }); } function serializeModule(symbol, symbolName, modifierFlags) { var members = getNamespaceMembersForSerialization(symbol); @@ -55486,7 +55911,7 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 256 /* SyntaxKind.FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); + var decl = signatureToSignatureDeclarationHelper(sig, 259 /* SyntaxKind.FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); addResult(ts.setTextRange(decl, getSignatureTextRangeLocation(sig)), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports @@ -55644,7 +56069,7 @@ var ts; !ts.some(getSignaturesOfType(staticType, 1 /* SignatureKind.Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? [ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : - serializeSignatures(1 /* SignatureKind.Construct */, staticType, staticBaseType, 171 /* SyntaxKind.Constructor */); + serializeSignatures(1 /* SignatureKind.Construct */, staticType, staticBaseType, 173 /* SyntaxKind.Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( @@ -55693,8 +56118,8 @@ var ts; var targetName = getInternalSymbolName(target, verbatimTargetName); includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first switch (node.kind) { - case 203 /* SyntaxKind.BindingElement */: - if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 254 /* SyntaxKind.VariableDeclaration */) { + case 205 /* SyntaxKind.BindingElement */: + if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 257 /* SyntaxKind.VariableDeclaration */) { // const { SomeClass } = require('./lib'); var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; @@ -55707,13 +56132,13 @@ var ts; // We don't know how to serialize this (nested?) binding element ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); break; - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 221 /* SyntaxKind.BinaryExpression */) { + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 223 /* SyntaxKind.BinaryExpression */) { // module.exports = { SomeClass } serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), targetName); } break; - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: // commonjs require: const x = require('y') if (ts.isPropertyAccessExpression(node.initializer)) { // const x = require('y').z @@ -55731,7 +56156,7 @@ var ts; break; } // else fall through and treat commonjs require just like import= - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: // This _specifically_ only exists to handle json declarations - where we make aliases, but since // we emit no declarations for the json document, must not refer to it in the declarations if (target.escapedName === "export=" /* InternalSymbolName.ExportEquals */ && ts.some(target.declarations, ts.isJsonSourceFile)) { @@ -55747,13 +56172,13 @@ var ts; ? symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false) : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* ModifierFlags.None */); break; - case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 267 /* SyntaxKind.NamespaceExportDeclaration */: // export as namespace foo // TODO: Not part of a file's local or export symbol tables // Is bound into file.symbol.globalExports instead, which we don't currently traverse addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* ModifierFlags.None */); break; - case 267 /* SyntaxKind.ImportClause */: + case 270 /* SyntaxKind.ImportClause */: addResult(ts.factory.createImportDeclaration( /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned @@ -55762,17 +56187,17 @@ var ts; ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context)), /*assertClause*/ undefined), 0 /* ModifierFlags.None */); break; - case 268 /* SyntaxKind.NamespaceImport */: + case 271 /* SyntaxKind.NamespaceImport */: addResult(ts.factory.createImportDeclaration( /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)), /*assertClause*/ undefined), 0 /* ModifierFlags.None */); break; - case 274 /* SyntaxKind.NamespaceExport */: + case 277 /* SyntaxKind.NamespaceExport */: addResult(ts.factory.createExportDeclaration( /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* ModifierFlags.None */); break; - case 270 /* SyntaxKind.ImportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: addResult(ts.factory.createImportDeclaration( /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ false, @@ -55782,7 +56207,7 @@ var ts; ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context)), /*assertClause*/ undefined), 0 /* ModifierFlags.None */); break; - case 275 /* SyntaxKind.ExportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, // which we must exactly preserve var specifier = node.parent.parent.moduleSpecifier; @@ -55790,12 +56215,12 @@ var ts; // another file serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined); break; - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: serializeMaybeAliasAssignment(symbol); break; - case 221 /* SyntaxKind.BinaryExpression */: - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 223 /* SyntaxKind.BinaryExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: // Could be best encoded as though an export specifier or as though an export assignment // If name is default or export=, do an export assignment // Otherwise do an export specifier @@ -55939,7 +56364,7 @@ var ts; && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { return []; } - var flag = (modifierFlags & ~256 /* ModifierFlags.Async */) | (isStatic ? 32 /* ModifierFlags.Static */ : 0); + var flag = (modifierFlags & ~512 /* ModifierFlags.Async */) | (isStatic ? 32 /* ModifierFlags.Static */ : 0); var name = getPropertyNameNodeForSymbol(p, context); var firstPropertyLikeDecl = (_a = p.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); if (p.flags & 98304 /* SymbolFlags.Accessor */ && useAccessors) { @@ -55961,7 +56386,7 @@ var ts; // This is an else/if as accessors and properties can't merge in TS, but might in JS // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* SymbolFlags.Property */ | 3 /* SymbolFlags.Variable */ | 98304 /* SymbolFlags.Accessor */)) { - return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getWriteTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); @@ -56151,7 +56576,7 @@ var ts; if (flags === void 0) { flags = 16384 /* TypeFormatFlags.UseAliasDefinedOutsideCurrentScope */; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { - var predicate = ts.factory.createTypePredicateNode(typePredicate.kind === 2 /* TypePredicateKind.AssertsThis */ || typePredicate.kind === 3 /* TypePredicateKind.AssertsIdentifier */ ? ts.factory.createToken(128 /* SyntaxKind.AssertsKeyword */) : undefined, typePredicate.kind === 1 /* TypePredicateKind.Identifier */ || typePredicate.kind === 3 /* TypePredicateKind.AssertsIdentifier */ ? ts.factory.createIdentifier(typePredicate.parameterName) : ts.factory.createThisTypeNode(), typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* NodeBuilderFlags.IgnoreErrors */ | 512 /* NodeBuilderFlags.WriteTypeParametersInQualifiedName */) // TODO: GH#18217 + var predicate = ts.factory.createTypePredicateNode(typePredicate.kind === 2 /* TypePredicateKind.AssertsThis */ || typePredicate.kind === 3 /* TypePredicateKind.AssertsIdentifier */ ? ts.factory.createToken(129 /* SyntaxKind.AssertsKeyword */) : undefined, typePredicate.kind === 1 /* TypePredicateKind.Identifier */ || typePredicate.kind === 3 /* TypePredicateKind.AssertsIdentifier */ ? ts.factory.createIdentifier(typePredicate.parameterName) : ts.factory.createThisTypeNode(), typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* NodeBuilderFlags.IgnoreErrors */ | 512 /* NodeBuilderFlags.WriteTypeParametersInQualifiedName */) // TODO: GH#18217 ); var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); @@ -56198,7 +56623,7 @@ var ts; function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* SymbolFlags.TypeLiteral */ && type.symbol.declarations) { var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent); - if (node.kind === 259 /* SyntaxKind.TypeAliasDeclaration */) { + if (node.kind === 262 /* SyntaxKind.TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -56206,11 +56631,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ && + node.parent.kind === 265 /* SyntaxKind.ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 305 /* SyntaxKind.SourceFile */ || ts.isAmbientModule(location); + return location.kind === 308 /* SyntaxKind.SourceFile */ || ts.isAmbientModule(location); } function getNameOfSymbolFromNameType(symbol, context) { var nameType = getSymbolLinks(symbol).nameType; @@ -56269,17 +56694,17 @@ var ts; if (!declaration) { declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway } - if (declaration.parent && declaration.parent.kind === 254 /* SyntaxKind.VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 257 /* SyntaxKind.VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 226 /* SyntaxKind.ClassExpression */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 228 /* SyntaxKind.ClassExpression */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: if (context && !context.encounteredError && !(context.flags & 131072 /* NodeBuilderFlags.AllowAnonymousIdentifier */)) { context.encounteredError = true; } - return declaration.kind === 226 /* SyntaxKind.ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 228 /* SyntaxKind.ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var name = getNameOfSymbolFromNameType(symbol, context); @@ -56296,28 +56721,28 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 339 /* SyntaxKind.JSDocEnumTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: return isDeclarationVisible(node.parent.parent); - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 261 /* SyntaxKind.ModuleDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -56325,55 +56750,55 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */) && - !(node.kind !== 265 /* SyntaxKind.ImportEqualsDeclaration */ && parent.kind !== 305 /* SyntaxKind.SourceFile */ && parent.flags & 16777216 /* NodeFlags.Ambient */)) { + !(node.kind !== 268 /* SyntaxKind.ImportEqualsDeclaration */ && parent.kind !== 308 /* SyntaxKind.SourceFile */ && parent.flags & 16777216 /* NodeFlags.Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: if (ts.hasEffectiveModifier(node, 8 /* ModifierFlags.Private */ | 16 /* ModifierFlags.Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 171 /* SyntaxKind.Constructor */: - case 175 /* SyntaxKind.ConstructSignature */: - case 174 /* SyntaxKind.CallSignature */: - case 176 /* SyntaxKind.IndexSignature */: - case 164 /* SyntaxKind.Parameter */: - case 262 /* SyntaxKind.ModuleBlock */: - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 182 /* SyntaxKind.TypeLiteral */: - case 178 /* SyntaxKind.TypeReference */: - case 183 /* SyntaxKind.ArrayType */: - case 184 /* SyntaxKind.TupleType */: - case 187 /* SyntaxKind.UnionType */: - case 188 /* SyntaxKind.IntersectionType */: - case 191 /* SyntaxKind.ParenthesizedType */: - case 197 /* SyntaxKind.NamedTupleMember */: + case 173 /* SyntaxKind.Constructor */: + case 177 /* SyntaxKind.ConstructSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 178 /* SyntaxKind.IndexSignature */: + case 166 /* SyntaxKind.Parameter */: + case 265 /* SyntaxKind.ModuleBlock */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: + case 184 /* SyntaxKind.TypeLiteral */: + case 180 /* SyntaxKind.TypeReference */: + case 185 /* SyntaxKind.ArrayType */: + case 186 /* SyntaxKind.TupleType */: + case 189 /* SyntaxKind.UnionType */: + case 190 /* SyntaxKind.IntersectionType */: + case 193 /* SyntaxKind.ParenthesizedType */: + case 199 /* SyntaxKind.NamedTupleMember */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 267 /* SyntaxKind.ImportClause */: - case 268 /* SyntaxKind.NamespaceImport */: - case 270 /* SyntaxKind.ImportSpecifier */: + case 270 /* SyntaxKind.ImportClause */: + case 271 /* SyntaxKind.NamespaceImport */: + case 273 /* SyntaxKind.ImportSpecifier */: return false; // Type parameters are always visible - case 163 /* SyntaxKind.TypeParameter */: + case 165 /* SyntaxKind.TypeParameter */: // Source file and namespace export are always visible // falls through - case 305 /* SyntaxKind.SourceFile */: - case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 308 /* SyntaxKind.SourceFile */: + case 267 /* SyntaxKind.NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: return false; default: return false; @@ -56382,10 +56807,10 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 271 /* SyntaxKind.ExportAssignment */) { + if (node.parent && node.parent.kind === 274 /* SyntaxKind.ExportAssignment */) { exportSymbol = resolveName(node, node.escapedText, 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */ | 2097152 /* SymbolFlags.Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 275 /* SyntaxKind.ExportSpecifier */) { + else if (node.parent.kind === 278 /* SyntaxKind.ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */ | 2097152 /* SymbolFlags.Alias */); } var result; @@ -56492,12 +56917,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: - case 255 /* SyntaxKind.VariableDeclarationList */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 269 /* SyntaxKind.NamedImports */: - case 268 /* SyntaxKind.NamespaceImport */: - case 267 /* SyntaxKind.ImportClause */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 258 /* SyntaxKind.VariableDeclarationList */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 272 /* SyntaxKind.NamedImports */: + case 271 /* SyntaxKind.NamespaceImport */: + case 270 /* SyntaxKind.ImportClause */: return false; default: return true; @@ -56627,23 +57052,23 @@ var ts; function getParentElementAccess(node) { var ancestor = node.parent.parent; switch (ancestor.kind) { - case 203 /* SyntaxKind.BindingElement */: - case 296 /* SyntaxKind.PropertyAssignment */: + case 205 /* SyntaxKind.BindingElement */: + case 299 /* SyntaxKind.PropertyAssignment */: return getSyntheticElementAccess(ancestor); - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return getSyntheticElementAccess(node.parent); - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return ancestor.initializer; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return ancestor.right; } } function getDestructuringPropertyName(node) { var parent = node.parent; - if (node.kind === 203 /* SyntaxKind.BindingElement */ && parent.kind === 201 /* SyntaxKind.ObjectBindingPattern */) { + if (node.kind === 205 /* SyntaxKind.BindingElement */ && parent.kind === 203 /* SyntaxKind.ObjectBindingPattern */) { return getLiteralPropertyNameText(node.propertyName || node.name); } - if (node.kind === 296 /* SyntaxKind.PropertyAssignment */ || node.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */) { + if (node.kind === 299 /* SyntaxKind.PropertyAssignment */ || node.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */) { return getLiteralPropertyNameText(node.name); } return "" + parent.elements.indexOf(node); @@ -56673,7 +57098,7 @@ var ts; parentType = getTypeWithFacts(parentType, 524288 /* TypeFacts.NEUndefined */); } var type; - if (pattern.kind === 201 /* SyntaxKind.ObjectBindingPattern */) { + if (pattern.kind === 203 /* SyntaxKind.ObjectBindingPattern */) { if (declaration.dotDotDotToken) { parentType = getReducedType(parentType); if (parentType.flags & 2 /* TypeFlags.Unknown */ || !isValidSpreadType(parentType)) { @@ -56744,7 +57169,7 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node, /*excludeJSDocTypeAssertions*/ true); - return expr.kind === 204 /* SyntaxKind.ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 206 /* SyntaxKind.ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, isProperty, isOptional) { if (isProperty === void 0) { isProperty = false; } @@ -56755,11 +57180,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality, checkMode) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 243 /* SyntaxKind.ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 246 /* SyntaxKind.ForInStatement */) { var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression, /*checkMode*/ checkMode))); return indexType.flags & (262144 /* TypeFlags.TypeParameter */ | 4194304 /* TypeFlags.Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 244 /* SyntaxKind.ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 247 /* SyntaxKind.ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -56770,7 +57195,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } - var isProperty = ts.isPropertyDeclaration(declaration) || ts.isPropertySignature(declaration); + var isProperty = ts.isPropertyDeclaration(declaration) && !ts.hasAccessorModifier(declaration) || ts.isPropertySignature(declaration); var isOptional = includeOptionality && (isProperty && !!declaration.questionToken || ts.isParameter(declaration) && (!!declaration.questionToken || isJSDocOptionalParameter(declaration)) || isOptionalJSDocPropertyLikeTag(declaration)); @@ -56797,8 +57222,8 @@ var ts; if (ts.isParameter(declaration)) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 173 /* SyntaxKind.SetAccessor */ && hasBindableName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 172 /* SyntaxKind.GetAccessor */); + if (func.kind === 175 /* SyntaxKind.SetAccessor */ && hasBindableName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 174 /* SyntaxKind.GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -56810,11 +57235,9 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } - if (ts.isInJSFile(declaration)) { - var type_1 = getParameterTypeOfTypeTag(func, declaration); - if (type_1) - return type_1; - } + var parameterTypeOfTypeTag = getParameterTypeOfTypeTag(func, declaration); + if (parameterTypeOfTypeTag) + return parameterTypeOfTypeTag; // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* InternalSymbolName.This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { @@ -56875,7 +57298,7 @@ var ts; links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { return ts.isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && - (declaration.left.kind !== 207 /* SyntaxKind.ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + (declaration.left.kind !== 209 /* SyntaxKind.ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration); }); } @@ -56897,11 +57320,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false); - if (container && (container.kind === 171 /* SyntaxKind.Constructor */ || isJSConstructor(container))) { + if (container && (container.kind === 173 /* SyntaxKind.Constructor */ || isJSConstructor(container))) { return container; } } - ; } /** Create a synthetic property access flow node after the last statement of the file */ function getFlowTypeFromCommonJSExport(symbol) { @@ -57194,9 +57616,9 @@ var ts; var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. // Function expressions that are assigned to the prototype count as methods. - return thisContainer.kind === 171 /* SyntaxKind.Constructor */ || - thisContainer.kind === 256 /* SyntaxKind.FunctionDeclaration */ || - (thisContainer.kind === 213 /* SyntaxKind.FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 173 /* SyntaxKind.Constructor */ || + thisContainer.kind === 259 /* SyntaxKind.FunctionDeclaration */ || + (thisContainer.kind === 215 /* SyntaxKind.FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -57224,7 +57646,11 @@ var ts; if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAny(element, anyType); } - return anyType; + // When we're including the pattern in the type (an indication we're obtaining a contextual type), we + // use a non-inferrable any type. Inference will never directly infer this type, but it is possible + // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases, + // widening of the binding pattern type substitutes a regular any for the non-inferrable any. + return includePatternInType ? nonInferrableAnyType : anyType; } // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { @@ -57262,7 +57688,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var restElement = lastElement && lastElement.kind === 203 /* SyntaxKind.BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; + var restElement = lastElement && lastElement.kind === 205 /* SyntaxKind.BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; if (elements.length === 0 || elements.length === 1 && restElement) { return languageVersion >= 2 /* ScriptTarget.ES2015 */ ? createIterableType(anyType) : anyArrayType; } @@ -57287,7 +57713,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 201 /* SyntaxKind.ObjectBindingPattern */ + return pattern.kind === 203 /* SyntaxKind.ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -57335,7 +57761,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 164 /* SyntaxKind.Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 166 /* SyntaxKind.Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(node) { @@ -57390,9 +57816,9 @@ var ts; if (typeNode === undefined) { return useUnknownInCatchVariables ? unknownType : anyType; } - var type_2 = getTypeOfNode(typeNode); + var type_1 = getTypeOfNode(typeNode); // an errorType will make `checkTryStatement` issue an error - return isTypeAny(type_2) || type_2 === unknownType ? type_2 : errorType; + return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType; } // Handle export default expressions if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) { @@ -57415,7 +57841,7 @@ var ts; return reportCircularityError(symbol); } var type; - if (declaration.kind === 271 /* SyntaxKind.ExportAssignment */) { + if (declaration.kind === 274 /* SyntaxKind.ExportAssignment */) { type = widenTypeForVariableLikeDeclaration(tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionCached(declaration.expression), declaration); } else if (ts.isBinaryExpression(declaration) || @@ -57483,13 +57909,17 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 172 /* SyntaxKind.GetAccessor */) { - var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); - return getterTypeAnnotation; - } - else { - var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation; + switch (accessor.kind) { + case 174 /* SyntaxKind.GetAccessor */: + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation; + case 175 /* SyntaxKind.SetAccessor */: + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation; + case 169 /* SyntaxKind.PropertyDeclaration */: + ts.Debug.assert(ts.hasAccessorModifier(accessor)); + var accessorTypeAnnotation = ts.getEffectiveTypeAnnotationNode(accessor); + return accessorTypeAnnotation; } } return undefined; @@ -57511,14 +57941,17 @@ var ts; if (!pushTypeResolution(symbol, 0 /* TypeSystemPropertyName.Type */)) { return errorType; } - var getter = ts.getDeclarationOfKind(symbol, 172 /* SyntaxKind.GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 173 /* SyntaxKind.SetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 174 /* SyntaxKind.GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 175 /* SyntaxKind.SetAccessor */); + var accessor = ts.tryCast(ts.getDeclarationOfKind(symbol, 169 /* SyntaxKind.PropertyDeclaration */), ts.isAutoAccessorPropertyDeclaration); // We try to resolve a getter type annotation, a setter type annotation, or a getter function // body return type inference, in that order. var type = getter && ts.isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || getAnnotatedAccessorType(getter) || getAnnotatedAccessorType(setter) || - getter && getter.body && getReturnTypeFromBody(getter); + getAnnotatedAccessorType(accessor) || + getter && getter.body && getReturnTypeFromBody(getter) || + accessor && accessor.initializer && getWidenedTypeForVariableLikeDeclaration(accessor, /*includeOptionality*/ true); if (!type) { if (setter && !isPrivateWithinAmbient(setter)) { errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); @@ -57526,6 +57959,9 @@ var ts; else if (getter && !isPrivateWithinAmbient(getter)) { errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } + else if (accessor && !isPrivateWithinAmbient(accessor)) { + errorOrSuggestion(noImplicitAny, accessor, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), "any"); + } type = anyType; } if (!popTypeResolution()) { @@ -57535,6 +57971,9 @@ var ts; else if (getAnnotatedAccessorTypeNode(setter)) { error(setter, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); } + else if (getAnnotatedAccessorTypeNode(accessor)) { + error(setter, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } else if (getter && noImplicitAny) { error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } @@ -57545,12 +57984,13 @@ var ts; return links.type; } function getWriteTypeOfAccessors(symbol) { + var _a; var links = getSymbolLinks(symbol); if (!links.writeType) { if (!pushTypeResolution(symbol, 8 /* TypeSystemPropertyName.WriteType */)) { return errorType; } - var setter = ts.getDeclarationOfKind(symbol, 173 /* SyntaxKind.SetAccessor */); + var setter = (_a = ts.getDeclarationOfKind(symbol, 175 /* SyntaxKind.SetAccessor */)) !== null && _a !== void 0 ? _a : ts.tryCast(ts.getDeclarationOfKind(symbol, 169 /* SyntaxKind.PropertyDeclaration */), ts.isAutoAccessorPropertyDeclaration); var writeType = getAnnotatedAccessorType(setter); if (!popTypeResolution()) { if (getAnnotatedAccessorTypeNode(setter)) { @@ -57590,9 +58030,9 @@ var ts; if (symbol.flags & 1536 /* SymbolFlags.Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration && (declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || + else if (declaration && (declaration.kind === 223 /* SyntaxKind.BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 221 /* SyntaxKind.BinaryExpression */)) { + declaration.parent.kind === 223 /* SyntaxKind.BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* SymbolFlags.ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -57602,11 +58042,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* InternalSymbolName.ExportEquals */)); - var type_3 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_3; + return type_2; } } var type = createObjectType(16 /* ObjectFlags.Anonymous */, symbol); @@ -57636,7 +58076,7 @@ var ts; links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType - : targetSymbol.flags & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) + : getAllSymbolFlags(targetSymbol) & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; @@ -57657,7 +58097,7 @@ var ts; return errorType; } // Check if variable has initializer that circularly references the variable itself - if (noImplicitAny && (declaration.kind !== 164 /* SyntaxKind.Parameter */ || declaration.initializer)) { + if (noImplicitAny && (declaration.kind !== 166 /* SyntaxKind.Parameter */ || declaration.initializer)) { error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); } // Circularities could also result from parameters in function expressions that end up @@ -57789,46 +58229,46 @@ var ts; return undefined; } switch (node.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 168 /* SyntaxKind.MethodSignature */: - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 344 /* SyntaxKind.JSDocTemplateTag */: - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 339 /* SyntaxKind.JSDocEnumTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 195 /* SyntaxKind.MappedType */: - case 189 /* SyntaxKind.ConditionalType */: { + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 170 /* SyntaxKind.MethodSignature */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: + case 320 /* SyntaxKind.JSDocFunctionType */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 347 /* SyntaxKind.JSDocTemplateTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 197 /* SyntaxKind.MappedType */: + case 191 /* SyntaxKind.ConditionalType */: { var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 195 /* SyntaxKind.MappedType */) { + if (node.kind === 197 /* SyntaxKind.MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 189 /* SyntaxKind.ConditionalType */) { + else if (node.kind === 191 /* SyntaxKind.ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 257 /* SyntaxKind.ClassDeclaration */ || node.kind === 226 /* SyntaxKind.ClassExpression */ || node.kind === 258 /* SyntaxKind.InterfaceDeclaration */ || isJSConstructor(node)) && + (node.kind === 260 /* SyntaxKind.ClassDeclaration */ || node.kind === 228 /* SyntaxKind.ClassExpression */ || node.kind === 261 /* SyntaxKind.InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } - case 340 /* SyntaxKind.JSDocParameterTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: var paramSymbol = ts.getParameterSymbolFromJSDoc(node); if (paramSymbol) { node = paramSymbol.valueDeclaration; } break; - case 320 /* SyntaxKind.JSDoc */: { + case 323 /* SyntaxKind.JSDoc */: { var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); return node.tags ? appendTypeParameters(outerTypeParameters, ts.flatMap(node.tags, function (t) { return ts.isJSDocTemplateTag(t) ? t.typeParameters : undefined; })) @@ -57839,7 +58279,7 @@ var ts; } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* SymbolFlags.Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 258 /* SyntaxKind.InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* SymbolFlags.Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 261 /* SyntaxKind.InterfaceDeclaration */); ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } @@ -57852,9 +58292,9 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 258 /* SyntaxKind.InterfaceDeclaration */ || - node.kind === 257 /* SyntaxKind.ClassDeclaration */ || - node.kind === 226 /* SyntaxKind.ClassExpression */ || + if (node.kind === 261 /* SyntaxKind.InterfaceDeclaration */ || + node.kind === 260 /* SyntaxKind.ClassDeclaration */ || + node.kind === 228 /* SyntaxKind.ClassExpression */ || isJSConstructor(node) || ts.isTypeAlias(node)) { var declaration = node; @@ -58006,7 +58446,7 @@ var ts; if (!popTypeResolution() && type.symbol.declarations) { for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 257 /* SyntaxKind.ClassDeclaration */ || declaration.kind === 258 /* SyntaxKind.InterfaceDeclaration */) { + if (declaration.kind === 260 /* SyntaxKind.ClassDeclaration */ || declaration.kind === 261 /* SyntaxKind.InterfaceDeclaration */) { reportCircularBaseType(declaration, type); } } @@ -58102,7 +58542,7 @@ var ts; if (type.symbol.declarations) { for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 258 /* SyntaxKind.InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 261 /* SyntaxKind.InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getReducedType(getTypeFromTypeNode(node)); @@ -58142,7 +58582,7 @@ var ts; } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 258 /* SyntaxKind.InterfaceDeclaration */) { + if (declaration.kind === 261 /* SyntaxKind.InterfaceDeclaration */) { if (declaration.flags & 128 /* NodeFlags.ContainsThis */) { return false; } @@ -58221,7 +58661,7 @@ var ts; } else { type = errorType; - if (declaration.kind === 339 /* SyntaxKind.JSDocEnumTag */) { + if (declaration.kind === 342 /* SyntaxKind.JSDocEnumTag */) { error(declaration.typeExpression.type, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } else { @@ -58236,7 +58676,7 @@ var ts; if (ts.isStringLiteralLike(expr)) { return true; } - else if (expr.kind === 221 /* SyntaxKind.BinaryExpression */) { + else if (expr.kind === 223 /* SyntaxKind.BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -58251,12 +58691,12 @@ var ts; case 8 /* SyntaxKind.NumericLiteral */: case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: return true; - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: return expr.operator === 40 /* SyntaxKind.MinusToken */ && expr.operand.kind === 8 /* SyntaxKind.NumericLiteral */; case 79 /* SyntaxKind.Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -58271,7 +58711,7 @@ var ts; if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 260 /* SyntaxKind.EnumDeclaration */) { + if (declaration.kind === 263 /* SyntaxKind.EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (member.initializer && ts.isStringLiteralLike(member.initializer)) { @@ -58300,7 +58740,7 @@ var ts; if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 260 /* SyntaxKind.EnumDeclaration */) { + if (declaration.kind === 263 /* SyntaxKind.EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; var value = getEnumMemberValue(member); @@ -58373,22 +58813,22 @@ var ts; */ function isThislessType(node) { switch (node.kind) { - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 150 /* SyntaxKind.StringKeyword */: - case 147 /* SyntaxKind.NumberKeyword */: - case 158 /* SyntaxKind.BigIntKeyword */: - case 133 /* SyntaxKind.BooleanKeyword */: - case 151 /* SyntaxKind.SymbolKeyword */: - case 148 /* SyntaxKind.ObjectKeyword */: + case 131 /* SyntaxKind.AnyKeyword */: + case 157 /* SyntaxKind.UnknownKeyword */: + case 152 /* SyntaxKind.StringKeyword */: + case 148 /* SyntaxKind.NumberKeyword */: + case 160 /* SyntaxKind.BigIntKeyword */: + case 134 /* SyntaxKind.BooleanKeyword */: + case 153 /* SyntaxKind.SymbolKeyword */: + case 149 /* SyntaxKind.ObjectKeyword */: case 114 /* SyntaxKind.VoidKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: - case 196 /* SyntaxKind.LiteralType */: + case 155 /* SyntaxKind.UndefinedKeyword */: + case 144 /* SyntaxKind.NeverKeyword */: + case 198 /* SyntaxKind.LiteralType */: return true; - case 183 /* SyntaxKind.ArrayType */: + case 185 /* SyntaxKind.ArrayType */: return isThislessType(node.elementType); - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -58414,7 +58854,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 171 /* SyntaxKind.Constructor */ || (!!returnType && isThislessType(returnType))) && + return (node.kind === 173 /* SyntaxKind.Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -58430,14 +58870,14 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -58648,8 +59088,10 @@ var ts; if (members) { for (var _b = 0, members_5 = members; _b < members_5.length; _b++) { var member = members_5[_b]; - if (isStatic_1 === ts.hasStaticModifier(member) && hasLateBindableName(member)) { - lateBindMember(symbol, earlySymbols, lateSymbols, member); + if (isStatic_1 === ts.hasStaticModifier(member)) { + if (hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } } } } @@ -58664,8 +59106,10 @@ var ts; || ts.isBinaryExpression(member) && isPossiblyAliasedThisProperty(member, assignmentKind) || assignmentKind === 9 /* AssignmentDeclarationKind.ObjectDefinePrototypeProperty */ || assignmentKind === 6 /* AssignmentDeclarationKind.Prototype */; // A straight `Prototype` assignment probably can never have a computed name - if (isStatic_1 === !isInstanceMember && hasLateBindableName(member)) { - lateBindMember(symbol, earlySymbols, lateSymbols, member); + if (isStatic_1 === !isInstanceMember) { + if (hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } } } } @@ -58852,7 +59296,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* SignatureKind.Construct */); var declaration = ts.getClassLikeDeclarationOfSymbol(classType.symbol); - var isAbstract = !!declaration && ts.hasSyntacticModifier(declaration, 128 /* ModifierFlags.Abstract */); + var isAbstract = !!declaration && ts.hasSyntacticModifier(declaration, 256 /* ModifierFlags.Abstract */); if (baseSignatures.length === 0) { return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, isAbstract ? 4 /* SignatureFlags.Abstract */ : 0 /* SignatureFlags.None */)]; } @@ -59325,6 +59769,12 @@ var ts; return mapType(type, getLowerBoundOfKeyType); } if (type.flags & 2097152 /* TypeFlags.Intersection */) { + // Similarly to getTypeFromIntersectionTypeNode, we preserve the special string & {}, number & {}, + // and bigint & {} intersections that are used to prevent subtype reduction in union types. + var types = type.types; + if (types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType) { + return type; + } return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); } return type; @@ -59468,8 +59918,8 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 193 /* SyntaxKind.TypeOperator */ && - constraintDeclaration.operator === 140 /* SyntaxKind.KeyOfKeyword */; + return constraintDeclaration.kind === 195 /* SyntaxKind.TypeOperator */ && + constraintDeclaration.operator === 141 /* SyntaxKind.KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { @@ -59509,7 +59959,20 @@ var ts; return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ && getMappedTypeModifiers(type) & 4 /* MappedTypeModifiers.IncludeOptional */); } function isGenericMappedType(type) { - return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + if (ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) { + var constraint = getConstraintTypeFromMappedType(type); + if (isGenericIndexType(constraint)) { + return true; + } + // A mapped type is generic if the 'as' clause references generic types other than the iteration type. + // To determine this, we substitute the constraint type (that we now know isn't generic) for the iteration + // type and check whether the resulting type is generic. + var nameType = getNameTypeFromMappedType(type); + if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type), constraint)))) { + return true; + } + } + return false; } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -59829,10 +60292,10 @@ var ts; var baseTypes = []; var different = false; for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type_4 = types_7[_i]; - var baseType = getBaseConstraint(type_4); + var type_3 = types_7[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { - if (baseType !== type_4) { + if (baseType !== type_3) { different = true; } baseTypes.push(baseType); @@ -59876,7 +60339,7 @@ var ts; return constraint && getBaseConstraint(constraint); } if (t.flags & 33554432 /* TypeFlags.Substitution */) { - return getBaseConstraint(t.substitute); + return getBaseConstraint(getSubstitutionIntersection(t)); } return t; } @@ -59979,7 +60442,7 @@ var ts; var indexTypes; var isUnion = containingType.flags & 1048576 /* TypeFlags.Union */; // Flags we want to propagate to the result if they exist in all source symbols - var optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */; + var optionalFlag; var syntheticFlag = 4 /* CheckFlags.SyntheticMethod */; var checkFlags = isUnion ? 0 : 8 /* CheckFlags.Readonly */; var mergedInstantiations = false; @@ -59990,11 +60453,14 @@ var ts; var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop) { - if (isUnion) { - optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); - } - else { - optionalFlag &= prop.flags; + if (prop.flags & 106500 /* SymbolFlags.ClassMember */) { + optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : (optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */); + if (isUnion) { + optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); + } + else { + optionalFlag &= prop.flags; + } } if (!singleProp) { singleProp = prop; @@ -60003,7 +60469,7 @@ var ts; var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); // If the symbols are instances of one another with identical types - consider the symbols // equivalent and just use the first one, which thus allows us to avoid eliding private - // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + // members when intersecting a (this-)instantiations of a class with its raw base or another instance if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* Ternary.True */ : 0 /* Ternary.False */; }) === -1 /* Ternary.True */) { // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed @@ -60051,7 +60517,11 @@ var ts; } } } - if (!singleProp || isUnion && (propSet || checkFlags & 48 /* CheckFlags.Partial */) && checkFlags & (1024 /* CheckFlags.ContainsPrivate */ | 512 /* CheckFlags.ContainsProtected */)) { + if (!singleProp || + isUnion && + (propSet || checkFlags & 48 /* CheckFlags.Partial */) && + checkFlags & (1024 /* CheckFlags.ContainsPrivate */ | 512 /* CheckFlags.ContainsProtected */) && + !(propSet && getCommonDeclarationsOfSymbols(ts.arrayFrom(propSet.values())))) { // No property was found, or, in a union, a property has a private or protected declaration in one // constituent, but is missing or has a different declaration in another constituent. return undefined; @@ -60109,7 +60579,7 @@ var ts; propTypes.push(type); } ts.addRange(propTypes, indexTypes); - var result = createSymbol(4 /* SymbolFlags.Property */ | optionalFlag, name, syntheticFlag | checkFlags); + var result = createSymbol(4 /* SymbolFlags.Property */ | (optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : 0), name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && firstValueDeclaration) { result.valueDeclaration = firstValueDeclaration; @@ -60153,6 +60623,33 @@ var ts; } return property; } + function getCommonDeclarationsOfSymbols(symbols) { + var commonDeclarations; + var _loop_14 = function (symbol) { + if (!symbol.declarations) { + return { value: undefined }; + } + if (!commonDeclarations) { + commonDeclarations = new ts.Set(symbol.declarations); + return "continue"; + } + commonDeclarations.forEach(function (declaration) { + if (!ts.contains(symbol.declarations, declaration)) { + commonDeclarations.delete(declaration); + } + }); + if (commonDeclarations.size === 0) { + return { value: undefined }; + } + }; + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var symbol = symbols_3[_i]; + var state_4 = _loop_14(symbol); + if (typeof state_4 === "object") + return state_4.value; + } + return commonDeclarations; + } function getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment) { var property = getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment); // We need to filter out partial properties in union types @@ -60356,10 +60853,10 @@ var ts; function isJSDocOptionalParameter(node) { return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - node.type && node.type.kind === 316 /* SyntaxKind.JSDocOptionalType */ + node.type && node.type.kind === 319 /* SyntaxKind.JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 316 /* SyntaxKind.JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 319 /* SyntaxKind.JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -60392,14 +60889,14 @@ var ts; return false; } function isOptionalPropertyDeclaration(node) { - return ts.isPropertyDeclaration(node) && node.questionToken; + return ts.isPropertyDeclaration(node) && !ts.hasAccessorModifier(node) && node.questionToken; } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 316 /* SyntaxKind.JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 319 /* SyntaxKind.JSDocOptionalType */; } function createTypePredicate(kind, parameterName, parameterIndex, type) { return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -60481,7 +60978,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 196 /* SyntaxKind.LiteralType */) { + if (type && type.kind === 198 /* SyntaxKind.LiteralType */) { flags |= 2 /* SignatureFlags.HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter @@ -60494,24 +60991,24 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 172 /* SyntaxKind.GetAccessor */ || declaration.kind === 173 /* SyntaxKind.SetAccessor */) && + if ((declaration.kind === 174 /* SyntaxKind.GetAccessor */ || declaration.kind === 175 /* SyntaxKind.SetAccessor */) && hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 172 /* SyntaxKind.GetAccessor */ ? 173 /* SyntaxKind.SetAccessor */ : 172 /* SyntaxKind.GetAccessor */; + var otherKind = declaration.kind === 174 /* SyntaxKind.GetAccessor */ ? 175 /* SyntaxKind.SetAccessor */ : 174 /* SyntaxKind.GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 171 /* SyntaxKind.Constructor */ ? + var classType = declaration.kind === 173 /* SyntaxKind.Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { flags |= 1 /* SignatureFlags.HasRestParameter */; } - if (ts.isConstructorTypeNode(declaration) && ts.hasSyntacticModifier(declaration, 128 /* ModifierFlags.Abstract */) || - ts.isConstructorDeclaration(declaration) && ts.hasSyntacticModifier(declaration.parent, 128 /* ModifierFlags.Abstract */)) { + if (ts.isConstructorTypeNode(declaration) && ts.hasSyntacticModifier(declaration, 256 /* ModifierFlags.Abstract */) || + ts.isConstructorDeclaration(declaration) && ts.hasSyntacticModifier(declaration.parent, 256 /* ModifierFlags.Abstract */)) { flags |= 4 /* SignatureFlags.Abstract */; } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, @@ -60590,16 +61087,16 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; - case 167 /* SyntaxKind.PropertyDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - return node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */ + case 169 /* SyntaxKind.PropertyDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + return node.name.kind === 164 /* SyntaxKind.ComputedPropertyName */ && traverse(node.name); - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return traverse(node.expression); - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: return traverse(node.initializer); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -60623,7 +61120,12 @@ var ts; continue; } } - result.push(getSignatureFromDeclaration(decl)); + // If this is a function or method declaration, get the signature from the @type tag for the sake of optional parameters. + // Exclude contextually-typed kinds because we already apply the @type tag to the context, plus applying it here to the initializer would supress checks that the two are compatible. + result.push((!ts.isFunctionExpressionOrArrowFunction(decl) && + !ts.isObjectLiteralMethod(decl) && + getSignatureOfTypeTag(decl)) || + getSignatureFromDeclaration(decl)); } return result; } @@ -60654,7 +61156,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJSFile(signature.declaration)) { + if (!type) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -60671,7 +61173,7 @@ var ts; function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = node.type && getTypeFromTypeNode(node.type); - return parameterName.kind === 192 /* SyntaxKind.ThisType */ ? + return parameterName.kind === 194 /* SyntaxKind.ThisType */ ? createTypePredicate(node.assertsModifier ? 2 /* TypePredicateKind.AssertsThis */ : 0 /* TypePredicateKind.This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) : createTypePredicate(node.assertsModifier ? 3 /* TypePredicateKind.AssertsIdentifier */ : 1 /* TypePredicateKind.Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } @@ -60717,7 +61219,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 171 /* SyntaxKind.Constructor */) { + if (declaration.kind === 173 /* SyntaxKind.Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -60727,12 +61229,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 172 /* SyntaxKind.GetAccessor */ && hasBindableName(declaration)) { + if (declaration.kind === 174 /* SyntaxKind.GetAccessor */ && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 173 /* SyntaxKind.SetAccessor */); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 175 /* SyntaxKind.SetAccessor */); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -60835,7 +61337,7 @@ var ts; if (!signature.isolatedSignatureType) { var kind = (_a = signature.declaration) === null || _a === void 0 ? void 0 : _a.kind; // If declaration is undefined, it is likely to be the signature of the default constructor. - var isConstructor = kind === undefined || kind === 171 /* SyntaxKind.Constructor */ || kind === 175 /* SyntaxKind.ConstructSignature */ || kind === 180 /* SyntaxKind.ConstructorType */; + var isConstructor = kind === undefined || kind === 173 /* SyntaxKind.Constructor */ || kind === 177 /* SyntaxKind.ConstructSignature */ || kind === 182 /* SyntaxKind.ConstructorType */; var type = createObjectType(16 /* ObjectFlags.Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -60862,7 +61364,7 @@ var ts; function getIndexInfosOfIndexSymbol(indexSymbol) { if (indexSymbol.declarations) { var indexInfos_4 = []; - var _loop_14 = function (declaration) { + var _loop_15 = function (declaration) { if (declaration.parameters.length === 1) { var parameter = declaration.parameters[0]; if (parameter.type) { @@ -60876,7 +61378,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_14(declaration); + _loop_15(declaration); } return indexInfos_4; } @@ -60893,14 +61395,14 @@ var ts; var _a; var inferences; if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { - var _loop_15 = function (declaration) { - if (declaration.parent.kind === 190 /* SyntaxKind.InferType */) { + var _loop_16 = function (declaration) { + if (declaration.parent.kind === 192 /* SyntaxKind.InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; - if (grandParent.kind === 178 /* SyntaxKind.TypeReference */ && !omitTypeReferences) { + if (grandParent.kind === 180 /* SyntaxKind.TypeReference */ && !omitTypeReferences) { var typeReference_1 = grandParent; var typeParameters_1 = getTypeParametersForTypeReference(typeReference_1); if (typeParameters_1) { @@ -60927,27 +61429,27 @@ var ts; } // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type // or a named rest tuple element, we infer an 'unknown[]' constraint. - else if (grandParent.kind === 164 /* SyntaxKind.Parameter */ && grandParent.dotDotDotToken || - grandParent.kind === 186 /* SyntaxKind.RestType */ || - grandParent.kind === 197 /* SyntaxKind.NamedTupleMember */ && grandParent.dotDotDotToken) { + else if (grandParent.kind === 166 /* SyntaxKind.Parameter */ && grandParent.dotDotDotToken || + grandParent.kind === 188 /* SyntaxKind.RestType */ || + grandParent.kind === 199 /* SyntaxKind.NamedTupleMember */ && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string' // constraint. - else if (grandParent.kind === 199 /* SyntaxKind.TemplateLiteralTypeSpan */) { + else if (grandParent.kind === 201 /* SyntaxKind.TemplateLiteralTypeSpan */) { inferences = ts.append(inferences, stringType); } // When an 'infer T' declaration is in the constraint position of a mapped type, we infer a 'keyof any' // constraint. - else if (grandParent.kind === 163 /* SyntaxKind.TypeParameter */ && grandParent.parent.kind === 195 /* SyntaxKind.MappedType */) { + else if (grandParent.kind === 165 /* SyntaxKind.TypeParameter */ && grandParent.parent.kind === 197 /* SyntaxKind.MappedType */) { inferences = ts.append(inferences, keyofConstraintType); } // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template // of the check type's mapped type - else if (grandParent.kind === 195 /* SyntaxKind.MappedType */ && grandParent.type && - ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 189 /* SyntaxKind.ConditionalType */ && - grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 195 /* SyntaxKind.MappedType */ && + else if (grandParent.kind === 197 /* SyntaxKind.MappedType */ && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 191 /* SyntaxKind.ConditionalType */ && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 197 /* SyntaxKind.MappedType */ && grandParent.parent.checkType.type) { var checkMappedType_1 = grandParent.parent.checkType; var nodeType = getTypeFromTypeNode(checkMappedType_1.type); @@ -60957,7 +61459,7 @@ var ts; }; for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { var declaration = _b[_i]; - _loop_15(declaration); + _loop_16(declaration); } } return inferences && getIntersectionType(inferences); @@ -60979,7 +61481,7 @@ var ts; if (type.flags & 1 /* TypeFlags.Any */ && !isErrorType(type)) { // Allow errorType to propegate to keep downstream errors suppressed // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was), // use unknown otherwise - type = constraintDeclaration.parent.parent.kind === 195 /* SyntaxKind.MappedType */ ? keyofConstraintType : unknownType; + type = constraintDeclaration.parent.parent.kind === 197 /* SyntaxKind.MappedType */ ? keyofConstraintType : unknownType; } typeParameter.constraint = type; } @@ -60988,7 +61490,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 163 /* SyntaxKind.TypeParameter */); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 165 /* SyntaxKind.TypeParameter */); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getEffectiveContainerForJSDocTemplateTag(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -61074,8 +61576,8 @@ var ts; } var node = type.node; var typeArguments = !node ? ts.emptyArray : - node.kind === 178 /* SyntaxKind.TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : - node.kind === 183 /* SyntaxKind.ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : + node.kind === 180 /* SyntaxKind.TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : + node.kind === 185 /* SyntaxKind.ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) { type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; @@ -61117,7 +61619,7 @@ var ts; return errorType; } } - if (node.kind === 178 /* SyntaxKind.TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { + if (node.kind === 180 /* SyntaxKind.TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { return createDeferredTypeReference(type, node, /*mapper*/ undefined); } // In a type reference, the outer type parameters of the referenced class or interface are automatically @@ -61188,9 +61690,9 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return node.typeName; - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -61205,13 +61707,13 @@ var ts; return symbol.parent ? "".concat(getSymbolPath(symbol.parent), ".").concat(symbol.escapedName) : symbol.escapedName; } function getUnresolvedSymbolForEntityName(name) { - var identifier = name.kind === 161 /* SyntaxKind.QualifiedName */ ? name.right : - name.kind === 206 /* SyntaxKind.PropertyAccessExpression */ ? name.name : + var identifier = name.kind === 163 /* SyntaxKind.QualifiedName */ ? name.right : + name.kind === 208 /* SyntaxKind.PropertyAccessExpression */ ? name.name : name; var text = identifier.escapedText; if (text) { - var parentSymbol = name.kind === 161 /* SyntaxKind.QualifiedName */ ? getUnresolvedSymbolForEntityName(name.left) : - name.kind === 206 /* SyntaxKind.PropertyAccessExpression */ ? getUnresolvedSymbolForEntityName(name.expression) : + var parentSymbol = name.kind === 163 /* SyntaxKind.QualifiedName */ ? getUnresolvedSymbolForEntityName(name.left) : + name.kind === 208 /* SyntaxKind.PropertyAccessExpression */ ? getUnresolvedSymbolForEntityName(name.expression) : undefined; var path = parentSymbol ? "".concat(getSymbolPath(parentSymbol), ".").concat(text) : text; var result = unresolvedSymbols.get(path); @@ -61272,7 +61774,7 @@ var ts; var valueType = getTypeOfSymbol(symbol); var typeType = valueType; if (symbol.valueDeclaration) { - var isImportTypeWithQualifier = node.kind === 200 /* SyntaxKind.ImportType */ && node.qualifier; + var isImportTypeWithQualifier = node.kind === 202 /* SyntaxKind.ImportType */ && node.qualifier; // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL} if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) { typeType = getTypeReferenceType(node, valueType.symbol); @@ -61282,23 +61784,27 @@ var ts; } return links.resolvedJSDocType; } - function getSubstitutionType(baseType, substitute) { - if (substitute.flags & 3 /* TypeFlags.AnyOrUnknown */ || substitute === baseType) { + function getSubstitutionType(baseType, constraint) { + if (constraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || constraint === baseType || + !isGenericType(baseType) && !isGenericType(constraint)) { return baseType; } - var id = "".concat(getTypeId(baseType), ">").concat(getTypeId(substitute)); + var id = "".concat(getTypeId(baseType), ">").concat(getTypeId(constraint)); var cached = substitutionTypes.get(id); if (cached) { return cached; } var result = createType(33554432 /* TypeFlags.Substitution */); result.baseType = baseType; - result.substitute = substitute; + result.constraint = constraint; substitutionTypes.set(id, result); return result; } + function getSubstitutionIntersection(substitutionType) { + return getIntersectionType([substitutionType.constraint, substitutionType.baseType]); + } function isUnaryTupleTypeNode(node) { - return node.kind === 184 /* SyntaxKind.TupleType */ && node.elements.length === 1; + return node.kind === 186 /* SyntaxKind.TupleType */ && node.elements.length === 1; } function getImpliedConstraint(type, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : @@ -61308,16 +61814,16 @@ var ts; function getConditionalFlowTypeOfType(type, node) { var constraints; var covariant = true; - while (node && !ts.isStatement(node) && node.kind !== 320 /* SyntaxKind.JSDoc */) { + while (node && !ts.isStatement(node) && node.kind !== 323 /* SyntaxKind.JSDoc */) { var parent = node.parent; // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax - if (parent.kind === 164 /* SyntaxKind.Parameter */) { + if (parent.kind === 166 /* SyntaxKind.Parameter */) { covariant = !covariant; } // Always substitute on type parameters, regardless of variance, since even // in contravariant positions, they may rely on substituted constraints to be valid - if ((covariant || type.flags & 8650752 /* TypeFlags.TypeVariable */) && parent.kind === 189 /* SyntaxKind.ConditionalType */ && node === parent.trueType) { + if ((covariant || type.flags & 8650752 /* TypeFlags.TypeVariable */) && parent.kind === 191 /* SyntaxKind.ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -61325,7 +61831,7 @@ var ts; } // Given a homomorphic mapped type { [K in keyof T]: XXX }, where T is constrained to an array or tuple type, in the // template type XXX, K has an added constraint of number | `${number}`. - else if (type.flags & 262144 /* TypeFlags.TypeParameter */ && parent.kind === 195 /* SyntaxKind.MappedType */ && node === parent.type) { + else if (type.flags & 262144 /* TypeFlags.TypeParameter */ && parent.kind === 197 /* SyntaxKind.MappedType */ && node === parent.type) { var mappedType = getTypeFromTypeNode(parent); if (getTypeParameterFromMappedType(mappedType) === getActualTypeVariable(type)) { var typeParameter = getHomomorphicTypeVariable(mappedType); @@ -61339,10 +61845,10 @@ var ts; } node = parent; } - return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type; + return constraints ? getSubstitutionType(type, getIntersectionType(constraints)) : type; } function isJSDocTypeReference(node) { - return !!(node.flags & 8388608 /* NodeFlags.JSDoc */) && (node.kind === 178 /* SyntaxKind.TypeReference */ || node.kind === 200 /* SyntaxKind.ImportType */); + return !!(node.flags & 8388608 /* NodeFlags.JSDoc */) && (node.kind === 180 /* SyntaxKind.TypeReference */ || node.kind === 202 /* SyntaxKind.ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -61457,9 +61963,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return declaration; } } @@ -61610,6 +62116,13 @@ var ts; function getGlobalBigIntType() { return (deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, /*reportErrors*/ false))) || emptyObjectType; } + function getGlobalNaNSymbol() { + return (deferredGlobalNaNSymbol || (deferredGlobalNaNSymbol = getGlobalValueSymbol("NaN", /*reportErrors*/ false))); + } + function getGlobalRecordSymbol() { + deferredGlobalRecordSymbol || (deferredGlobalRecordSymbol = getGlobalTypeAliasSymbol("Record", /*arity*/ 2, /*reportErrors*/ true) || unknownSymbol); + return deferredGlobalRecordSymbol === unknownSymbol ? undefined : deferredGlobalRecordSymbol; + } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -61627,11 +62140,11 @@ var ts; } function getTupleElementFlags(node) { switch (node.kind) { - case 185 /* SyntaxKind.OptionalType */: + case 187 /* SyntaxKind.OptionalType */: return 2 /* ElementFlags.Optional */; - case 186 /* SyntaxKind.RestType */: + case 188 /* SyntaxKind.RestType */: return getRestTypeElementFlags(node); - case 197 /* SyntaxKind.NamedTupleMember */: + case 199 /* SyntaxKind.NamedTupleMember */: return node.questionToken ? 2 /* ElementFlags.Optional */ : node.dotDotDotToken ? getRestTypeElementFlags(node) : 1 /* ElementFlags.Required */; @@ -61649,14 +62162,14 @@ var ts; return readonly ? globalReadonlyArrayType : globalArrayType; } var elementFlags = ts.map(node.elements, getTupleElementFlags); - var missingName = ts.some(node.elements, function (e) { return e.kind !== 197 /* SyntaxKind.NamedTupleMember */; }); + var missingName = ts.some(node.elements, function (e) { return e.kind !== 199 /* SyntaxKind.NamedTupleMember */; }); return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? undefined : node.elements); } // Return true if the given type reference node is directly aliased or if it needs to be deferred // because it is possibly contained in a circular chain of eagerly resolved types. function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) { - return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 183 /* SyntaxKind.ArrayType */ ? mayResolveTypeAlias(node.elementType) : - node.kind === 184 /* SyntaxKind.TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : + return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 185 /* SyntaxKind.ArrayType */ ? mayResolveTypeAlias(node.elementType) : + node.kind === 186 /* SyntaxKind.TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias)); } // Return true when the given node is transitively contained in type constructs that eagerly @@ -61665,18 +62178,18 @@ var ts; function isResolvedByTypeAlias(node) { var parent = node.parent; switch (parent.kind) { - case 191 /* SyntaxKind.ParenthesizedType */: - case 197 /* SyntaxKind.NamedTupleMember */: - case 178 /* SyntaxKind.TypeReference */: - case 187 /* SyntaxKind.UnionType */: - case 188 /* SyntaxKind.IntersectionType */: - case 194 /* SyntaxKind.IndexedAccessType */: - case 189 /* SyntaxKind.ConditionalType */: - case 193 /* SyntaxKind.TypeOperator */: - case 183 /* SyntaxKind.ArrayType */: - case 184 /* SyntaxKind.TupleType */: + case 193 /* SyntaxKind.ParenthesizedType */: + case 199 /* SyntaxKind.NamedTupleMember */: + case 180 /* SyntaxKind.TypeReference */: + case 189 /* SyntaxKind.UnionType */: + case 190 /* SyntaxKind.IntersectionType */: + case 196 /* SyntaxKind.IndexedAccessType */: + case 191 /* SyntaxKind.ConditionalType */: + case 195 /* SyntaxKind.TypeOperator */: + case 185 /* SyntaxKind.ArrayType */: + case 186 /* SyntaxKind.TupleType */: return isResolvedByTypeAlias(parent); - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return true; } return false; @@ -61685,28 +62198,28 @@ var ts; // of a type alias. function mayResolveTypeAlias(node) { switch (node.kind) { - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node, 788968 /* SymbolFlags.Type */).flags & 524288 /* SymbolFlags.TypeAlias */); - case 181 /* SyntaxKind.TypeQuery */: + case 183 /* SyntaxKind.TypeQuery */: return true; - case 193 /* SyntaxKind.TypeOperator */: - return node.operator !== 154 /* SyntaxKind.UniqueKeyword */ && mayResolveTypeAlias(node.type); - case 191 /* SyntaxKind.ParenthesizedType */: - case 185 /* SyntaxKind.OptionalType */: - case 197 /* SyntaxKind.NamedTupleMember */: - case 316 /* SyntaxKind.JSDocOptionalType */: - case 314 /* SyntaxKind.JSDocNullableType */: - case 315 /* SyntaxKind.JSDocNonNullableType */: - case 309 /* SyntaxKind.JSDocTypeExpression */: + case 195 /* SyntaxKind.TypeOperator */: + return node.operator !== 156 /* SyntaxKind.UniqueKeyword */ && mayResolveTypeAlias(node.type); + case 193 /* SyntaxKind.ParenthesizedType */: + case 187 /* SyntaxKind.OptionalType */: + case 199 /* SyntaxKind.NamedTupleMember */: + case 319 /* SyntaxKind.JSDocOptionalType */: + case 317 /* SyntaxKind.JSDocNullableType */: + case 318 /* SyntaxKind.JSDocNonNullableType */: + case 312 /* SyntaxKind.JSDocTypeExpression */: return mayResolveTypeAlias(node.type); - case 186 /* SyntaxKind.RestType */: - return node.type.kind !== 183 /* SyntaxKind.ArrayType */ || mayResolveTypeAlias(node.type.elementType); - case 187 /* SyntaxKind.UnionType */: - case 188 /* SyntaxKind.IntersectionType */: + case 188 /* SyntaxKind.RestType */: + return node.type.kind !== 185 /* SyntaxKind.ArrayType */ || mayResolveTypeAlias(node.type.elementType); + case 189 /* SyntaxKind.UnionType */: + case 190 /* SyntaxKind.IntersectionType */: return ts.some(node.types, mayResolveTypeAlias); - case 194 /* SyntaxKind.IndexedAccessType */: + case 196 /* SyntaxKind.IndexedAccessType */: return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType); - case 189 /* SyntaxKind.ConditionalType */: + case 191 /* SyntaxKind.ConditionalType */: return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType); } @@ -61719,19 +62232,19 @@ var ts; if (target === emptyGenericType) { links.resolvedType = emptyObjectType; } - else if (!(node.kind === 184 /* SyntaxKind.TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* ElementFlags.Variadic */); })) && isDeferredTypeReferenceNode(node)) { - links.resolvedType = node.kind === 184 /* SyntaxKind.TupleType */ && node.elements.length === 0 ? target : + else if (!(node.kind === 186 /* SyntaxKind.TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* ElementFlags.Variadic */); })) && isDeferredTypeReferenceNode(node)) { + links.resolvedType = node.kind === 186 /* SyntaxKind.TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference(target, node, /*mapper*/ undefined); } else { - var elementTypes = node.kind === 183 /* SyntaxKind.ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); + var elementTypes = node.kind === 185 /* SyntaxKind.ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); links.resolvedType = createNormalizedTypeReference(target, elementTypes); } } return links.resolvedType; } function isReadonlyTypeOperator(node) { - return ts.isTypeOperatorNode(node) && node.operator === 145 /* SyntaxKind.ReadonlyKeyword */; + return ts.isTypeOperatorNode(node) && node.operator === 146 /* SyntaxKind.ReadonlyKeyword */; } function createTupleType(elementTypes, elementFlags, readonly, namedMemberDeclarations) { if (readonly === void 0) { readonly = false; } @@ -61846,7 +62359,7 @@ var ts; var lastRequiredIndex = -1; var firstRestIndex = -1; var lastOptionalOrRestIndex = -1; - var _loop_16 = function (i) { + var _loop_17 = function (i) { var type = elementTypes[i]; var flags = target.elementFlags[i]; if (flags & 8 /* ElementFlags.Variadic */) { @@ -61876,9 +62389,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - var state_4 = _loop_16(i); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_17(i); + if (typeof state_5 === "object") + return state_5.value; } // Turn optional elements preceding the last required element into required elements for (var i = 0; i < lastRequiredIndex; i++) { @@ -61906,7 +62419,7 @@ var ts; if (flags & (2 /* ElementFlags.Optional */ | 4 /* ElementFlags.Rest */)) { lastOptionalOrRestIndex = expandedFlags.length; } - expandedTypes.push(type); + expandedTypes.push(flags & 2 /* ElementFlags.Optional */ ? addOptionality(type, /*isProperty*/ true) : type); expandedFlags.push(flags); if (expandedDeclarations && declaration) { expandedDeclarations.push(declaration); @@ -62072,7 +62585,7 @@ var ts; var templates = ts.filter(types, isPatternLiteralType); if (templates.length) { var i = types.length; - var _loop_17 = function () { + var _loop_18 = function () { i--; var t = types[i]; if (t.flags & 128 /* TypeFlags.StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { @@ -62080,7 +62593,7 @@ var ts; } }; while (i > 0) { - _loop_17(); + _loop_18(); } } } @@ -62157,14 +62670,14 @@ var ts; var namedUnions = []; addNamedUnions(namedUnions, types); var reducedTypes = []; - var _loop_18 = function (t) { + var _loop_19 = function (t) { if (!ts.some(namedUnions, function (union) { return containsType(union.types, t); })) { reducedTypes.push(t); } }; for (var _i = 0, typeSet_1 = typeSet; _i < typeSet_1.length; _i++) { var t = typeSet_1[_i]; - _loop_18(t); + _loop_19(t); } if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) { return namedUnions[0]; @@ -62654,7 +63167,7 @@ var ts; type.flags & 16777216 /* TypeFlags.Conditional */ ? type.root.isDistributive && type.checkType === typeVariable : type.flags & (3145728 /* TypeFlags.UnionOrIntersection */ | 134217728 /* TypeFlags.TemplateLiteral */) ? ts.every(type.types, isDistributive) : type.flags & 8388608 /* TypeFlags.IndexedAccess */ ? isDistributive(type.objectType) && isDistributive(type.indexType) : - type.flags & 33554432 /* TypeFlags.Substitution */ ? isDistributive(type.substitute) : + type.flags & 33554432 /* TypeFlags.Substitution */ ? isDistributive(type.baseType) && isDistributive(type.constraint) : type.flags & 268435456 /* TypeFlags.StringMapping */ ? isDistributive(type.type) : false; } @@ -62735,15 +63248,15 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { switch (node.operator) { - case 140 /* SyntaxKind.KeyOfKeyword */: + case 141 /* SyntaxKind.KeyOfKeyword */: links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); break; - case 154 /* SyntaxKind.UniqueKeyword */: - links.resolvedType = node.type.kind === 151 /* SyntaxKind.SymbolKeyword */ + case 156 /* SyntaxKind.UniqueKeyword */: + links.resolvedType = node.type.kind === 153 /* SyntaxKind.SymbolKeyword */ ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) : errorType; break; - case 145 /* SyntaxKind.ReadonlyKeyword */: + case 146 /* SyntaxKind.ReadonlyKeyword */: links.resolvedType = getTypeFromTypeNode(node.type); break; default: @@ -62779,8 +63292,14 @@ var ts; return getStringLiteralType(text); } newTexts.push(text); - if (ts.every(newTexts, function (t) { return t === ""; }) && ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { - return stringType; + if (ts.every(newTexts, function (t) { return t === ""; })) { + if (ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { + return stringType; + } + // Normalize `${Mapping}` into Mapping + if (newTypes.length === 1 && isPatternLiteralType(newTypes[0])) { + return newTypes[0]; + } } var id = "".concat(getTypeListId(newTypes), "|").concat(ts.map(newTexts, function (t) { return t.length; }).join(","), "|").concat(newTexts.join("")); var type = templateLiteralTypes.get(id); @@ -62839,12 +63358,14 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - // Mapping> === Mapping - type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : - isGenericIndexType(type) || isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, isPatternLiteralPlaceholderType(type) && !(type.flags & 268435456 /* TypeFlags.StringMapping */) ? getTemplateLiteralType(["", ""], [type]) : type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : - type; + type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : + type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : + // Mapping> === Mapping + type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : + type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : + // This handles Mapping<`${number}`> and Mapping<`${bigint}`> + isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : + type; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -62935,7 +63456,7 @@ var ts; } function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, accessNode, accessFlags) { var _a; - var accessExpression = accessNode && accessNode.kind === 207 /* SyntaxKind.ElementAccessExpression */ ? accessNode : undefined; + var accessExpression = accessNode && accessNode.kind === 209 /* SyntaxKind.ElementAccessExpression */ ? accessNode : undefined; var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode); if (propName !== undefined) { if (accessFlags & 256 /* AccessFlags.Contextual */) { @@ -63009,7 +63530,18 @@ var ts; return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; } errorIfWritingToReadonlyIndex(indexInfo); - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; + // When accessing an enum object with its own type, + // e.g. E[E.A] for enum E { A }, undefined shouldn't + // be included in the result type + if ((accessFlags & 1 /* AccessFlags.IncludeUndefined */) && + !(objectType.symbol && + objectType.symbol.flags & (256 /* SymbolFlags.RegularEnum */ | 128 /* SymbolFlags.ConstEnum */) && + (indexType.symbol && + indexType.flags & 1024 /* TypeFlags.EnumLiteral */ && + getParentOfSymbol(indexType.symbol) === objectType.symbol))) { + return getUnionType([indexInfo.type, undefinedType]); + } + return indexInfo.type; } if (indexType.flags & 131072 /* TypeFlags.Never */) { return neverType; @@ -63110,16 +63642,17 @@ var ts; } } function getIndexNodeForAccessExpression(accessNode) { - return accessNode.kind === 207 /* SyntaxKind.ElementAccessExpression */ ? accessNode.argumentExpression : - accessNode.kind === 194 /* SyntaxKind.IndexedAccessType */ ? accessNode.indexType : - accessNode.kind === 162 /* SyntaxKind.ComputedPropertyName */ ? accessNode.expression : + return accessNode.kind === 209 /* SyntaxKind.ElementAccessExpression */ ? accessNode.argumentExpression : + accessNode.kind === 196 /* SyntaxKind.IndexedAccessType */ ? accessNode.indexType : + accessNode.kind === 164 /* SyntaxKind.ComputedPropertyName */ ? accessNode.expression : accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || isPatternLiteralType(type); } function isPatternLiteralType(type) { - return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); + return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType) || + !!(type.flags & 268435456 /* TypeFlags.StringMapping */) && isPatternLiteralPlaceholderType(type.type); } function isGenericType(type) { return !!getGenericObjectFlags(type); @@ -63141,7 +63674,7 @@ var ts; if (type.flags & 33554432 /* TypeFlags.Substitution */) { if (!(type.objectFlags & 2097152 /* ObjectFlags.IsGenericTypeComputed */)) { type.objectFlags |= 2097152 /* ObjectFlags.IsGenericTypeComputed */ | - getGenericObjectFlags(type.substitute) | getGenericObjectFlags(type.baseType); + getGenericObjectFlags(type.baseType) | getGenericObjectFlags(type.constraint); } return type.objectFlags & 12582912 /* ObjectFlags.IsGenericType */; } @@ -63292,7 +63825,7 @@ var ts; // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved // eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 194 /* SyntaxKind.IndexedAccessType */ ? + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 196 /* SyntaxKind.IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) { if (objectType.flags & 3 /* TypeFlags.AnyOrUnknown */) { @@ -63344,11 +63877,7 @@ var ts; var objectType = getTypeFromTypeNode(node.objectType); var indexType = getTypeFromTypeNode(node.indexType); var potentialAlias = getAliasSymbolForTypeNode(node); - var resolved = getIndexedAccessType(objectType, indexType, 0 /* AccessFlags.None */, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias)); - links.resolvedType = resolved.flags & 8388608 /* TypeFlags.IndexedAccess */ && - resolved.objectType === objectType && - resolved.indexType === indexType ? - getConditionalFlowTypeOfType(resolved, node) : resolved; + links.resolvedType = getIndexedAccessType(objectType, indexType, 0 /* AccessFlags.None */, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias)); } return links.resolvedType; } @@ -63402,18 +63931,23 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_19 = function () { + // We loop here for an immediately nested conditional type in the false position, effectively treating + // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for + // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of + // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive + // cases we increment the tail recursion counter and stop after 1000 iterations. + while (true) { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; - return "break"; + break; } var isUnwrapped = isTypicalNondistributiveConditional(root); var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { - return { value: wildcardType }; + return wildcardType; } var combinedMapper = void 0; if (root.inferTypeParameters) { @@ -63446,11 +63980,7 @@ var ts; } } } - // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type - // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to - // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint - // so in those cases we refain from performing inference and retain the uninfered type parameter - if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -63482,14 +64012,14 @@ var ts; var newRoot = falseType_1.root; if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) { root = newRoot; - return "continue"; + continue; } if (canTailRecurse(falseType_1, mapper)) { - return "continue"; + continue; } } result = instantiateType(falseType_1, mapper); - return "break"; + break; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -63500,10 +64030,10 @@ var ts; var trueType_1 = getTypeFromTypeNode(root.node.trueType); var trueMapper = combinedMapper || mapper; if (canTailRecurse(trueType_1, trueMapper)) { - return "continue"; + continue; } result = instantiateType(trueType_1, trueMapper); - return "break"; + break; } } // Return a deferred type for a check that is neither definitely true nor definitely false @@ -63515,19 +64045,7 @@ var ts; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 - return "break"; - }; - // We loop here for an immediately nested conditional type in the false position, effectively treating - // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for - // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of - // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive - // cases we increment the tail recursion counter and stop after 1000 iterations. - while (true) { - var state_5 = _loop_19(); - if (typeof state_5 === "object") - return state_5.value; - if (state_5 === "break") - break; + break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; // We tail-recurse for generic conditional types that (a) have not already been evaluated and cached, and @@ -63719,7 +64237,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host) || ts.isJSDocTypeExpression(host) || ts.isTypeOperatorNode(host) && host.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { + while (ts.isParenthesizedTypeNode(host) || ts.isJSDocTypeExpression(host) || ts.isTypeOperatorNode(host) && host.operator === 146 /* SyntaxKind.ReadonlyKeyword */) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -63964,7 +64482,7 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 258 /* SyntaxKind.InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 261 /* SyntaxKind.InterfaceDeclaration */)) { if (!ts.isStatic(container) && (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -63999,17 +64517,17 @@ var ts; } function getArrayElementTypeNode(node) { switch (node.kind) { - case 191 /* SyntaxKind.ParenthesizedType */: + case 193 /* SyntaxKind.ParenthesizedType */: return getArrayElementTypeNode(node.type); - case 184 /* SyntaxKind.TupleType */: + case 186 /* SyntaxKind.TupleType */: if (node.elements.length === 1) { node = node.elements[0]; - if (node.kind === 186 /* SyntaxKind.RestType */ || node.kind === 197 /* SyntaxKind.NamedTupleMember */ && node.dotDotDotToken) { + if (node.kind === 188 /* SyntaxKind.RestType */ || node.kind === 199 /* SyntaxKind.NamedTupleMember */ && node.dotDotDotToken) { return getArrayElementTypeNode(node.type); } } break; - case 183 /* SyntaxKind.ArrayType */: + case 185 /* SyntaxKind.ArrayType */: return node.elementType; } return undefined; @@ -64025,99 +64543,99 @@ var ts; } function getTypeFromTypeNodeWorker(node) { switch (node.kind) { - case 130 /* SyntaxKind.AnyKeyword */: - case 312 /* SyntaxKind.JSDocAllType */: - case 313 /* SyntaxKind.JSDocUnknownType */: + case 131 /* SyntaxKind.AnyKeyword */: + case 315 /* SyntaxKind.JSDocAllType */: + case 316 /* SyntaxKind.JSDocUnknownType */: return anyType; - case 155 /* SyntaxKind.UnknownKeyword */: + case 157 /* SyntaxKind.UnknownKeyword */: return unknownType; - case 150 /* SyntaxKind.StringKeyword */: + case 152 /* SyntaxKind.StringKeyword */: return stringType; - case 147 /* SyntaxKind.NumberKeyword */: + case 148 /* SyntaxKind.NumberKeyword */: return numberType; - case 158 /* SyntaxKind.BigIntKeyword */: + case 160 /* SyntaxKind.BigIntKeyword */: return bigintType; - case 133 /* SyntaxKind.BooleanKeyword */: + case 134 /* SyntaxKind.BooleanKeyword */: return booleanType; - case 151 /* SyntaxKind.SymbolKeyword */: + case 153 /* SyntaxKind.SymbolKeyword */: return esSymbolType; case 114 /* SyntaxKind.VoidKeyword */: return voidType; - case 153 /* SyntaxKind.UndefinedKeyword */: + case 155 /* SyntaxKind.UndefinedKeyword */: return undefinedType; case 104 /* SyntaxKind.NullKeyword */: // TODO(rbuckton): `NullKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service. return nullType; - case 143 /* SyntaxKind.NeverKeyword */: + case 144 /* SyntaxKind.NeverKeyword */: return neverType; - case 148 /* SyntaxKind.ObjectKeyword */: + case 149 /* SyntaxKind.ObjectKeyword */: return node.flags & 262144 /* NodeFlags.JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType; - case 138 /* SyntaxKind.IntrinsicKeyword */: + case 139 /* SyntaxKind.IntrinsicKeyword */: return intrinsicMarkerType; - case 192 /* SyntaxKind.ThisType */: + case 194 /* SyntaxKind.ThisType */: case 108 /* SyntaxKind.ThisKeyword */: // TODO(rbuckton): `ThisKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service and because of `isPartOfTypeNode`. return getTypeFromThisTypeNode(node); - case 196 /* SyntaxKind.LiteralType */: + case 198 /* SyntaxKind.LiteralType */: return getTypeFromLiteralTypeNode(node); - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return getTypeFromTypeReference(node); - case 177 /* SyntaxKind.TypePredicate */: + case 179 /* SyntaxKind.TypePredicate */: return node.assertsModifier ? voidType : booleanType; - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 181 /* SyntaxKind.TypeQuery */: + case 183 /* SyntaxKind.TypeQuery */: return getTypeFromTypeQueryNode(node); - case 183 /* SyntaxKind.ArrayType */: - case 184 /* SyntaxKind.TupleType */: + case 185 /* SyntaxKind.ArrayType */: + case 186 /* SyntaxKind.TupleType */: return getTypeFromArrayOrTupleTypeNode(node); - case 185 /* SyntaxKind.OptionalType */: + case 187 /* SyntaxKind.OptionalType */: return getTypeFromOptionalTypeNode(node); - case 187 /* SyntaxKind.UnionType */: + case 189 /* SyntaxKind.UnionType */: return getTypeFromUnionTypeNode(node); - case 188 /* SyntaxKind.IntersectionType */: + case 190 /* SyntaxKind.IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 314 /* SyntaxKind.JSDocNullableType */: + case 317 /* SyntaxKind.JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 316 /* SyntaxKind.JSDocOptionalType */: + case 319 /* SyntaxKind.JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 197 /* SyntaxKind.NamedTupleMember */: + case 199 /* SyntaxKind.NamedTupleMember */: return getTypeFromNamedTupleTypeNode(node); - case 191 /* SyntaxKind.ParenthesizedType */: - case 315 /* SyntaxKind.JSDocNonNullableType */: - case 309 /* SyntaxKind.JSDocTypeExpression */: + case 193 /* SyntaxKind.ParenthesizedType */: + case 318 /* SyntaxKind.JSDocNonNullableType */: + case 312 /* SyntaxKind.JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 186 /* SyntaxKind.RestType */: + case 188 /* SyntaxKind.RestType */: return getTypeFromRestTypeNode(node); - case 318 /* SyntaxKind.JSDocVariadicType */: + case 321 /* SyntaxKind.JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 182 /* SyntaxKind.TypeLiteral */: - case 322 /* SyntaxKind.JSDocTypeLiteral */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 323 /* SyntaxKind.JSDocSignature */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: + case 184 /* SyntaxKind.TypeLiteral */: + case 325 /* SyntaxKind.JSDocTypeLiteral */: + case 320 /* SyntaxKind.JSDocFunctionType */: + case 326 /* SyntaxKind.JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 193 /* SyntaxKind.TypeOperator */: + case 195 /* SyntaxKind.TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 194 /* SyntaxKind.IndexedAccessType */: + case 196 /* SyntaxKind.IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 195 /* SyntaxKind.MappedType */: + case 197 /* SyntaxKind.MappedType */: return getTypeFromMappedTypeNode(node); - case 189 /* SyntaxKind.ConditionalType */: + case 191 /* SyntaxKind.ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 190 /* SyntaxKind.InferType */: + case 192 /* SyntaxKind.InferType */: return getTypeFromInferTypeNode(node); - case 198 /* SyntaxKind.TemplateLiteralType */: + case 200 /* SyntaxKind.TemplateLiteralType */: return getTypeFromTemplateTypeNode(node); - case 200 /* SyntaxKind.ImportType */: + case 202 /* SyntaxKind.ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier, qualified name, or property access expression is a type expression // Callers should first ensure this by calling `isPartOfTypeNode` // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 79 /* SyntaxKind.Identifier */: - case 161 /* SyntaxKind.QualifiedName */: - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 163 /* SyntaxKind.QualifiedName */: + case 208 /* SyntaxKind.PropertyAccessExpression */: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -64224,8 +64742,8 @@ var ts; return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); } function getRestrictiveTypeParameter(tp) { - return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), - tp.restrictiveInstantiation.constraint = unknownType, + return !tp.constraint && !getConstraintDeclaration(tp) || tp.constraint === noConstraintType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), + tp.restrictiveInstantiation.constraint = noConstraintType, tp.restrictiveInstantiation); } function cloneTypeParameter(typeParameter) { @@ -64339,17 +64857,18 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.parent.kind === 178 /* SyntaxKind.TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || - node.parent.kind === 200 /* SyntaxKind.ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); + return !(node.parent.kind === 180 /* SyntaxKind.TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || + node.parent.kind === 202 /* SyntaxKind.ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); } function isTypeParameterPossiblyReferenced(tp, node) { - // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // If the type parameter doesn't have exactly one declaration, if there are intervening statement blocks // between the node and the type parameter declaration, if the node contains actual references to the - // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + // type parameter, or if the node contains type queries that we can't prove couldn't contain references to the type parameter, + // we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container = tp.symbol.declarations[0].parent; for (var n = node; n !== container; n = n.parent) { - if (!n || n.kind === 235 /* SyntaxKind.Block */ || n.kind === 189 /* SyntaxKind.ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { + if (!n || n.kind === 238 /* SyntaxKind.Block */ || n.kind === 191 /* SyntaxKind.ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { return true; } } @@ -64358,15 +64877,36 @@ var ts; return true; function containsReference(node) { switch (node.kind) { - case 192 /* SyntaxKind.ThisType */: + case 194 /* SyntaxKind.ThisType */: return !!tp.isThisType; case 79 /* SyntaxKind.Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality - case 181 /* SyntaxKind.TypeQuery */: + case 183 /* SyntaxKind.TypeQuery */: + var entityName = node.exprName; + var firstIdentifier = ts.getFirstIdentifier(entityName); + var firstIdentifierSymbol = getResolvedSymbol(firstIdentifier); + var tpDeclaration = tp.symbol.declarations[0]; // There is exactly one declaration, otherwise `containsReference` is not called + var tpScope_1; + if (tpDeclaration.kind === 165 /* SyntaxKind.TypeParameter */) { // Type parameter is a regular type parameter, e.g. foo + tpScope_1 = tpDeclaration.parent; + } + else if (tp.isThisType) { + // Type parameter is the this type, and its declaration is the class declaration. + tpScope_1 = tpDeclaration; + } + else { + // Type parameter's declaration was unrecognized. + // This could happen if the type parameter comes from e.g. a JSDoc annotation, so we default to returning true. + return true; + } + if (firstIdentifierSymbol.declarations) { + return ts.some(firstIdentifierSymbol.declarations, function (idDecl) { return ts.isNodeDescendantOf(idDecl, tpScope_1); }) || + ts.some(node.typeArguments, containsReference); + } return true; - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: return !node.type && !!node.body || ts.some(node.typeParameters, containsReference) || ts.some(node.parameters, containsReference) || @@ -64588,17 +65128,18 @@ var ts; return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper), aliasSymbol, aliasTypeArguments); } if (flags & 33554432 /* TypeFlags.Substitution */) { - var maybeVariable = instantiateType(type.baseType, mapper); - if (maybeVariable.flags & 8650752 /* TypeFlags.TypeVariable */) { - return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper)); + var newBaseType = instantiateType(type.baseType, mapper); + var newConstraint = instantiateType(type.constraint, mapper); + // A substitution type originates in the true branch of a conditional type and can be resolved + // to just the base type in the same cases as the conditional type resolves to its true branch + // (because the base type is then known to satisfy the constraint). + if (newBaseType.flags & 8650752 /* TypeFlags.TypeVariable */ && isGenericType(newConstraint)) { + return getSubstitutionType(newBaseType, newConstraint); } - else { - var sub = instantiateType(type.substitute, mapper); - if (sub.flags & 3 /* TypeFlags.AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) { - return maybeVariable; - } - return sub; + if (newConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(newBaseType), getRestrictiveInstantiation(newConstraint))) { + return newBaseType; } + return newBaseType.flags & 8650752 /* TypeFlags.TypeVariable */ ? getSubstitutionType(newBaseType, newConstraint) : getIntersectionType([newConstraint, newBaseType]); } return type; } @@ -64647,35 +65188,35 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 169 /* SyntaxKind.MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 171 /* SyntaxKind.MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type return isContextSensitiveFunctionLikeDeclaration(node); - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 222 /* SyntaxKind.ConditionalExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return (node.operatorToken.kind === 56 /* SyntaxKind.BarBarToken */ || node.operatorToken.kind === 60 /* SyntaxKind.QuestionQuestionToken */) && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: return isContextSensitive(node.initializer); - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return isContextSensitive(node.expression); - case 286 /* SyntaxKind.JsxAttributes */: + case 289 /* SyntaxKind.JsxAttributes */: return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); - case 285 /* SyntaxKind.JsxAttribute */: { + case 288 /* SyntaxKind.JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 288 /* SyntaxKind.JsxExpression */: { + case 291 /* SyntaxKind.JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -64684,15 +65225,14 @@ var ts; return false; } function isContextSensitiveFunctionLikeDeclaration(node) { - return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) && - (ts.hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node)); + return ts.hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node); } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 235 /* SyntaxKind.Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 238 /* SyntaxKind.Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || ts.isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -64793,23 +65333,23 @@ var ts; return true; } switch (node.kind) { - case 288 /* SyntaxKind.JsxExpression */: - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 291 /* SyntaxKind.JsxExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: switch (node.operatorToken.kind) { case 63 /* SyntaxKind.EqualsToken */: case 27 /* SyntaxKind.CommaToken */: return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); } break; - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 286 /* SyntaxKind.JsxAttributes */: + case 289 /* SyntaxKind.JsxAttributes */: return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer); } return false; @@ -65018,7 +65558,7 @@ var ts; } function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { switch (child.kind) { - case 288 /* SyntaxKind.JsxExpression */: + case 291 /* SyntaxKind.JsxExpression */: // child is of the type of the expression return { errorNode: child, innerExpression: child.expression, nameType: nameType }; case 11 /* SyntaxKind.JsxText */: @@ -65027,9 +65567,9 @@ var ts; } // child is a string return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; - case 278 /* SyntaxKind.JsxElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 282 /* SyntaxKind.JsxFragment */: + case 281 /* SyntaxKind.JsxElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: + case 285 /* SyntaxKind.JsxFragment */: // child is of type JSX.Element return { errorNode: child, innerExpression: child, nameType: nameType }; default: @@ -65177,11 +65717,11 @@ var ts; } _b = prop.kind; switch (_b) { - case 173 /* SyntaxKind.SetAccessor */: return [3 /*break*/, 2]; - case 172 /* SyntaxKind.GetAccessor */: return [3 /*break*/, 2]; - case 169 /* SyntaxKind.MethodDeclaration */: return [3 /*break*/, 2]; - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: return [3 /*break*/, 2]; - case 296 /* SyntaxKind.PropertyAssignment */: return [3 /*break*/, 4]; + case 175 /* SyntaxKind.SetAccessor */: return [3 /*break*/, 2]; + case 174 /* SyntaxKind.GetAccessor */: return [3 /*break*/, 2]; + case 171 /* SyntaxKind.MethodDeclaration */: return [3 /*break*/, 2]; + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 299 /* SyntaxKind.PropertyAssignment */: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -65254,8 +65794,8 @@ var ts; void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers); } var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; - var strictVariance = !(checkMode & 3 /* SignatureCheckMode.Callback */) && strictFunctionTypes && kind !== 169 /* SyntaxKind.MethodDeclaration */ && - kind !== 168 /* SyntaxKind.MethodSignature */ && kind !== 171 /* SyntaxKind.Constructor */; + var strictVariance = !(checkMode & 3 /* SignatureCheckMode.Callback */) && strictFunctionTypes && kind !== 171 /* SyntaxKind.MethodDeclaration */ && + kind !== 170 /* SyntaxKind.MethodSignature */ && kind !== 173 /* SyntaxKind.Constructor */; var result = -1 /* Ternary.True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -65552,7 +66092,7 @@ var ts; var t = isFreshLiteralType(type) ? type.regularType : ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : - type.flags & 33554432 /* TypeFlags.Substitution */ ? writing ? type.baseType : type.substitute : + type.flags & 33554432 /* TypeFlags.Substitution */ ? writing ? type.baseType : getSubstitutionIntersection(type) : type.flags & 25165824 /* TypeFlags.Simplifiable */ ? getSimplifiedType(type, writing) : type; if (t === type) @@ -65959,7 +66499,8 @@ var ts; return 0 /* Ternary.False */; } } - var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* IntersectionState.Target */) && + var isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source)) && + !(intersectionState & 2 /* IntersectionState.Target */) && source.flags & (131068 /* TypeFlags.Primitive */ | 524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && source !== globalObjectType && target.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)); @@ -65986,27 +66527,6 @@ var ts; var result_7 = skipCaching ? unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) : recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags); - // For certain combinations involving intersections and optional, excess, or mismatched properties we need - // an extra property check where the intersection is viewed as a single object. The following are motivating - // examples that all should be errors, but aren't without this extra property check: - // - // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property - // - // declare let wrong: { a: { y: string } }; - // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type - // - // function foo(x: { a?: string }, y: T & { a: boolean }) { - // x = y; // Mismatched property in source intersection - // } - // - // We suppress recursive intersection property checks because they can generate lots of work when relating - // recursive intersections that are structurally similar but not exactly identical. See #37854. - if (result_7 && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { - inPropertyCheck = true; - result_7 &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* IntersectionState.PropertyCheck */, recursionFlags); - inPropertyCheck = false; - } if (result_7) { return result_7; } @@ -66211,11 +66731,15 @@ var ts; // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't // appear to be comparable to '2'. if (relation === comparableRelation && target.flags & 131068 /* TypeFlags.Primitive */) { - var constraints = ts.sameMap(source.types, getBaseConstraintOrType); + var constraints = ts.sameMap(source.types, function (t) { return t.flags & 465829888 /* TypeFlags.Instantiable */ ? getBaseConstraintOfType(t) || unknownType : t; }); if (constraints !== source.types) { source = getIntersectionType(constraints); + if (source.flags & 131072 /* TypeFlags.Never */) { + return 0 /* Ternary.False */; + } if (!(source.flags & 2097152 /* TypeFlags.Intersection */)) { - return isRelatedTo(source, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false); + return isRelatedTo(source, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false) || + isRelatedTo(target, source, 1 /* RecursionFlags.Source */, /*reportErrors*/ false); } } } @@ -66400,8 +66924,7 @@ var ts; if (overflow) { return 0 /* Ternary.False */; } - var keyIntersectionState = intersectionState | (inPropertyCheck ? 8 /* IntersectionState.InPropertyCheck */ : 0); - var id = getRelationKey(source, target, keyIntersectionState, relation, /*ingnoreConstraints*/ false); + var id = getRelationKey(source, target, intersectionState, relation, /*ingnoreConstraints*/ false); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* RelationComparisonResult.Failed */ && !(entry & 4 /* RelationComparisonResult.Reported */)) { @@ -66431,7 +66954,7 @@ var ts; // A key that starts with "*" is an indication that we have type references that reference constrained // type parameters. For such keys we also check against the key we would have gotten if all type parameters // were unconstrained. - var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, keyIntersectionState, relation, /*ignoreConstraints*/ true) : undefined; + var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, intersectionState, relation, /*ignoreConstraints*/ true) : undefined; for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { @@ -66518,7 +67041,7 @@ var ts; function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { var saveErrorInfo = captureErrorCalculationState(); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo); - if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + if (relation !== identityRelation) { // The combined constraint of an intersection type is the intersection of the constraints of // the constituents. When an intersection type contains instantiable types with union type // constraints, there are situations where we need to examine the combined constraint. One is @@ -66532,10 +67055,33 @@ var ts; // needs to have its constraint hoisted into an intersection with said type parameter, this way // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` - var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); - if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself - // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this - result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); + if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself + // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this + result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + } + } + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && !isGenericObjectType(target) && source.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) || + isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { + inPropertyCheck = true; + result &= propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); + inPropertyCheck = false; } } if (result) { @@ -66544,9 +67090,6 @@ var ts; return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo) { - if (intersectionState & 4 /* IntersectionState.PropertyCheck */) { - return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); - } var result; var originalErrorInfo; var varianceCheckFailed = false; @@ -66585,7 +67128,11 @@ var ts; } } if (sourceFlags & 33554432 /* TypeFlags.Substitution */) { - return isRelatedTo(source.substitute, target.substitute, 3 /* RecursionFlags.Both */, /*reportErrors*/ false); + if (result = isRelatedTo(source.baseType, target.baseType, 3 /* RecursionFlags.Both */, /*reportErrors*/ false)) { + if (result &= isRelatedTo(source.constraint, target.constraint, 3 /* RecursionFlags.Both */, /*reportErrors*/ false)) { + return result; + } + } } if (!(sourceFlags & 524288 /* TypeFlags.Object */)) { return 0 /* Ternary.False */; @@ -66643,7 +67190,7 @@ var ts; // with another type parameter unless one extends the other. (Remember: comparability is mostly bidirectional!) var constraint = getConstraintOfTypeParameter(source); if (constraint && hasNonCircularBaseConstraint(source)) { - while (constraint && constraint.flags & 262144 /* TypeFlags.TypeParameter */) { + while (constraint && someType(constraint, function (c) { return !!(c.flags & 262144 /* TypeFlags.TypeParameter */); })) { if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { return result; } @@ -67299,7 +67846,7 @@ var ts; return 0 /* Ternary.False */; } // When checking for comparability, be more lenient with optional properties. - if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && targetProp.flags & 106500 /* SymbolFlags.ClassMember */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -67337,7 +67884,7 @@ var ts; shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it } if (props.length === 1) { - var propName = symbolToString(unmatchedProperty); + var propName = symbolToString(unmatchedProperty, /*enclosingDeclaration*/ undefined, 0 /* SymbolFlags.None */, 4 /* SymbolFormatFlags.AllowAnyNodeKind */ | 16 /* SymbolFormatFlags.WriteComputedProps */); reportError.apply(void 0, __spreadArray([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target), false)); if (ts.length(unmatchedProperty.declarations)) { associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName)); @@ -67586,7 +68133,7 @@ var ts; var targetSignature = ts.first(targetSignatures); result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, incompatibleReporter(sourceSignature, targetSignature)); if (!result && reportErrors && kind === 1 /* SignatureKind.Construct */ && (sourceObjectFlags & targetObjectFlags) && - (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 171 /* SyntaxKind.Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 171 /* SyntaxKind.Constructor */)) { + (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 173 /* SyntaxKind.Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 173 /* SyntaxKind.Constructor */)) { var constructSignatureToString = function (signature) { return signatureToString(signature, /*enclosingDeclaration*/ undefined, 262144 /* TypeFormatFlags.WriteArrowStyleSignature */, kind); }; @@ -68351,7 +68898,7 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(target); // A base type expression may circularly reference the class itself (e.g. as an argument to function call), so we only // check for base types specified as simple qualified names. - if (baseTypeNode && baseTypeNode.expression.kind !== 79 /* SyntaxKind.Identifier */ && baseTypeNode.expression.kind !== 206 /* SyntaxKind.PropertyAccessExpression */) { + if (baseTypeNode && baseTypeNode.expression.kind !== 79 /* SyntaxKind.Identifier */ && baseTypeNode.expression.kind !== 208 /* SyntaxKind.PropertyAccessExpression */) { return undefined; } } @@ -68399,8 +68946,7 @@ var ts; return !!(type.flags & 109440 /* TypeFlags.Unit */); } function isUnitLikeType(type) { - return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.some(type.types, isUnitType) : - !!(type.flags & 109440 /* TypeFlags.Unit */); + return isUnitType(getBaseConstraintOrType(type)); } function extractUnitType(type) { return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.find(type.types, isUnitType) || type : type; @@ -68442,7 +68988,7 @@ var ts; if (!isLiteralOfContextualType(type, contextualType)) { type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); } - return type; + return getRegularTypeOfLiteralType(type); } function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) { if (type && isUnitType(type)) { @@ -68537,7 +69083,8 @@ var ts; function getOptionalType(type, isProperty) { if (isProperty === void 0) { isProperty = false; } ts.Debug.assert(strictNullChecks); - return type.flags & 32768 /* TypeFlags.Undefined */ ? type : getUnionType([type, isProperty ? missingType : undefinedType]); + var missingOrUndefined = isProperty ? missingType : undefinedType; + return type.flags & 32768 /* TypeFlags.Undefined */ || type.flags & 1048576 /* TypeFlags.Union */ && type.types[0] === missingOrUndefined ? type : getUnionType([type, missingOrUndefined]); } function getGlobalNonNullableTypeInstantiation(type) { if (!deferredGlobalNonNullableTypeAlias) { @@ -68826,12 +69373,12 @@ var ts; } var diagnostic; switch (declaration.kind) { - case 221 /* SyntaxKind.BinaryExpression */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: + case 223 /* SyntaxKind.BinaryExpression */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: var param = declaration; if (ts.isIdentifier(param.name) && (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && @@ -68847,23 +69394,23 @@ var ts; noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; if (!noImplicitAny) { // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. return; } break; - case 317 /* SyntaxKind.JSDocFunctionType */: + case 320 /* SyntaxKind.JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; - case 256 /* SyntaxKind.FunctionDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: if (noImplicitAny && !declaration.name) { if (wideningKind === 3 /* WideningKind.GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); @@ -68877,7 +69424,7 @@ var ts; wideningKind === 3 /* WideningKind.GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; - case 195 /* SyntaxKind.MappedType */: + case 197 /* SyntaxKind.MappedType */: if (noImplicitAny) { error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); } @@ -68994,7 +69541,7 @@ var ts; if (context.intraExpressionInferenceSites) { for (var _i = 0, _a = context.intraExpressionInferenceSites; _i < _a.length; _i++) { var _b = _a[_i], node = _b.node, type = _b.type; - var contextualType = node.kind === 169 /* SyntaxKind.MethodDeclaration */ ? + var contextualType = node.kind === 171 /* SyntaxKind.MethodDeclaration */ ? getContextualTypeForObjectLiteralMethod(node, 2 /* ContextFlags.NoConstraints */) : getContextualType(node, 2 /* ContextFlags.NoConstraints */); if (contextualType) { @@ -69057,8 +69604,8 @@ var ts; } function isNonGenericTopLevelType(type) { if (type.aliasSymbol && !type.aliasTypeArguments) { - var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 259 /* SyntaxKind.TypeAliasDeclaration */); - return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 305 /* SyntaxKind.SourceFile */ ? true : n.kind === 261 /* SyntaxKind.ModuleDeclaration */ ? false : "quit"; })); + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 262 /* SyntaxKind.TypeAliasDeclaration */); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 308 /* SyntaxKind.SourceFile */ ? true : n.kind === 264 /* SyntaxKind.ModuleDeclaration */ ? false : "quit"; })); } return false; } @@ -69278,7 +69825,7 @@ var ts; && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); } function isMemberOfStringMapping(source, target) { - if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + if (target.flags & (4 /* TypeFlags.String */ | 1 /* TypeFlags.Any */)) { return true; } if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { @@ -69516,7 +70063,10 @@ var ts; // // This flag is infectious; if we produce Box (where never is silentNeverType), Box is // also non-inferrable. - if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) { + // + // As a special case, also ignore nonInferrableAnyType, which is a special form of the any type + // used as a stand-in for binding elements when they are being inferred. + if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */ || source === nonInferrableAnyType) { return; } if (!inference.isFixed) { @@ -69589,7 +70139,7 @@ var ts; } else if (source.flags & 33554432 /* TypeFlags.Substitution */) { inferFromTypes(source.baseType, target); - inferWithPriority(source.substitute, target, 4 /* InferencePriority.SubstituteSource */); // Make substitute inference at a lower priority + inferWithPriority(getSubstitutionIntersection(source), target, 4 /* InferencePriority.SubstituteSource */); // Make substitute inference at a lower priority } else if (target.flags & 16777216 /* TypeFlags.Conditional */) { invokeOnce(source, target, inferToConditionalType); @@ -70071,7 +70621,7 @@ var ts; var saveBivariant = bivariant; var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; // Once we descend into a bivariant signature we remain bivariant for all nested inferences - bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; + bivariant = bivariant || kind === 171 /* SyntaxKind.MethodDeclaration */ || kind === 170 /* SyntaxKind.MethodSignature */ || kind === 173 /* SyntaxKind.Constructor */; applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes); bivariant = saveBivariant; applyToReturnTypes(source, target, inferFromTypes); @@ -70270,7 +70820,7 @@ var ts; } // falls through default: - if (node.parent.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */) { + if (node.parent.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */) { return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; } else { @@ -70291,7 +70841,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 181 /* SyntaxKind.TypeQuery */ ? true : n.kind === 79 /* SyntaxKind.Identifier */ || n.kind === 161 /* SyntaxKind.QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 183 /* SyntaxKind.TypeQuery */ ? true : n.kind === 79 /* SyntaxKind.Identifier */ || n.kind === 163 /* SyntaxKind.QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the @@ -70307,26 +70857,26 @@ var ts; // falls through case 108 /* SyntaxKind.ThisKeyword */: return "0|".concat(flowContainer ? getNodeId(flowContainer) : "-1", "|").concat(getTypeId(declaredType), "|").concat(getTypeId(initialType)); - case 230 /* SyntaxKind.NonNullExpression */: - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 232 /* SyntaxKind.NonNullExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: var left = getFlowCacheKey(node.left, declaredType, initialType, flowContainer); return left && left + "." + node.right.escapedText; - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: var propName = getAccessedPropertyName(node); if (propName !== undefined) { var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); return key && key + "." + propName; } break; - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 202 /* SyntaxKind.ArrayBindingPattern */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 169 /* SyntaxKind.MethodDeclaration */: + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 171 /* SyntaxKind.MethodDeclaration */: // Handle pseudo-references originating in getNarrowedTypeOfSymbol. return "".concat(getNodeId(node), "#").concat(getTypeId(declaredType)); } @@ -70334,16 +70884,16 @@ var ts; } function isMatchingReference(source, target) { switch (target.kind) { - case 212 /* SyntaxKind.ParenthesizedExpression */: - case 230 /* SyntaxKind.NonNullExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: + case 232 /* SyntaxKind.NonNullExpression */: return isMatchingReference(source, target.expression); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return (ts.isAssignmentExpression(target) && isMatchingReference(source, target.left)) || (ts.isBinaryExpression(target) && target.operatorToken.kind === 27 /* SyntaxKind.CommaToken */ && isMatchingReference(source, target.right)); } switch (source.kind) { - case 231 /* SyntaxKind.MetaProperty */: - return target.kind === 231 /* SyntaxKind.MetaProperty */ + case 233 /* SyntaxKind.MetaProperty */: + return target.kind === 233 /* SyntaxKind.MetaProperty */ && source.keywordToken === target.keywordToken && source.name.escapedText === target.name.escapedText; case 79 /* SyntaxKind.Identifier */: @@ -70351,26 +70901,26 @@ var ts; return ts.isThisInTypeQuery(source) ? target.kind === 108 /* SyntaxKind.ThisKeyword */ : target.kind === 79 /* SyntaxKind.Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 254 /* SyntaxKind.VariableDeclaration */ || target.kind === 203 /* SyntaxKind.BindingElement */) && + (target.kind === 257 /* SyntaxKind.VariableDeclaration */ || target.kind === 205 /* SyntaxKind.BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 108 /* SyntaxKind.ThisKeyword */: return target.kind === 108 /* SyntaxKind.ThisKeyword */; case 106 /* SyntaxKind.SuperKeyword */: return target.kind === 106 /* SyntaxKind.SuperKeyword */; - case 230 /* SyntaxKind.NonNullExpression */: - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 232 /* SyntaxKind.NonNullExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return isMatchingReference(source.expression, target); - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: var sourcePropertyName = getAccessedPropertyName(source); var targetPropertyName = ts.isAccessExpression(target) ? getAccessedPropertyName(target) : undefined; return sourcePropertyName !== undefined && targetPropertyName !== undefined && targetPropertyName === sourcePropertyName && isMatchingReference(source.expression, target.expression); - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: return ts.isAccessExpression(target) && source.right.escapedText === getAccessedPropertyName(target) && isMatchingReference(source.left, target.expression); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* SyntaxKind.CommaToken */ && isMatchingReference(source.right, target)); } return false; @@ -70401,7 +70951,7 @@ var ts; } if (ts.isEntityNameExpression(node.argumentExpression)) { var symbol = resolveEntityName(node.argumentExpression, 111551 /* SymbolFlags.Value */, /*ignoreErrors*/ true); - if (!symbol || !isConstVariable(symbol)) + if (!symbol || !(isConstVariable(symbol) || (symbol.flags & 8 /* SymbolFlags.EnumMember */))) return undefined; var declaration = symbol.valueDeclaration; if (declaration === undefined) @@ -70413,9 +70963,14 @@ var ts; return name; } } - if (ts.hasOnlyExpressionInitializer(declaration)) { + if (ts.hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node.argumentExpression)) { var initializer = ts.getEffectiveInitializer(declaration); - return initializer && tryGetNameFromType(getTypeOfExpression(initializer)); + if (initializer) { + return tryGetNameFromType(getTypeOfExpression(initializer)); + } + if (ts.isEnumMember(declaration)) { + return ts.getTextOfPropertyName(declaration.name); + } } } return undefined; @@ -70542,7 +71097,7 @@ var ts; } function getMatchingUnionConstituentForObjectLiteral(unionType, node) { var keyPropertyName = getKeyPropertyName(unionType); - var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 296 /* SyntaxKind.PropertyAssignment */ && + var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 299 /* SyntaxKind.PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); var propType = propNode && getContextFreeTypeOfExpression(propNode.initializer); return propType && getConstituentTypeForKeyType(unionType, propType); @@ -70559,7 +71114,7 @@ var ts; } } } - if (expression.expression.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && + if (expression.expression.kind === 208 /* SyntaxKind.PropertyAccessExpression */ && isOrContainsMatchingReference(reference, expression.expression.expression)) { return true; } @@ -70759,15 +71314,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(65 /* IterationUse.Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 204 /* SyntaxKind.ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 296 /* SyntaxKind.PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 206 /* SyntaxKind.ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 299 /* SyntaxKind.PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 221 /* SyntaxKind.BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 244 /* SyntaxKind.ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 223 /* SyntaxKind.BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 247 /* SyntaxKind.ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -70784,21 +71339,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 243 /* SyntaxKind.ForInStatement */: + case 246 /* SyntaxKind.ForInStatement */: return stringType; - case 244 /* SyntaxKind.ForOfStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return checkRightHandSideOfForOf(parent) || errorType; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 215 /* SyntaxKind.DeleteExpression */: + case 217 /* SyntaxKind.DeleteExpression */: return undefinedType; - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 225 /* SyntaxKind.SpreadElement */: + case 227 /* SyntaxKind.SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -70806,7 +71361,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 201 /* SyntaxKind.ObjectBindingPattern */ ? + var type = pattern.kind === 203 /* SyntaxKind.ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -70824,30 +71379,30 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 243 /* SyntaxKind.ForInStatement */) { + if (node.parent.parent.kind === 246 /* SyntaxKind.ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 244 /* SyntaxKind.ForOfStatement */) { + if (node.parent.parent.kind === 247 /* SyntaxKind.ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 254 /* SyntaxKind.VariableDeclaration */ ? + return node.kind === 257 /* SyntaxKind.VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function isEmptyArrayAssignment(node) { - return node.kind === 254 /* SyntaxKind.VariableDeclaration */ && node.initializer && + return node.kind === 257 /* SyntaxKind.VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 203 /* SyntaxKind.BindingElement */ && node.parent.kind === 221 /* SyntaxKind.BinaryExpression */ && + node.kind !== 205 /* SyntaxKind.BindingElement */ && node.parent.kind === 223 /* SyntaxKind.BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: switch (node.operatorToken.kind) { case 63 /* SyntaxKind.EqualsToken */: case 75 /* SyntaxKind.BarBarEqualsToken */: @@ -70862,13 +71417,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */ || - parent.kind === 221 /* SyntaxKind.BinaryExpression */ && parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */ && parent.left === node || - parent.kind === 221 /* SyntaxKind.BinaryExpression */ && parent.operatorToken.kind === 27 /* SyntaxKind.CommaToken */ && parent.right === node ? + return parent.kind === 214 /* SyntaxKind.ParenthesizedExpression */ || + parent.kind === 223 /* SyntaxKind.BinaryExpression */ && parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */ && parent.left === node || + parent.kind === 223 /* SyntaxKind.BinaryExpression */ && parent.operatorToken.kind === 27 /* SyntaxKind.CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 289 /* SyntaxKind.CaseClause */) { + if (clause.kind === 292 /* SyntaxKind.CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -70887,13 +71442,13 @@ var ts; // Get the type names from all cases in a switch on `typeof`. The default clause and/or duplicate type names are // represented as undefined. Return undefined if one or more case clause expressions are not string literals. function getSwitchClauseTypeOfWitnesses(switchStatement) { - if (ts.some(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 289 /* SyntaxKind.CaseClause */ && !ts.isStringLiteralLike(clause.expression); })) { + if (ts.some(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 292 /* SyntaxKind.CaseClause */ && !ts.isStringLiteralLike(clause.expression); })) { return undefined; } var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - var text = clause.kind === 289 /* SyntaxKind.CaseClause */ ? clause.expression.text : undefined; + var text = clause.kind === 292 /* SyntaxKind.CaseClause */ ? clause.expression.text : undefined; witnesses.push(text && !ts.contains(witnesses, text) ? text : undefined); } return witnesses; @@ -71080,12 +71635,12 @@ var ts; var root = getReferenceRoot(node); var parent = root.parent; var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" || - parent.parent.kind === 208 /* SyntaxKind.CallExpression */ + parent.parent.kind === 210 /* SyntaxKind.CallExpression */ && ts.isIdentifier(parent.name) && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 207 /* SyntaxKind.ElementAccessExpression */ && + var isElementAssignment = parent.kind === 209 /* SyntaxKind.ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 221 /* SyntaxKind.BinaryExpression */ && + parent.parent.kind === 223 /* SyntaxKind.BinaryExpression */ && parent.parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -71098,6 +71653,7 @@ var ts; ts.isInJSFile(node) && ts.hasInitializer(node) && node.initializer && ts.isFunctionExpressionOrArrowFunction(node.initializer) && ts.getEffectiveReturnTypeNode(node.initializer)); } function getExplicitTypeOfSymbol(symbol, diagnostic) { + symbol = resolveSymbol(symbol); if (symbol.flags & (16 /* SymbolFlags.Function */ | 8192 /* SymbolFlags.Method */ | 32 /* SymbolFlags.Class */ | 512 /* SymbolFlags.ValueModule */)) { return getTypeOfSymbol(symbol); } @@ -71113,7 +71669,7 @@ var ts; if (isDeclarationWithExplicitTypeAnnotation(declaration)) { return getTypeOfSymbol(symbol); } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 244 /* SyntaxKind.ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 247 /* SyntaxKind.ForOfStatement */) { var statement = declaration.parent.parent; var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); if (expressionType) { @@ -71136,12 +71692,12 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node)); - return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol, diagnostic); + return getExplicitTypeOfSymbol(symbol, diagnostic); case 108 /* SyntaxKind.ThisKeyword */: return getExplicitThisType(node); case 106 /* SyntaxKind.SuperKeyword */: return checkSuperExpression(node); - case 206 /* SyntaxKind.PropertyAccessExpression */: { + case 208 /* SyntaxKind.PropertyAccessExpression */: { var type = getTypeOfDottedName(node.expression, diagnostic); if (type) { var name = node.name; @@ -71159,7 +71715,7 @@ var ts; } return undefined; } - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return getTypeOfDottedName(node.expression, diagnostic); } } @@ -71173,7 +71729,7 @@ var ts; // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. var funcType = void 0; - if (node.parent.kind === 238 /* SyntaxKind.ExpressionStatement */) { + if (node.parent.kind === 241 /* SyntaxKind.ExpressionStatement */) { funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); } else if (node.expression.kind !== 106 /* SyntaxKind.SuperKeyword */) { @@ -71217,7 +71773,7 @@ var ts; } function isFalseExpression(expr) { var node = ts.skipParentheses(expr, /*excludeJSDocTypeAssertions*/ true); - return node.kind === 95 /* SyntaxKind.FalseKeyword */ || node.kind === 221 /* SyntaxKind.BinaryExpression */ && (node.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + return node.kind === 95 /* SyntaxKind.FalseKeyword */ || node.kind === 223 /* SyntaxKind.BinaryExpression */ && (node.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 56 /* SyntaxKind.BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); } function isReachableFlowNodeWorker(flow, noCacheCheck) { @@ -71338,8 +71894,8 @@ var ts; var symbol = getResolvedSymbol(node); return isConstVariable(symbol) || ts.isParameterOrCatchClauseVariable(symbol) && !isSymbolAssigned(symbol); } - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: // The resolvedSymbol property is initialized by checkPropertyAccess or checkElementAccess before we get here. return isConstantReference(node.expression) && isReadonlySymbol(getNodeLinks(node).resolvedSymbol || unknownSymbol); } @@ -71366,7 +71922,7 @@ var ts; // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. var resultType = ts.getObjectFlags(evolvedType) & 256 /* ObjectFlags.EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); - if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 230 /* SyntaxKind.NonNullExpression */ && !(resultType.flags & 131072 /* TypeFlags.Never */) && getTypeWithFacts(resultType, 2097152 /* TypeFacts.NEUndefinedOrNull */).flags & 131072 /* TypeFlags.Never */) { + if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 232 /* SyntaxKind.NonNullExpression */ && !(resultType.flags & 131072 /* TypeFlags.Never */) && getTypeWithFacts(resultType, 2097152 /* TypeFacts.NEUndefinedOrNull */).flags & 131072 /* TypeFlags.Never */) { return declaredType; } // The non-null unknown type should never escape control flow analysis. @@ -71451,8 +72007,8 @@ var ts; // Check if we should continue with the control flow of the containing function. var container = flow.node; if (container && container !== flowContainer && - reference.kind !== 206 /* SyntaxKind.PropertyAccessExpression */ && - reference.kind !== 207 /* SyntaxKind.ElementAccessExpression */ && + reference.kind !== 208 /* SyntaxKind.PropertyAccessExpression */ && + reference.kind !== 209 /* SyntaxKind.ElementAccessExpression */ && reference.kind !== 108 /* SyntaxKind.ThisKeyword */) { flow = container.flowNode; continue; @@ -71477,7 +72033,7 @@ var ts; } function getInitialOrAssignedType(flow) { var node = flow.node; - return getNarrowableTypeForReference(node.kind === 254 /* SyntaxKind.VariableDeclaration */ || node.kind === 203 /* SyntaxKind.BindingElement */ ? + return getNarrowableTypeForReference(node.kind === 257 /* SyntaxKind.VariableDeclaration */ || node.kind === 205 /* SyntaxKind.BindingElement */ ? getInitialType(node) : getAssignedType(node), reference); } @@ -71517,14 +72073,14 @@ var ts; // in which case we continue control flow analysis back to the function's declaration if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { var init = ts.getDeclaredExpandoInitializer(node); - if (init && (init.kind === 213 /* SyntaxKind.FunctionExpression */ || init.kind === 214 /* SyntaxKind.ArrowFunction */)) { + if (init && (init.kind === 215 /* SyntaxKind.FunctionExpression */ || init.kind === 216 /* SyntaxKind.ArrowFunction */)) { return getTypeAtFlowNode(flow.antecedent); } } return declaredType; } // for (const _ in ref) acts as a nonnull on ref - if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 243 /* SyntaxKind.ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 246 /* SyntaxKind.ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)))); } // Assignment doesn't affect reference @@ -71535,7 +72091,7 @@ var ts; if (node.kind === 95 /* SyntaxKind.FalseKeyword */) { return unreachableNeverType; } - if (node.kind === 221 /* SyntaxKind.BinaryExpression */) { + if (node.kind === 223 /* SyntaxKind.BinaryExpression */) { if (node.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); } @@ -71566,7 +72122,7 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 208 /* SyntaxKind.CallExpression */ ? + var expr = node.kind === 210 /* SyntaxKind.CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -71574,7 +72130,7 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* ObjectFlags.EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 208 /* SyntaxKind.CallExpression */) { + if (node.kind === 210 /* SyntaxKind.CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -71622,15 +72178,15 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (expr.kind === 216 /* SyntaxKind.TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { - type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + else if (expr.kind === 218 /* SyntaxKind.TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { if (strictNullChecks) { if (optionalChainContainsReference(expr, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* TypeFlags.Undefined */ | 131072 /* TypeFlags.Never */)); }); } - else if (expr.kind === 216 /* SyntaxKind.TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + else if (expr.kind === 218 /* SyntaxKind.TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* TypeFlags.Never */ || t.flags & 128 /* TypeFlags.StringLiteral */ && t.value === "undefined"); }); } } @@ -71858,7 +72414,7 @@ var ts; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); - return !(narrowedPropType.flags & 131072 /* TypeFlags.Never */) && areTypesComparable(narrowedPropType, discriminantType); + return !(discriminantType.flags & 131072 /* TypeFlags.Never */) && !(narrowedPropType.flags & 131072 /* TypeFlags.Never */) && areTypesComparable(narrowedPropType, discriminantType); }); } function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) { @@ -71900,18 +72456,26 @@ var ts; } function isTypePresencePossible(type, propName, assumeTrue) { var prop = getPropertyOfType(type, propName); - if (prop) { - return prop.flags & 16777216 /* SymbolFlags.Optional */ ? true : assumeTrue; - } - return getApplicableIndexInfoForName(type, propName) ? true : !assumeTrue; + return prop ? + !!(prop.flags & 16777216 /* SymbolFlags.Optional */) || assumeTrue : + !!getApplicableIndexInfoForName(type, propName) || !assumeTrue; } - function narrowByInKeyword(type, name, assumeTrue) { - if (type.flags & 1048576 /* TypeFlags.Union */ - || type.flags & 524288 /* TypeFlags.Object */ && declaredType !== type && !(declaredType === unknownType && isEmptyAnonymousObjectType(type)) - || ts.isThisTypeParameter(type) - || type.flags & 2097152 /* TypeFlags.Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol && t.symbol !== nodeGlobalThisSymbol; })) { + function narrowTypeByInKeyword(type, nameType, assumeTrue) { + var name = getPropertyNameFromType(nameType); + var isKnownProperty = someType(type, function (t) { return isTypePresencePossible(t, name, /*assumeTrue*/ true); }); + if (isKnownProperty) { + // If the check is for a known property (i.e. a property declared in some constituent of + // the target type), we filter the target type by presence of absence of the property. return filterType(type, function (t) { return isTypePresencePossible(t, name, assumeTrue); }); } + if (assumeTrue) { + // If the check is for an unknown property, we intersect the target type with `Record`, + // where X is the name of the property. + var recordSymbol = getGlobalRecordSymbol(); + if (recordSymbol) { + return getIntersectionType([type, getTypeAliasInstantiation(recordSymbol, [nameType, unknownType])]); + } + } return type; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { @@ -71928,10 +72492,10 @@ var ts; var operator = expr.operatorToken.kind; var left = getReferenceCandidate(expr.left); var right = getReferenceCandidate(expr.right); - if (left.kind === 216 /* SyntaxKind.TypeOfExpression */ && ts.isStringLiteralLike(right)) { + if (left.kind === 218 /* SyntaxKind.TypeOfExpression */ && ts.isStringLiteralLike(right)) { return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (right.kind === 216 /* SyntaxKind.TypeOfExpression */ && ts.isStringLiteralLike(left)) { + if (right.kind === 218 /* SyntaxKind.TypeOfExpression */ && ts.isStringLiteralLike(left)) { return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } if (isMatchingReference(reference, left)) { @@ -71970,15 +72534,14 @@ var ts; return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue); } var target = getReferenceCandidate(expr.right); - var leftType = getTypeOfNode(expr.left); - if (leftType.flags & 128 /* TypeFlags.StringLiteral */) { - var name = ts.escapeLeadingUnderscores(leftType.value); + var leftType = getTypeOfExpression(expr.left); + if (leftType.flags & 8576 /* TypeFlags.StringOrNumberLiteralOrUnique */) { if (containsMissingType(type) && ts.isAccessExpression(reference) && isMatchingReference(reference.expression, target) && - getAccessedPropertyName(reference) === name) { + getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) { return getTypeWithFacts(type, assumeTrue ? 524288 /* TypeFacts.NEUndefined */ : 65536 /* TypeFacts.EQUndefined */); } if (isMatchingReference(reference, target)) { - return narrowByInKeyword(type, name, assumeTrue); + return narrowTypeByInKeyword(type, leftType, assumeTrue); } } break; @@ -72040,24 +72603,11 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (((type.flags & 2 /* TypeFlags.Unknown */) || isEmptyAnonymousObjectType(type) && !(valueType.flags & 98304 /* TypeFlags.Nullable */)) && - assumeTrue && - (operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */ || operator === 37 /* SyntaxKind.ExclamationEqualsEqualsToken */)) { - if (valueType.flags & (131068 /* TypeFlags.Primitive */ | 67108864 /* TypeFlags.NonPrimitive */)) { - return valueType; - } - if (valueType.flags & 524288 /* TypeFlags.Object */) { - return nonPrimitiveType; - } - if (type.flags & 2 /* TypeFlags.Unknown */) { - return type; - } - } + var doubleEquals = operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 35 /* SyntaxKind.ExclamationEqualsToken */; if (valueType.flags & 98304 /* TypeFlags.Nullable */) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 35 /* SyntaxKind.ExclamationEqualsToken */; var facts = doubleEquals ? assumeTrue ? 262144 /* TypeFacts.EQUndefinedOrNull */ : 2097152 /* TypeFacts.NEUndefinedOrNull */ : valueType.flags & 65536 /* TypeFlags.Null */ ? @@ -72066,10 +72616,16 @@ var ts; return getAdjustedTypeWithFacts(type, facts); } if (assumeTrue) { - var filterFn = operator === 34 /* SyntaxKind.EqualsEqualsToken */ ? - function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); } : - function (t) { return areTypesComparable(t, valueType); }; - return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType); + if (!doubleEquals && (type.flags & 2 /* TypeFlags.Unknown */ || someType(type, isEmptyAnonymousObjectType))) { + if (valueType.flags & (131068 /* TypeFlags.Primitive */ | 67108864 /* TypeFlags.NonPrimitive */) || isEmptyAnonymousObjectType(valueType)) { + return valueType; + } + if (valueType.flags & 524288 /* TypeFlags.Object */) { + return nonPrimitiveType; + } + } + var filteredType = filterType(type, function (t) { return areTypesComparable(t, valueType) || doubleEquals && isCoercibleUnderDoubleEquals(t, valueType); }); + return replacePrimitivesWithLiterals(filteredType, valueType); } if (isUnitType(valueType)) { return filterType(type, function (t) { return !(isUnitLikeType(t) && areTypesComparable(t, valueType)); }); @@ -72083,11 +72639,18 @@ var ts; } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + var propertyAccess = getDiscriminantPropertyAccess(typeOfExpr.expression, type); + if (propertyAccess) { + return narrowTypeByDiscriminant(type, propertyAccess, function (t) { return narrowTypeByLiteralExpression(t, literal, assumeTrue); }); + } if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } + return narrowTypeByLiteralExpression(type, literal, assumeTrue); + } + function narrowTypeByLiteralExpression(type, literal, assumeTrue) { return assumeTrue ? narrowTypeByTypeName(type, literal.text) : getTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */); @@ -72167,13 +72730,13 @@ var ts; neverType; }); } - function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + function narrowTypeBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); if (!witnesses) { return type; } // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause. - var defaultIndex = ts.findIndex(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 290 /* SyntaxKind.DefaultClause */; }); + var defaultIndex = ts.findIndex(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 293 /* SyntaxKind.DefaultClause */; }); var hasDefaultClause = clauseStart === clauseEnd || (defaultIndex >= clauseStart && defaultIndex < clauseEnd); if (hasDefaultClause) { // In the default clause we filter constituents down to those that are not-equal to all handled cases. @@ -72377,17 +72940,17 @@ var ts; // falls through case 108 /* SyntaxKind.ThisKeyword */: case 106 /* SyntaxKind.SuperKeyword */: - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return narrowTypeByCallExpression(type, expr, assumeTrue); - case 212 /* SyntaxKind.ParenthesizedExpression */: - case 230 /* SyntaxKind.NonNullExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: + case 232 /* SyntaxKind.NonNullExpression */: return narrowType(type, expr.expression, assumeTrue); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: if (expr.operator === 53 /* SyntaxKind.ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -72436,9 +72999,9 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 262 /* SyntaxKind.ModuleBlock */ || - node.kind === 305 /* SyntaxKind.SourceFile */ || - node.kind === 167 /* SyntaxKind.PropertyDeclaration */; + node.kind === 265 /* SyntaxKind.ModuleBlock */ || + node.kind === 308 /* SyntaxKind.SourceFile */ || + node.kind === 169 /* SyntaxKind.PropertyDeclaration */; }); } // Check if a parameter or catch variable is assigned anywhere @@ -72481,7 +73044,7 @@ var ts; function removeOptionalityFromDeclaredType(declaredType, declaration) { if (pushTypeResolution(declaration.symbol, 2 /* TypeSystemPropertyName.DeclaredType */)) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 164 /* SyntaxKind.Parameter */ && + declaration.kind === 166 /* SyntaxKind.Parameter */ && declaration.initializer && getTypeFacts(declaredType) & 16777216 /* TypeFacts.IsUndefined */ && !(getTypeFacts(checkExpression(declaration.initializer)) & 16777216 /* TypeFacts.IsUndefined */); @@ -72498,10 +73061,10 @@ var ts; // In an element access obj[x], we consider obj to be in a constraint position, except when obj is of // a generic type without a nullable constraint and x is a generic type. This is because when both obj // and x are of generic types T and K, we want the resulting type to be T[K]. - return parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */ || - parent.kind === 161 /* SyntaxKind.QualifiedName */ || - parent.kind === 208 /* SyntaxKind.CallExpression */ && parent.expression === node || - parent.kind === 207 /* SyntaxKind.ElementAccessExpression */ && parent.expression === node && + return parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */ || + parent.kind === 163 /* SyntaxKind.QualifiedName */ || + parent.kind === 210 /* SyntaxKind.CallExpression */ && parent.expression === node || + parent.kind === 209 /* SyntaxKind.ElementAccessExpression */ && parent.expression === node && !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { @@ -72555,15 +73118,15 @@ var ts; }); } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { var target = resolveAlias(symbol); - if (target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */)) { // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled // (because the const enum value will not be inlined), or if (2) the alias is an export // of a const enum declaration that will be preserved. if (compilerOptions.isolatedModules || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || - !isConstEnumOrConstEnumOnlyModule(target)) { + !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -72600,15 +73163,16 @@ var ts; // destructuring from the narrowed parent type. if (ts.isBindingElement(declaration) && !declaration.initializer && !declaration.dotDotDotToken && declaration.parent.elements.length >= 2) { var parent = declaration.parent.parent; - if (parent.kind === 254 /* SyntaxKind.VariableDeclaration */ && ts.getCombinedNodeFlags(declaration) & 2 /* NodeFlags.Const */ || parent.kind === 164 /* SyntaxKind.Parameter */) { + if (parent.kind === 257 /* SyntaxKind.VariableDeclaration */ && ts.getCombinedNodeFlags(declaration) & 2 /* NodeFlags.Const */ || parent.kind === 166 /* SyntaxKind.Parameter */) { var links = getNodeLinks(parent); if (!(links.flags & 268435456 /* NodeCheckFlags.InCheckIdentifier */)) { links.flags |= 268435456 /* NodeCheckFlags.InCheckIdentifier */; var parentType = getTypeForBindingElementParent(parent, 0 /* CheckMode.Normal */); + var parentTypeConstraint = parentType && mapType(parentType, getBaseConstraintOrType); links.flags &= ~268435456 /* NodeCheckFlags.InCheckIdentifier */; - if (parentType && parentType.flags & 1048576 /* TypeFlags.Union */ && !(parent.kind === 164 /* SyntaxKind.Parameter */ && isSymbolAssigned(symbol))) { + if (parentTypeConstraint && parentTypeConstraint.flags & 1048576 /* TypeFlags.Union */ && !(parent.kind === 166 /* SyntaxKind.Parameter */ && isSymbolAssigned(symbol))) { var pattern = declaration.parent; - var narrowedType = getFlowTypeOfReference(pattern, parentType, parentType, /*flowContainer*/ undefined, location.flowNode); + var narrowedType = getFlowTypeOfReference(pattern, parentTypeConstraint, parentTypeConstraint, /*flowContainer*/ undefined, location.flowNode); if (narrowedType.flags & 131072 /* TypeFlags.Never */) { return neverType; } @@ -72675,10 +73239,10 @@ var ts; } var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ScriptTarget.ES2015 */) { - if (container.kind === 214 /* SyntaxKind.ArrowFunction */) { + if (container.kind === 216 /* SyntaxKind.ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } - else if (ts.hasSyntacticModifier(container, 256 /* ModifierFlags.Async */)) { + else if (ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); } } @@ -72698,7 +73262,7 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (declaration.kind === 257 /* SyntaxKind.ClassDeclaration */ + if (declaration.kind === 260 /* SyntaxKind.ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -72710,12 +73274,12 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 226 /* SyntaxKind.ClassExpression */) { + else if (declaration.kind === 228 /* SyntaxKind.ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 305 /* SyntaxKind.SourceFile */) { + while (container.kind !== 308 /* SyntaxKind.SourceFile */) { if (container.parent === declaration) { if (ts.isPropertyDeclaration(container) && ts.isStatic(container) || ts.isClassStaticBlockDeclaration(container)) { getNodeLinks(declaration).flags |= 16777216 /* NodeCheckFlags.ClassWithConstructorReference */; @@ -72773,7 +73337,7 @@ var ts; // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 164 /* SyntaxKind.Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 166 /* SyntaxKind.Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; @@ -72782,19 +73346,19 @@ var ts; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 213 /* SyntaxKind.FunctionExpression */ || - flowContainer.kind === 214 /* SyntaxKind.ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 215 /* SyntaxKind.FunctionExpression */ || + flowContainer.kind === 216 /* SyntaxKind.ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstVariable(localOrExportSymbol) && type !== autoArrayType || isParameter && !isSymbolAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 16384 /* TypeFlags.Void */)) !== 0 || - isInTypeQuery(node) || node.parent.kind === 275 /* SyntaxKind.ExportSpecifier */) || - node.parent.kind === 230 /* SyntaxKind.NonNullExpression */ || - declaration.kind === 254 /* SyntaxKind.VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 278 /* SyntaxKind.ExportSpecifier */) || + node.parent.kind === 232 /* SyntaxKind.NonNullExpression */ || + declaration.kind === 257 /* SyntaxKind.VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 16777216 /* NodeFlags.Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -72819,6 +73383,12 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function isSameScopedBindingElement(node, declaration) { + if (ts.isBindingElement(declaration)) { + var bindingElement = ts.findAncestor(node, ts.isBindingElement); + return bindingElement && ts.getRootDeclaration(bindingElement) === ts.getRootDeclaration(declaration); + } + } function shouldMarkIdentifierAliasReferenced(node) { var _a; var parent = node.parent; @@ -72852,7 +73422,7 @@ var ts; (symbol.flags & (2 /* SymbolFlags.BlockScopedVariable */ | 32 /* SymbolFlags.Class */)) === 0 || !symbol.valueDeclaration || ts.isSourceFile(symbol.valueDeclaration) || - symbol.valueDeclaration.parent.kind === 292 /* SyntaxKind.CatchClause */) { + symbol.valueDeclaration.parent.kind === 295 /* SyntaxKind.CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -72867,7 +73437,7 @@ var ts; // mark iteration statement as containing block-scoped binding captured in some function var capturesBlockScopeBindingInLoopBody = true; if (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 255 /* SyntaxKind.VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 258 /* SyntaxKind.VariableDeclarationList */); if (varDeclList && varDeclList.parent === container) { var part = getPartOfForStatementContainingNode(node.parent, container); if (part) { @@ -72888,7 +73458,7 @@ var ts; // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. if (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 255 /* SyntaxKind.VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 258 /* SyntaxKind.VariableDeclarationList */); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NodeCheckFlags.NeedsLoopOutParameter */; } @@ -72907,7 +73477,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */) { + while (current.parent.kind === 214 /* SyntaxKind.ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -72915,7 +73485,7 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 219 /* SyntaxKind.PrefixUnaryExpression */ || current.parent.kind === 220 /* SyntaxKind.PostfixUnaryExpression */)) { + else if ((current.parent.kind === 221 /* SyntaxKind.PrefixUnaryExpression */ || current.parent.kind === 222 /* SyntaxKind.PostfixUnaryExpression */)) { var expr = current.parent; isAssigned = expr.operator === 45 /* SyntaxKind.PlusPlusToken */ || expr.operator === 46 /* SyntaxKind.MinusMinusToken */; } @@ -72928,7 +73498,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* NodeCheckFlags.LexicalThis */; - if (container.kind === 167 /* SyntaxKind.PropertyDeclaration */ || container.kind === 171 /* SyntaxKind.Constructor */) { + if (container.kind === 169 /* SyntaxKind.PropertyDeclaration */ || container.kind === 173 /* SyntaxKind.Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* NodeCheckFlags.CaptureThis */; } @@ -72975,31 +73545,31 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var capturedByArrowFunction = false; - if (container.kind === 171 /* SyntaxKind.Constructor */) { + if (container.kind === 173 /* SyntaxKind.Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 214 /* SyntaxKind.ArrowFunction */) { + if (container.kind === 216 /* SyntaxKind.ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); capturedByArrowFunction = true; } checkThisInStaticClassFieldInitializerInDecoratedClass(node, container); switch (container.kind) { - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -73010,7 +73580,7 @@ var ts; var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container); if (noImplicitThis) { var globalThisType_1 = getTypeOfSymbol(globalThisSymbol); - if (type === globalThisType_1 && capturedByArrowFunction) { + if ((type === globalThisType_1 || type === getTypeOfSymbol(nodeGlobalThisSymbol)) && capturedByArrowFunction) { error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this); } else if (!type) { @@ -73090,7 +73660,7 @@ var ts; } function getClassNameFromPrototypeMethod(container) { // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 213 /* SyntaxKind.FunctionExpression */ && + if (container.kind === 215 /* SyntaxKind.FunctionExpression */ && ts.isBinaryExpression(container.parent) && ts.getAssignmentDeclarationKind(container.parent) === 3 /* AssignmentDeclarationKind.PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = container' @@ -73100,16 +73670,16 @@ var ts; .expression; // x } // x.prototype = { method() { } } - else if (container.kind === 169 /* SyntaxKind.MethodDeclaration */ && - container.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */ && + else if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && + container.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */ && ts.isBinaryExpression(container.parent.parent) && ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* AssignmentDeclarationKind.Prototype */) { return container.parent.parent.left.expression; } // x.prototype = { method: function() { } } - else if (container.kind === 213 /* SyntaxKind.FunctionExpression */ && - container.parent.kind === 296 /* SyntaxKind.PropertyAssignment */ && - container.parent.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */ && + else if (container.kind === 215 /* SyntaxKind.FunctionExpression */ && + container.parent.kind === 299 /* SyntaxKind.PropertyAssignment */ && + container.parent.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */ && ts.isBinaryExpression(container.parent.parent.parent) && ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* AssignmentDeclarationKind.Prototype */) { return container.parent.parent.parent.left.expression; @@ -73117,7 +73687,7 @@ var ts; // Object.defineProperty(x, "method", { value: function() { } }); // Object.defineProperty(x, "method", { set: (x: () => void) => void }); // Object.defineProperty(x, "method", { get: () => function() { }) }); - else if (container.kind === 213 /* SyntaxKind.FunctionExpression */ && + else if (container.kind === 215 /* SyntaxKind.FunctionExpression */ && ts.isPropertyAssignment(container.parent) && ts.isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && @@ -73142,7 +73712,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 317 /* SyntaxKind.JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 320 /* SyntaxKind.JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -73156,19 +73726,24 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 164 /* SyntaxKind.Parameter */ && n.parent === constructorDecl; }); + return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 166 /* SyntaxKind.Parameter */ && n.parent === constructorDecl; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 208 /* SyntaxKind.CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 210 /* SyntaxKind.CallExpression */ && node.parent.expression === node; var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var container = immediateContainer; var needToCaptureLexicalThis = false; + var inAsyncFunction = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 214 /* SyntaxKind.ArrowFunction */) { + while (container && container.kind === 216 /* SyntaxKind.ArrowFunction */) { + if (ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ScriptTarget.ES2015 */; } + if (container && ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; @@ -73178,14 +73753,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 162 /* SyntaxKind.ComputedPropertyName */; }); - if (current && current.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 164 /* SyntaxKind.ComputedPropertyName */; }); + if (current && current.kind === 164 /* SyntaxKind.ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -73193,7 +73768,7 @@ var ts; } return errorType; } - if (!isCallExpression && immediateContainer.kind === 171 /* SyntaxKind.Constructor */) { + if (!isCallExpression && immediateContainer.kind === 173 /* SyntaxKind.Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.isStatic(container) || isCallExpression) { @@ -73274,12 +73849,12 @@ var ts; // as a call expression cannot be used as the target of a destructuring assignment while a property access can. // // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. - if (container.kind === 169 /* SyntaxKind.MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* ModifierFlags.Async */)) { + if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && inAsyncFunction) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */; + getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */; } else { - getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.AsyncMethodWithSuper */; + getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */; } } if (needToCaptureLexicalThis) { @@ -73288,7 +73863,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { + if (container.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) { if (languageVersion < 2 /* ScriptTarget.ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -73309,7 +73884,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 171 /* SyntaxKind.Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 173 /* SyntaxKind.Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return errorType; @@ -73324,7 +73899,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 171 /* SyntaxKind.Constructor */; + return container.kind === 173 /* SyntaxKind.Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -73332,23 +73907,23 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) { if (ts.isStatic(container)) { - return container.kind === 169 /* SyntaxKind.MethodDeclaration */ || - container.kind === 168 /* SyntaxKind.MethodSignature */ || - container.kind === 172 /* SyntaxKind.GetAccessor */ || - container.kind === 173 /* SyntaxKind.SetAccessor */ || - container.kind === 167 /* SyntaxKind.PropertyDeclaration */ || - container.kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */; + return container.kind === 171 /* SyntaxKind.MethodDeclaration */ || + container.kind === 170 /* SyntaxKind.MethodSignature */ || + container.kind === 174 /* SyntaxKind.GetAccessor */ || + container.kind === 175 /* SyntaxKind.SetAccessor */ || + container.kind === 169 /* SyntaxKind.PropertyDeclaration */ || + container.kind === 172 /* SyntaxKind.ClassStaticBlockDeclaration */; } else { - return container.kind === 169 /* SyntaxKind.MethodDeclaration */ || - container.kind === 168 /* SyntaxKind.MethodSignature */ || - container.kind === 172 /* SyntaxKind.GetAccessor */ || - container.kind === 173 /* SyntaxKind.SetAccessor */ || - container.kind === 167 /* SyntaxKind.PropertyDeclaration */ || - container.kind === 166 /* SyntaxKind.PropertySignature */ || - container.kind === 171 /* SyntaxKind.Constructor */; + return container.kind === 171 /* SyntaxKind.MethodDeclaration */ || + container.kind === 170 /* SyntaxKind.MethodSignature */ || + container.kind === 174 /* SyntaxKind.GetAccessor */ || + container.kind === 175 /* SyntaxKind.SetAccessor */ || + container.kind === 169 /* SyntaxKind.PropertyDeclaration */ || + container.kind === 168 /* SyntaxKind.PropertySignature */ || + container.kind === 173 /* SyntaxKind.Constructor */; } } } @@ -73356,10 +73931,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 169 /* SyntaxKind.MethodDeclaration */ || - func.kind === 172 /* SyntaxKind.GetAccessor */ || - func.kind === 173 /* SyntaxKind.SetAccessor */) && func.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */ ? func.parent : - func.kind === 213 /* SyntaxKind.FunctionExpression */ && func.parent.kind === 296 /* SyntaxKind.PropertyAssignment */ ? func.parent.parent : + return (func.kind === 171 /* SyntaxKind.MethodDeclaration */ || + func.kind === 174 /* SyntaxKind.GetAccessor */ || + func.kind === 175 /* SyntaxKind.SetAccessor */) && func.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */ ? func.parent : + func.kind === 215 /* SyntaxKind.FunctionExpression */ && func.parent.kind === 299 /* SyntaxKind.PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -73371,7 +73946,7 @@ var ts; }); } function getContextualThisParameterType(func) { - if (func.kind === 214 /* SyntaxKind.ArrowFunction */) { + if (func.kind === 216 /* SyntaxKind.ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -73398,7 +73973,7 @@ var ts; if (thisType) { return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); } - if (literal.parent.kind !== 296 /* SyntaxKind.PropertyAssignment */) { + if (literal.parent.kind !== 299 /* SyntaxKind.PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -73412,7 +73987,7 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = ts.walkUpParenthesizedExpressions(func.parent); - if (parent.kind === 221 /* SyntaxKind.BinaryExpression */ && parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { + if (parent.kind === 223 /* SyntaxKind.BinaryExpression */ && parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { var target = parent.left; if (ts.isAccessExpression(target)) { var expression = target.expression; @@ -73465,11 +74040,11 @@ var ts; return getTypeFromTypeNode(typeNode); } switch (declaration.kind) { - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return getContextuallyTypedParameterType(declaration); - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: return getContextualTypeForBindingElement(declaration, contextFlags); - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: if (ts.isStatic(declaration)) { return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags); } @@ -73480,10 +74055,10 @@ var ts; var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || - parent.kind !== 203 /* SyntaxKind.BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 64 /* CheckMode.RestBindingElement */ : 0 /* CheckMode.Normal */); + parent.kind !== 205 /* SyntaxKind.BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 64 /* CheckMode.RestBindingElement */ : 0 /* CheckMode.Normal */); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; - if (parent.name.kind === 202 /* SyntaxKind.ArrayBindingPattern */) { + if (parent.name.kind === 204 /* SyntaxKind.ArrayBindingPattern */) { var index = ts.indexOfNode(declaration.parent.elements, declaration); if (index < 0) return undefined; @@ -73640,7 +74215,7 @@ var ts; getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 210 /* SyntaxKind.TaggedTemplateExpression */) { + if (template.parent.kind === 212 /* SyntaxKind.TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -73759,9 +74334,11 @@ var ts; case 1 /* AssignmentDeclarationKind.ExportsProperty */: case 6 /* AssignmentDeclarationKind.Prototype */: case 3 /* AssignmentDeclarationKind.PrototypeProperty */: - var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; - // falls through case 2 /* AssignmentDeclarationKind.ModuleExports */: + var valueDeclaration = void 0; + if (kind !== 2 /* AssignmentDeclarationKind.ModuleExports */) { + valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + } valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); return annotated ? getTypeFromTypeNode(annotated) : undefined; @@ -73938,21 +74515,21 @@ var ts; case 95 /* SyntaxKind.FalseKeyword */: case 104 /* SyntaxKind.NullKeyword */: case 79 /* SyntaxKind.Identifier */: - case 153 /* SyntaxKind.UndefinedKeyword */: + case 155 /* SyntaxKind.UndefinedKeyword */: return true; - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); - case 288 /* SyntaxKind.JsxExpression */: + case 291 /* SyntaxKind.JsxExpression */: return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } function discriminateContextualTypeByObjectMembers(node, contextualType) { - return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 296 /* SyntaxKind.PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* SymbolFlags.Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 299 /* SyntaxKind.PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* SymbolFlags.Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 285 /* SyntaxKind.JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return getContextFreeTypeOfExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* SymbolFlags.Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 288 /* SyntaxKind.JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return getContextFreeTypeOfExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* SymbolFlags.Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -73973,9 +74550,10 @@ var ts; function instantiateContextualType(contextualType, node, contextFlags) { if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* TypeFlags.Instantiable */)) { var inferenceContext = getInferenceContext(node); - // If no inferences have been made, nothing is gained from instantiating as type parameters - // would just be replaced with their defaults similar to the apparent type. - if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + // If no inferences have been made, and none of the type parameters for which we are inferring + // specify default types, nothing is gained from instantiating as type parameters would just be + // replaced with their constraints similar to the apparent type. + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) { // For contextual signatures we incorporate all inferences made so far, e.g. from return // types as well as arguments to the left in a function call. return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); @@ -74035,60 +74613,62 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: - case 164 /* SyntaxKind.Parameter */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 203 /* SyntaxKind.BindingElement */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 166 /* SyntaxKind.Parameter */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 205 /* SyntaxKind.BindingElement */: return getContextualTypeForInitializerExpression(node, contextFlags); - case 214 /* SyntaxKind.ArrowFunction */: - case 247 /* SyntaxKind.ReturnStatement */: + case 216 /* SyntaxKind.ArrowFunction */: + case 250 /* SyntaxKind.ReturnStatement */: return getContextualTypeForReturnExpression(node, contextFlags); - case 224 /* SyntaxKind.YieldExpression */: + case 226 /* SyntaxKind.YieldExpression */: return getContextualTypeForYieldOperand(parent, contextFlags); - case 218 /* SyntaxKind.AwaitExpression */: + case 220 /* SyntaxKind.AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: return getContextualTypeForArgument(parent, node); - case 211 /* SyntaxKind.TypeAssertionExpression */: - case 229 /* SyntaxKind.AsExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: + case 231 /* SyntaxKind.AsExpression */: return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return getContextualTypeForBinaryOperand(node, contextFlags); - case 296 /* SyntaxKind.PropertyAssignment */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent, contextFlags); - case 298 /* SyntaxKind.SpreadAssignment */: + case 301 /* SyntaxKind.SpreadAssignment */: return getContextualType(parent.parent, contextFlags); - case 204 /* SyntaxKind.ArrayLiteralExpression */: { + case 206 /* SyntaxKind.ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 222 /* SyntaxKind.ConditionalExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: return getContextualTypeForConditionalOperand(node, contextFlags); - case 233 /* SyntaxKind.TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 223 /* SyntaxKind.TemplateExpression */); + case 236 /* SyntaxKind.TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 225 /* SyntaxKind.TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 212 /* SyntaxKind.ParenthesizedExpression */: { + case 214 /* SyntaxKind.ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return !tag ? getContextualType(parent, contextFlags) : ts.isJSDocTypeTag(tag) && ts.isConstTypeReference(tag.typeExpression.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(tag.typeExpression.type); } - case 230 /* SyntaxKind.NonNullExpression */: + case 232 /* SyntaxKind.NonNullExpression */: return getContextualType(parent, contextFlags); - case 271 /* SyntaxKind.ExportAssignment */: + case 235 /* SyntaxKind.SatisfiesExpression */: + return getTypeFromTypeNode(parent.type); + case 274 /* SyntaxKind.ExportAssignment */: return tryGetTypeFromEffectiveTypeNode(parent); - case 288 /* SyntaxKind.JsxExpression */: + case 291 /* SyntaxKind.JsxExpression */: return getContextualTypeForJsxExpression(parent, contextFlags); - case 285 /* SyntaxKind.JsxAttribute */: - case 287 /* SyntaxKind.JsxSpreadAttribute */: + case 288 /* SyntaxKind.JsxAttribute */: + case 290 /* SyntaxKind.JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent, contextFlags); - case 280 /* SyntaxKind.JsxOpeningElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; @@ -74214,9 +74794,16 @@ var ts; if (!isErrorType(intrinsicClassAttribs)) { var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); var hostClassType = getReturnTypeOfSignature(sig); - apparentAttributesType = intersectTypes(typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context))) - : intrinsicClassAttribs, apparentAttributesType); + var libraryManagedAttributeType = void 0; + if (typeParams) { + // apply JSX.IntrinsicClassElements + var inferredArgs = fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)); + libraryManagedAttributeType = instantiateType(intrinsicClassAttribs, createTypeMapper(typeParams, inferredArgs)); + } + // or JSX.IntrinsicClassElements has no generics. + else + libraryManagedAttributeType = intrinsicClassAttribs; + apparentAttributesType = intersectTypes(libraryManagedAttributeType, apparentAttributesType); } var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (!isErrorType(intrinsicAttribs)) { @@ -74339,7 +74926,7 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 169 /* SyntaxKind.MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 171 /* SyntaxKind.MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -74387,8 +74974,8 @@ var ts; return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type; } function hasDefaultValue(node) { - return (node.kind === 203 /* SyntaxKind.BindingElement */ && !!node.initializer) || - (node.kind === 221 /* SyntaxKind.BinaryExpression */ && node.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */); + return (node.kind === 205 /* SyntaxKind.BindingElement */ && !!node.initializer) || + (node.kind === 223 /* SyntaxKind.BinaryExpression */ && node.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */); } function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; @@ -74401,7 +74988,7 @@ var ts; var hasOmittedExpression = false; for (var i = 0; i < elementCount; i++) { var e = elements[i]; - if (e.kind === 225 /* SyntaxKind.SpreadElement */) { + if (e.kind === 227 /* SyntaxKind.SpreadElement */) { if (languageVersion < 2 /* ScriptTarget.ES2015 */) { checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* ExternalEmitHelpers.SpreadIncludes */ : 1024 /* ExternalEmitHelpers.SpreadArray */); } @@ -74434,7 +75021,7 @@ var ts; elementFlags.push(4 /* ElementFlags.Rest */); } } - else if (exactOptionalPropertyTypes && e.kind === 227 /* SyntaxKind.OmittedExpression */) { + else if (exactOptionalPropertyTypes && e.kind === 229 /* SyntaxKind.OmittedExpression */) { hasOmittedExpression = true; elementTypes.push(missingType); elementFlags.push(2 /* ElementFlags.Optional */); @@ -74474,7 +75061,7 @@ var ts; } function isNumericName(name) { switch (name.kind) { - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: return isNumericComputedName(name); case 79 /* SyntaxKind.Identifier */: return ts.isNumericLiteralName(name.escapedText); @@ -74495,7 +75082,7 @@ var ts; if (!links.resolvedType) { if ((ts.isTypeLiteralNode(node.parent.parent) || ts.isClassLike(node.parent.parent) || ts.isInterfaceDeclaration(node.parent.parent)) && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* SyntaxKind.InKeyword */ - && node.parent.kind !== 172 /* SyntaxKind.GetAccessor */ && node.parent.kind !== 173 /* SyntaxKind.SetAccessor */) { + && node.parent.kind !== 174 /* SyntaxKind.GetAccessor */ && node.parent.kind !== 175 /* SyntaxKind.SetAccessor */) { return links.resolvedType = errorType; } links.resolvedType = checkExpression(node.expression); @@ -74568,7 +75155,7 @@ var ts; var spread = emptyObjectType; var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 201 /* SyntaxKind.ObjectBindingPattern */ || contextualType.pattern.kind === 205 /* SyntaxKind.ObjectLiteralExpression */); + (contextualType.pattern.kind === 203 /* SyntaxKind.ObjectBindingPattern */ || contextualType.pattern.kind === 207 /* SyntaxKind.ObjectLiteralExpression */); var inConstContext = isConstContext(node); var checkFlags = inConstContext ? 8 /* CheckFlags.Readonly */ : 0; var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); @@ -74592,16 +75179,16 @@ var ts; for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var memberDecl = _c[_b]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 162 /* SyntaxKind.ComputedPropertyName */ ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 164 /* SyntaxKind.ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 296 /* SyntaxKind.PropertyAssignment */ || - memberDecl.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || + if (memberDecl.kind === 299 /* SyntaxKind.PropertyAssignment */ || + memberDecl.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 296 /* SyntaxKind.PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + var type = memberDecl.kind === 299 /* SyntaxKind.PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. // we don't want to say "could not find 'a'". - memberDecl.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : + memberDecl.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); @@ -74624,8 +75211,8 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 296 /* SyntaxKind.PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 299 /* SyntaxKind.PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* SymbolFlags.Optional */; } @@ -74651,14 +75238,14 @@ var ts; member = prop; allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop); if (contextualType && checkMode && checkMode & 2 /* CheckMode.Inferential */ && !(checkMode & 4 /* CheckMode.SkipContextSensitive */) && - (memberDecl.kind === 296 /* SyntaxKind.PropertyAssignment */ || memberDecl.kind === 169 /* SyntaxKind.MethodDeclaration */) && isContextSensitive(memberDecl)) { + (memberDecl.kind === 299 /* SyntaxKind.PropertyAssignment */ || memberDecl.kind === 171 /* SyntaxKind.MethodDeclaration */) && isContextSensitive(memberDecl)) { var inferenceContext = getInferenceContext(node); ts.Debug.assert(inferenceContext); // In CheckMode.Inferential we should always have an inference context - var inferenceNode = memberDecl.kind === 296 /* SyntaxKind.PropertyAssignment */ ? memberDecl.initializer : memberDecl; + var inferenceNode = memberDecl.kind === 299 /* SyntaxKind.PropertyAssignment */ ? memberDecl.initializer : memberDecl; addIntraExpressionInferenceSite(inferenceContext, inferenceNode, type); } } - else if (memberDecl.kind === 298 /* SyntaxKind.SpreadAssignment */) { + else if (memberDecl.kind === 301 /* SyntaxKind.SpreadAssignment */) { if (languageVersion < 2 /* ScriptTarget.ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* ExternalEmitHelpers.Assign */); } @@ -74694,7 +75281,7 @@ var ts; // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 172 /* SyntaxKind.GetAccessor */ || memberDecl.kind === 173 /* SyntaxKind.SetAccessor */); + ts.Debug.assert(memberDecl.kind === 174 /* SyntaxKind.GetAccessor */ || memberDecl.kind === 175 /* SyntaxKind.SetAccessor */); checkNodeDeferred(memberDecl); } if (computedNameType && !(computedNameType.flags & 8576 /* TypeFlags.StringOrNumberLiteralOrUnique */)) { @@ -74721,16 +75308,30 @@ var ts; // If object literal is contextually typed by the implied type of a binding pattern, augment the result // type with those properties for which the binding pattern specifies a default value. // If the object literal is spread into another object literal, skip this step and let the top-level object - // literal handle it instead. - if (contextualTypeHasPattern && node.parent.kind !== 298 /* SyntaxKind.SpreadAssignment */) { - for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) { - var prop = _e[_d]; - if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { - if (!(prop.flags & 16777216 /* SymbolFlags.Optional */)) { - error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + // literal handle it instead. Note that this might require full traversal to the root pattern's parent + // as it's the guaranteed to be the common ancestor of the pattern node and the current object node. + // It's not possible to check if the immediate parent node is a spread assignment + // since the type flows in non-obvious ways through conditional expressions, IIFEs and more. + if (contextualTypeHasPattern) { + var rootPatternParent_1 = ts.findAncestor(contextualType.pattern.parent, function (n) { + return n.kind === 257 /* SyntaxKind.VariableDeclaration */ || + n.kind === 223 /* SyntaxKind.BinaryExpression */ || + n.kind === 166 /* SyntaxKind.Parameter */; + }); + var spreadOrOutsideRootObject = ts.findAncestor(node, function (n) { + return n === rootPatternParent_1 || + n.kind === 301 /* SyntaxKind.SpreadAssignment */; + }); + if (spreadOrOutsideRootObject.kind !== 301 /* SyntaxKind.SpreadAssignment */) { + for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) { + var prop = _e[_d]; + if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { + if (!(prop.flags & 16777216 /* SymbolFlags.Optional */)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); } - propertiesTable.set(prop.escapedName, prop); - propertiesArray.push(prop); } } } @@ -74838,6 +75439,7 @@ var ts; */ function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; + var attributesType = getContextualType(attributes, 0 /* ContextFlags.None */); var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined; var attributesTable = ts.createSymbolTable(); var spread = emptyJsxObjectType; @@ -74865,9 +75467,15 @@ var ts; if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { explicitlySpecifyChildrenAttribute = true; } + if (attributesType) { + var prop = getPropertyOfType(attributesType, member.escapedName); + if (prop && prop.declarations && isDeprecatedSymbol(prop)) { + addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText); + } + } } else { - ts.Debug.assert(attributeDecl.kind === 287 /* SyntaxKind.JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 290 /* SyntaxKind.JsxSpreadAttribute */); if (attributesTable.size > 0) { spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); @@ -74894,7 +75502,7 @@ var ts; } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 278 /* SyntaxKind.JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 281 /* SyntaxKind.JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -74951,7 +75559,7 @@ var ts; childrenTypes.push(stringType); } } - else if (child.kind === 288 /* SyntaxKind.JsxExpression */ && !child.expression) { + else if (child.kind === 291 /* SyntaxKind.JsxExpression */ && !child.expression) { continue; // empty jsx expressions don't *really* count as present children } else { @@ -75383,9 +75991,9 @@ var ts; function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError) { if (reportError === void 0) { reportError = true; } var errorNode = !reportError ? undefined : - node.kind === 161 /* SyntaxKind.QualifiedName */ ? node.right : - node.kind === 200 /* SyntaxKind.ImportType */ ? node : - node.kind === 203 /* SyntaxKind.BindingElement */ && node.propertyName ? node.propertyName : node.name; + node.kind === 163 /* SyntaxKind.QualifiedName */ ? node.right : + node.kind === 202 /* SyntaxKind.ImportType */ ? node : + node.kind === 205 /* SyntaxKind.BindingElement */ && node.propertyName ? node.propertyName : node.name; return checkPropertyAccessibilityAtLocation(node, isSuper, writing, type, prop, errorNode); } /** @@ -75416,7 +76024,7 @@ var ts; return false; } } - if (flags & 128 /* ModifierFlags.Abstract */) { + if (flags & 256 /* ModifierFlags.Abstract */) { // A method cannot be accessed in a super property access if the method is abstract. // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an @@ -75428,7 +76036,7 @@ var ts; } } // Referencing abstract properties within their own constructors is not allowed - if ((flags & 128 /* ModifierFlags.Abstract */) && symbolHasNonMethodDeclaration(prop) && + if ((flags & 256 /* ModifierFlags.Abstract */) && symbolHasNonMethodDeclaration(prop) && (ts.isThisProperty(location) || ts.isThisInitializedObjectBindingExpression(location) || ts.isObjectBindingPattern(location.parent) && ts.isThisInitializedDeclaration(location.parent.parent))) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(location)) { @@ -75522,10 +76130,27 @@ var ts; return isNullableType(type) ? getNonNullableType(type) : type; } function reportObjectPossiblyNullOrUndefinedError(node, facts) { - error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); + var nodeText = ts.isEntityNameExpression(node) ? ts.entityNameToString(node) : undefined; + if (node.kind === 104 /* SyntaxKind.NullKeyword */) { + error(node, ts.Diagnostics.The_value_0_cannot_be_used_here, "null"); + return; + } + if (nodeText !== undefined && nodeText.length < 100) { + if (ts.isIdentifier(node) && nodeText === "undefined") { + error(node, ts.Diagnostics.The_value_0_cannot_be_used_here, "undefined"); + return; + } + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? + ts.Diagnostics._0_is_possibly_null_or_undefined : + ts.Diagnostics._0_is_possibly_undefined : + ts.Diagnostics._0_is_possibly_null, nodeText); + } + else { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } } function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) { error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? @@ -75535,6 +76160,13 @@ var ts; } function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* TypeFlags.Unknown */) { + if (ts.isEntityNameExpression(node)) { + var nodeText = ts.entityNameToString(node); + if (nodeText.length < 100) { + error(node, ts.Diagnostics._0_is_of_type_unknown, nodeText); + return errorType; + } + } error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } @@ -75552,6 +76184,17 @@ var ts; function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType.flags & 16384 /* TypeFlags.Void */) { + if (ts.isEntityNameExpression(node)) { + var nodeText = ts.entityNameToString(node); + if (ts.isIdentifier(node) && nodeText === "undefined") { + error(node, ts.Diagnostics.The_value_0_cannot_be_used_here, nodeText); + return nonNullType; + } + if (nodeText.length < 100) { + error(node, ts.Diagnostics._0_is_possibly_undefined, nodeText); + return nonNullType; + } + } error(node, ts.Diagnostics.Object_is_possibly_undefined); } return nonNullType; @@ -75570,7 +76213,7 @@ var ts; return checkPropertyAccessExpressionOrQualifiedName(node, node.left, leftType, node.right, checkMode); } function isMethodAccessForCall(node) { - while (node.parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */) { + while (node.parent.kind === 214 /* SyntaxKind.ParenthesizedExpression */) { node = node.parent; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; @@ -75710,7 +76353,7 @@ var ts; } return isErrorType(apparentType) ? errorType : apparentType; } - prop = getPropertyOfType(apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ node.kind === 161 /* SyntaxKind.QualifiedName */); + prop = getPropertyOfType(apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ node.kind === 163 /* SyntaxKind.QualifiedName */); } // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. // `Foo` is also not referenced in `enum FooCopy { Bar = Foo.Bar }`, because the enum member value gets inlined @@ -75720,7 +76363,7 @@ var ts; // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || - !(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & 8 /* SymbolFlags.EnumMember */ && node.parent.kind === 299 /* SyntaxKind.EnumMember */)) || + !(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & 8 /* SymbolFlags.EnumMember */ && node.parent.kind === 302 /* SyntaxKind.EnumMember */)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } @@ -75827,7 +76470,7 @@ var ts; if (declaration && isPropertyWithoutInitializer(declaration)) { if (!ts.isStatic(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 171 /* SyntaxKind.Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 16777216 /* NodeFlags.Ambient */)) { + if (flowContainer.kind === 173 /* SyntaxKind.Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 16777216 /* NodeFlags.Ambient */)) { assumeUninitialized = true; } } @@ -75862,8 +76505,8 @@ var ts; && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 257 /* SyntaxKind.ClassDeclaration */ && - node.parent.kind !== 178 /* SyntaxKind.TypeReference */ && + else if (valueDeclaration.kind === 260 /* SyntaxKind.ClassDeclaration */ && + node.parent.kind !== 180 /* SyntaxKind.TypeReference */ && !(valueDeclaration.flags & 16777216 /* NodeFlags.Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -75875,25 +76518,25 @@ var ts; function isInPropertyInitializerOrClassStaticBlock(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: return true; - case 296 /* SyntaxKind.PropertyAssignment */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 298 /* SyntaxKind.SpreadAssignment */: - case 162 /* SyntaxKind.ComputedPropertyName */: - case 233 /* SyntaxKind.TemplateSpan */: - case 288 /* SyntaxKind.JsxExpression */: - case 285 /* SyntaxKind.JsxAttribute */: - case 286 /* SyntaxKind.JsxAttributes */: - case 287 /* SyntaxKind.JsxSpreadAttribute */: - case 280 /* SyntaxKind.JsxOpeningElement */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: - case 291 /* SyntaxKind.HeritageClause */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 301 /* SyntaxKind.SpreadAssignment */: + case 164 /* SyntaxKind.ComputedPropertyName */: + case 236 /* SyntaxKind.TemplateSpan */: + case 291 /* SyntaxKind.JsxExpression */: + case 288 /* SyntaxKind.JsxAttribute */: + case 289 /* SyntaxKind.JsxAttributes */: + case 290 /* SyntaxKind.JsxSpreadAttribute */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: + case 294 /* SyntaxKind.HeritageClause */: return false; - case 214 /* SyntaxKind.ArrowFunction */: - case 238 /* SyntaxKind.ExpressionStatement */: + case 216 /* SyntaxKind.ArrowFunction */: + case 241 /* SyntaxKind.ExpressionStatement */: return ts.isBlock(node.parent) && ts.isClassStaticBlockDeclaration(node.parent.parent) ? true : "quit"; default: return ts.isExpressionNode(node) ? false : "quit"; @@ -76088,7 +76731,6 @@ var ts; } return false; } - ; var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get"; if (!hasProp(suggestedMethod)) { return undefined; @@ -76168,11 +76810,11 @@ var ts; } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return isValidPropertyAccessWithType(node, node.expression.kind === 106 /* SyntaxKind.SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 200 /* SyntaxKind.ImportType */: + case 202 /* SyntaxKind.ImportType */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } @@ -76187,7 +76829,7 @@ var ts; * @param property the accessed property's symbol. */ function isValidPropertyAccessForCompletions(node, type, property) { - return isPropertyAccessible(node, node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && node.expression.kind === 106 /* SyntaxKind.SuperKeyword */, + return isPropertyAccessible(node, node.kind === 208 /* SyntaxKind.PropertyAccessExpression */ && node.expression.kind === 106 /* SyntaxKind.SuperKeyword */, /* isWrite */ false, type, property); // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context. } @@ -76227,7 +76869,7 @@ var ts; */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (initializer.kind === 258 /* SyntaxKind.VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -76256,7 +76898,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 243 /* SyntaxKind.ForInStatement */ && + if (node.kind === 246 /* SyntaxKind.ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -76305,13 +76947,13 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 210 /* SyntaxKind.TaggedTemplateExpression */) { + if (node.kind === 212 /* SyntaxKind.TaggedTemplateExpression */) { checkExpression(node.template); } else if (ts.isJsxOpeningLikeElement(node)) { checkExpression(node.attributes); } - else if (node.kind !== 165 /* SyntaxKind.Decorator */) { + else if (node.kind !== 167 /* SyntaxKind.Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -76375,7 +77017,7 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 225 /* SyntaxKind.SpreadElement */ || arg.kind === 232 /* SyntaxKind.SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 227 /* SyntaxKind.SpreadElement */ || arg.kind === 234 /* SyntaxKind.SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); @@ -76392,9 +77034,9 @@ var ts; var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var effectiveParameterCount = getParameterCount(signature); var effectiveMinimumArguments = getMinArgumentCount(signature); - if (node.kind === 210 /* SyntaxKind.TaggedTemplateExpression */) { + if (node.kind === 212 /* SyntaxKind.TaggedTemplateExpression */) { argCount = args.length; - if (node.template.kind === 223 /* SyntaxKind.TemplateExpression */) { + if (node.template.kind === 225 /* SyntaxKind.TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -76409,7 +77051,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 165 /* SyntaxKind.Decorator */) { + else if (node.kind === 167 /* SyntaxKind.Decorator */) { argCount = getDecoratorArgumentCount(node, signature); } else if (ts.isJsxOpeningLikeElement(node)) { @@ -76423,7 +77065,7 @@ var ts; } else if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 209 /* SyntaxKind.NewExpression */); + ts.Debug.assert(node.kind === 211 /* SyntaxKind.NewExpression */); return getMinArgumentCount(signature) === 0; } else { @@ -76526,7 +77168,7 @@ var ts; // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (node.kind !== 165 /* SyntaxKind.Decorator */) { + if (node.kind !== 167 /* SyntaxKind.Decorator */) { var skipBindingPatterns = ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }); var contextualType = getContextualType(node, skipBindingPatterns ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); if (contextualType) { @@ -76590,7 +77232,7 @@ var ts; } for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 227 /* SyntaxKind.OmittedExpression */ && !(checkMode & 32 /* CheckMode.IsForStringLiteralArgumentCompletions */ && hasSkipDirectInferenceFlag(arg))) { + if (arg.kind !== 229 /* SyntaxKind.OmittedExpression */ && !(checkMode & 32 /* CheckMode.IsForStringLiteralArgumentCompletions */ && hasSkipDirectInferenceFlag(arg))) { var paramType = getTypeAtPosition(signature, i); if (couldContainTypeVariables(paramType)) { var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode); @@ -76616,7 +77258,7 @@ var ts; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. - return getMutableArrayOrTupleType(arg.kind === 232 /* SyntaxKind.SyntheticExpression */ ? arg.type : + return getMutableArrayOrTupleType(arg.kind === 234 /* SyntaxKind.SyntheticExpression */ ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode)); } } @@ -76626,13 +77268,13 @@ var ts; for (var i = index; i < argCount; i++) { var arg = args[i]; if (isSpreadArgument(arg)) { - var spreadType = arg.kind === 232 /* SyntaxKind.SyntheticExpression */ ? arg.type : checkExpression(arg.expression); + var spreadType = arg.kind === 234 /* SyntaxKind.SyntheticExpression */ ? arg.type : checkExpression(arg.expression); if (isArrayLikeType(spreadType)) { types.push(spreadType); flags.push(8 /* ElementFlags.Variadic */); } else { - types.push(checkIteratedTypeOrElementType(33 /* IterationUse.Spread */, spreadType, undefinedType, arg.kind === 225 /* SyntaxKind.SpreadElement */ ? arg.expression : arg)); + types.push(checkIteratedTypeOrElementType(33 /* IterationUse.Spread */, spreadType, undefinedType, arg.kind === 227 /* SyntaxKind.SpreadElement */ ? arg.expression : arg)); flags.push(4 /* ElementFlags.Rest */); } } @@ -76643,7 +77285,7 @@ var ts; types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); flags.push(1 /* ElementFlags.Required */); } - if (arg.kind === 232 /* SyntaxKind.SyntheticExpression */ && arg.tupleNameSource) { + if (arg.kind === 234 /* SyntaxKind.SyntheticExpression */ && arg.tupleNameSource) { names.push(arg.tupleNameSource); } } @@ -76787,7 +77429,7 @@ var ts; return undefined; } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 209 /* SyntaxKind.NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 211 /* SyntaxKind.NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. @@ -76805,7 +77447,7 @@ var ts; var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 227 /* SyntaxKind.OmittedExpression */) { + if (arg.kind !== 229 /* SyntaxKind.OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode); // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive), @@ -76850,8 +77492,8 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - var expression = node.kind === 208 /* SyntaxKind.CallExpression */ ? node.expression : - node.kind === 210 /* SyntaxKind.TaggedTemplateExpression */ ? node.tag : undefined; + var expression = node.kind === 210 /* SyntaxKind.CallExpression */ ? node.expression : + node.kind === 212 /* SyntaxKind.TaggedTemplateExpression */ ? node.tag : undefined; if (expression) { var callee = ts.skipOuterExpressions(expression); if (ts.isAccessExpression(callee)) { @@ -76869,17 +77511,17 @@ var ts; * Returns the effective arguments for an expression that works like a function invocation. */ function getEffectiveCallArguments(node) { - if (node.kind === 210 /* SyntaxKind.TaggedTemplateExpression */) { + if (node.kind === 212 /* SyntaxKind.TaggedTemplateExpression */) { var template = node.template; var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; - if (template.kind === 223 /* SyntaxKind.TemplateExpression */) { + if (template.kind === 225 /* SyntaxKind.TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_3.push(span.expression); }); } return args_3; } - if (node.kind === 165 /* SyntaxKind.Decorator */) { + if (node.kind === 167 /* SyntaxKind.Decorator */) { return getEffectiveDecoratorArguments(node); } if (ts.isJsxOpeningLikeElement(node)) { @@ -76893,7 +77535,7 @@ var ts; var _loop_26 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. - var spreadType = arg.kind === 225 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); + var spreadType = arg.kind === 227 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { ts.forEach(getTypeArguments(spreadType), function (t, i) { var _a; @@ -76920,30 +77562,30 @@ var ts; var parent = node.parent; var expr = node.expression; switch (parent.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class). return [ createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) ]; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts). var func = parent.parent; return [ - createSyntheticExpression(expr, parent.parent.kind === 171 /* SyntaxKind.Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, parent.parent.kind === 173 /* SyntaxKind.Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), createSyntheticExpression(expr, anyType), createSyntheticExpression(expr, numberType) ]; - case 167 /* SyntaxKind.PropertyDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: // A method or accessor declaration decorator will have two or three arguments (see // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators // for ES3, we will only pass two arguments. - var hasPropDesc = parent.kind !== 167 /* SyntaxKind.PropertyDeclaration */ && languageVersion !== 0 /* ScriptTarget.ES3 */; + var hasPropDesc = languageVersion !== 0 /* ScriptTarget.ES3 */ && (!ts.isPropertyDeclaration(parent) || ts.hasAccessorModifier(parent)); return [ createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), @@ -76957,17 +77599,17 @@ var ts; */ function getDecoratorArgumentCount(node, signature) { switch (node.parent.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: return 1; - case 167 /* SyntaxKind.PropertyDeclaration */: - return 2; - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + return ts.hasAccessorModifier(node.parent) ? 3 : 2; + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: // For ES3 or decorators with only two parameters we supply only two arguments return languageVersion === 0 /* ScriptTarget.ES3 */ || signature.parameters.length <= 2 ? 2 : 3; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return 3; default: return ts.Debug.fail(); @@ -77109,8 +77751,8 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { - var isTaggedTemplate = node.kind === 210 /* SyntaxKind.TaggedTemplateExpression */; - var isDecorator = node.kind === 165 /* SyntaxKind.Decorator */; + var isTaggedTemplate = node.kind === 212 /* SyntaxKind.TaggedTemplateExpression */; + var isDecorator = node.kind === 167 /* SyntaxKind.Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray; var typeArguments; @@ -77173,7 +77815,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = !!(checkMode & 16 /* CheckMode.IsForSignatureHelp */) && node.kind === 208 /* SyntaxKind.CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = !!(checkMode & 16 /* CheckMode.IsForSignatureHelp */) && node.kind === 210 /* SyntaxKind.CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -77662,7 +78304,7 @@ var ts; return resolveErrorCall(node); } var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && ts.hasSyntacticModifier(valueDecl, 128 /* ModifierFlags.Abstract */)) { + if (valueDecl && ts.hasSyntacticModifier(valueDecl, 256 /* ModifierFlags.Abstract */)) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } @@ -77733,7 +78375,7 @@ var ts; var declaration = signature.declaration; var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24 /* ModifierFlags.NonPublicAccessibilityModifier */); // (1) Public constructors and (2) constructor functions are always accessible. - if (!modifiers || declaration.kind !== 171 /* SyntaxKind.Constructor */) { + if (!modifiers || declaration.kind !== 173 /* SyntaxKind.Constructor */) { return true; } var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -77877,16 +78519,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -77932,7 +78574,7 @@ var ts; // file would probably be preferable. var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* SymbolFlags.Type */); var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* SymbolFlags.Type */, node); - var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); + var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */)); var parameterSymbol = createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, "props"); parameterSymbol.type = result; return createSignature(declaration, @@ -77981,16 +78623,16 @@ var ts; } function resolveSignature(node, candidatesOutArray, checkMode) { switch (node.kind) { - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return resolveCallExpression(node, candidatesOutArray, checkMode); - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: return resolveNewExpression(node, candidatesOutArray, checkMode); - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode); - case 165 /* SyntaxKind.Decorator */: + case 167 /* SyntaxKind.Decorator */: return resolveDecorator(node, candidatesOutArray, checkMode); - case 280 /* SyntaxKind.JsxOpeningElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); @@ -78034,12 +78676,15 @@ var ts; return false; } var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + (ts.isVariableDeclaration(node) || ts.isPropertyAssignment(node)) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : undefined; if (func) { - // If the node has a @class tag, treat it like a constructor. + // If the node has a @class or @constructor tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; + // If the node is a property of an object literal. + if (ts.isPropertyAssignment(ts.walkUpParenthesizedExpressions(func.parent))) + return false; // If the symbol of the node has members, treat it like a constructor. var symbol = getSymbolOfNode(func); return !!((_a = symbol === null || symbol === void 0 ? void 0 : symbol.members) === null || _a === void 0 ? void 0 : _a.size); @@ -78122,7 +78767,7 @@ var ts; return false; } var parent = node.parent; - while (parent && parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + while (parent && parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { parent = parent.parent; } if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { @@ -78148,12 +78793,12 @@ var ts; if (node.expression.kind === 106 /* SyntaxKind.SuperKeyword */) { return voidType; } - if (node.kind === 209 /* SyntaxKind.NewExpression */) { + if (node.kind === 211 /* SyntaxKind.NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 171 /* SyntaxKind.Constructor */ && - declaration.kind !== 175 /* SyntaxKind.ConstructSignature */ && - declaration.kind !== 180 /* SyntaxKind.ConstructorType */ && + declaration.kind !== 173 /* SyntaxKind.Constructor */ && + declaration.kind !== 177 /* SyntaxKind.ConstructSignature */ && + declaration.kind !== 182 /* SyntaxKind.ConstructorType */ && !ts.isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) { // When resolved signature is a call signature (and not a construct signature) the result type is any @@ -78173,7 +78818,7 @@ var ts; if (returnType.flags & 12288 /* TypeFlags.ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 208 /* SyntaxKind.CallExpression */ && !node.questionDotToken && node.parent.kind === 238 /* SyntaxKind.ExpressionStatement */ && + if (node.kind === 210 /* SyntaxKind.CallExpression */ && !node.questionDotToken && node.parent.kind === 241 /* SyntaxKind.ExpressionStatement */ && returnType.flags & 16384 /* TypeFlags.Void */ && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -78203,20 +78848,20 @@ var ts; function getDeprecatedSuggestionNode(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 208 /* SyntaxKind.CallExpression */: - case 165 /* SyntaxKind.Decorator */: - case 209 /* SyntaxKind.NewExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 167 /* SyntaxKind.Decorator */: + case 211 /* SyntaxKind.NewExpression */: return getDeprecatedSuggestionNode(node.expression); - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: return getDeprecatedSuggestionNode(node.tag); - case 280 /* SyntaxKind.JsxOpeningElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: return getDeprecatedSuggestionNode(node.tagName); - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return node.argumentExpression; - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return node.name; - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: var typeReference = node; return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference; default: @@ -78287,8 +78932,8 @@ var ts; if (hasDefaultOnly && type && !isErrorType(type)) { var synthType = type; if (!synthType.defaultOnlyType) { - var type_5 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); - synthType.defaultOnlyType = type_5; + var type_4 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); + synthType.defaultOnlyType = type_4; } return synthType.defaultOnlyType; } @@ -78331,9 +78976,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* SymbolFlags.Function */ - ? 256 /* SyntaxKind.FunctionDeclaration */ + ? 259 /* SyntaxKind.FunctionDeclaration */ : resolvedRequire.flags & 3 /* SymbolFlags.Variable */ - ? 254 /* SyntaxKind.VariableDeclaration */ + ? 257 /* SyntaxKind.VariableDeclaration */ : 0 /* SyntaxKind.Unknown */; if (targetDeclarationKind !== 0 /* SyntaxKind.Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -78353,7 +78998,7 @@ var ts; return getReturnTypeOfSignature(signature); } function checkAssertion(node) { - if (node.kind === 211 /* SyntaxKind.TypeAssertionExpression */) { + if (node.kind === 213 /* SyntaxKind.TypeAssertionExpression */) { var file = ts.getSourceFileOfNode(node); if (file && ts.fileExtensionIsOneOf(file.fileName, [".cts" /* Extension.Cts */, ".mts" /* Extension.Mts */])) { grammarErrorOnNode(node, ts.Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead); @@ -78369,25 +79014,25 @@ var ts; case 9 /* SyntaxKind.BigIntLiteral */: case 110 /* SyntaxKind.TrueKeyword */: case 95 /* SyntaxKind.FalseKeyword */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 223 /* SyntaxKind.TemplateExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 225 /* SyntaxKind.TemplateExpression */: return true; - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return isValidConstAssertionArgument(node.expression); - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: var op = node.operator; var arg = node.operand; return op === 40 /* SyntaxKind.MinusToken */ && (arg.kind === 8 /* SyntaxKind.NumericLiteral */ || arg.kind === 9 /* SyntaxKind.BigIntLiteral */) || op === 39 /* SyntaxKind.PlusToken */ && arg.kind === 8 /* SyntaxKind.NumericLiteral */; - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: var expr = node.expression; var symbol = getTypeOfNode(expr).symbol; if (symbol && symbol.flags & 2097152 /* SymbolFlags.Alias */) { symbol = resolveAlias(symbol); } - return !!(symbol && (symbol.flags & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); + return !!(symbol && (getAllSymbolFlags(symbol) & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); } return false; } @@ -78423,7 +79068,7 @@ var ts; } function checkExpressionWithTypeArguments(node) { checkGrammarExpressionWithTypeArguments(node); - var exprType = node.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */ ? checkExpression(node.expression) : + var exprType = node.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */ ? checkExpression(node.expression) : ts.isThisIdentifier(node.exprName) ? checkThisExpression(node.exprName) : checkExpression(node.exprName); var typeArguments = node.typeArguments; @@ -78487,6 +79132,16 @@ var ts; }); } } + function checkSatisfiesExpression(node) { + checkSourceElement(node.type); + var targetType = getTypeFromTypeNode(node.type); + if (isErrorType(targetType)) { + return targetType; + } + var exprType = checkExpression(node.expression); + checkTypeAssignableToAndOptionallyElaborate(exprType, targetType, node.type, node.expression, ts.Diagnostics.Type_0_does_not_satisfy_the_expected_type_1); + return exprType; + } function checkMetaProperty(node) { checkGrammarMetaProperty(node); if (node.keywordToken === 103 /* SyntaxKind.NewKeyword */) { @@ -78514,7 +79169,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 171 /* SyntaxKind.Constructor */) { + else if (container.kind === 173 /* SyntaxKind.Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -78566,7 +79221,7 @@ var ts; } function getParameterIdentifierNameAtPosition(signature, pos) { var _a; - if (((_a = signature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 317 /* SyntaxKind.JSDocFunctionType */) { + if (((_a = signature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 320 /* SyntaxKind.JSDocFunctionType */) { return undefined; } var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); @@ -78598,7 +79253,7 @@ var ts; return symbol.valueDeclaration && ts.isParameter(symbol.valueDeclaration) && ts.isIdentifier(symbol.valueDeclaration.name); } function isValidDeclarationForTupleLabel(d) { - return d.kind === 197 /* SyntaxKind.NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); + return d.kind === 199 /* SyntaxKind.NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); } function getNameableDeclarationAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); @@ -78890,7 +79545,7 @@ var ts; var yieldType; var nextType; var fallbackReturnType = voidType; - if (func.body.kind !== 235 /* SyntaxKind.Block */) { // Async or normal arrow function + if (func.body.kind !== 238 /* SyntaxKind.Block */) { // Async or normal arrow function returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* CheckMode.SkipGenericFunctions */); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -79039,15 +79694,25 @@ var ts; } function isExhaustiveSwitchStatement(node) { var links = getNodeLinks(node); - return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); + if (links.isExhaustive === undefined) { + links.isExhaustive = 0; // Indicate resolution is in process + var exhaustive = computeExhaustiveSwitchStatement(node); + if (links.isExhaustive === 0) { + links.isExhaustive = exhaustive; + } + } + else if (links.isExhaustive === 0) { + links.isExhaustive = false; // Resolve circularity to false + } + return links.isExhaustive; } function computeExhaustiveSwitchStatement(node) { - if (node.expression.kind === 216 /* SyntaxKind.TypeOfExpression */) { + if (node.expression.kind === 218 /* SyntaxKind.TypeOfExpression */) { var witnesses = getSwitchClauseTypeOfWitnesses(node); if (!witnesses) { return false; } - var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(node.expression.expression)); + var operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression)); // Get the not-equal flags for all handled cases. var notEqualFacts_2 = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses); if (operandConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */) { @@ -79057,7 +79722,7 @@ var ts; // A missing not-equal flag indicates that the type wasn't handled by some case. return !someType(operandConstraint, function (t) { return (getTypeFacts(t) & notEqualFacts_2) === notEqualFacts_2; }); } - var type = getTypeOfExpression(node.expression); + var type = checkExpressionCached(node.expression); if (!isLiteralType(type)) { return false; } @@ -79108,11 +79773,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: return true; - case 169 /* SyntaxKind.MethodDeclaration */: - return func.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */; + case 171 /* SyntaxKind.MethodDeclaration */: + return func.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */; default: return false; } @@ -79138,7 +79803,7 @@ var ts; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 168 /* SyntaxKind.MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 235 /* SyntaxKind.Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 170 /* SyntaxKind.MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 238 /* SyntaxKind.Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 512 /* NodeFlags.HasExplicitReturn */; @@ -79172,7 +79837,7 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 169 /* SyntaxKind.MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 171 /* SyntaxKind.MethodDeclaration */ || ts.isObjectLiteralMethod(node)); checkNodeDeferred(node); if (ts.isFunctionExpression(node)) { checkCollisionsForDeclarationName(node, node.name); @@ -79199,7 +79864,7 @@ var ts; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 213 /* SyntaxKind.FunctionExpression */) { + if (!hasGrammarError && node.kind === 215 /* SyntaxKind.FunctionExpression */) { checkGrammarForGenerator(node); } contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -79250,7 +79915,7 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 169 /* SyntaxKind.MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 171 /* SyntaxKind.MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnType = getReturnTypeFromAnnotation(node); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); @@ -79263,7 +79928,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 235 /* SyntaxKind.Block */) { + if (node.body.kind === 238 /* SyntaxKind.Block */) { checkSourceElement(node.body); } else { @@ -79353,7 +80018,7 @@ var ts; expr.expression.kind === 108 /* SyntaxKind.ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var ctor = ts.getContainingFunction(expr); - if (!(ctor && (ctor.kind === 171 /* SyntaxKind.Constructor */ || isJSConstructor(ctor)))) { + if (!(ctor && (ctor.kind === 173 /* SyntaxKind.Constructor */ || isJSConstructor(ctor)))) { return true; } if (symbol.valueDeclaration) { @@ -79378,7 +80043,7 @@ var ts; var symbol_2 = getNodeLinks(node).resolvedSymbol; if (symbol_2.flags & 2097152 /* SymbolFlags.Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol_2); - return !!declaration && declaration.kind === 268 /* SyntaxKind.NamespaceImport */; + return !!declaration && declaration.kind === 271 /* SyntaxKind.NamespaceImport */; } } } @@ -79478,7 +80143,7 @@ var ts; if (!hasParseDiagnostics(sourceFile)) { var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); - if (container && container.kind !== 171 /* SyntaxKind.Constructor */ && (ts.getFunctionFlags(container) & 2 /* FunctionFlags.Async */) === 0) { + if (container && container.kind !== 173 /* SyntaxKind.Constructor */ && (ts.getFunctionFlags(container) & 2 /* FunctionFlags.Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(container, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -79646,6 +80311,9 @@ var ts; } return booleanType; } + function hasEmptyObjectIntersection(type) { + return someType(type, function (t) { return t === unknownEmptyObjectType || !!(t.flags & 2097152 /* TypeFlags.Intersection */) && ts.some(t.types, isEmptyAnonymousObjectType); }); + } function checkInExpression(left, right, leftType, rightType) { if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; @@ -79662,40 +80330,20 @@ var ts; } } else { - leftType = checkNonNullType(leftType, left); - // TypeScript 1.0 spec (April 2014): 4.15.5 - // Require the left operand to be of type Any, the String primitive type, or the Number primitive type. - if (!(allTypesAssignableToKind(leftType, 402653316 /* TypeFlags.StringLike */ | 296 /* TypeFlags.NumberLike */ | 12288 /* TypeFlags.ESSymbolLike */) || - isTypeAssignableToKind(leftType, 4194304 /* TypeFlags.Index */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */ | 262144 /* TypeFlags.TypeParameter */))) { - error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or_symbol); + // The type of the lef operand must be assignable to string, number, or symbol. + checkTypeAssignableTo(checkNonNullType(leftType, left), stringNumberSymbolType, left); + } + // The type of the right operand must be assignable to 'object'. + if (checkTypeAssignableTo(checkNonNullType(rightType, right), nonPrimitiveType, right)) { + // The {} type is assignable to the object type, yet {} might represent a primitive type. Here we + // detect and error on {} that results from narrowing the unknown type, as well as intersections + // that include {} (we know that the other types in such intersections are assignable to object + // since we already checked for that). + if (hasEmptyObjectIntersection(rightType)) { + error(right, ts.Diagnostics.Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operator, typeToString(rightType)); } } - rightType = checkNonNullType(rightType, right); - // TypeScript 1.0 spec (April 2014): 4.15.5 - // The in operator requires the right operand to be - // - // 1. assignable to the non-primitive type, - // 2. an unconstrained type parameter, - // 3. a union or intersection including one or more type parameters, whose constituents are all assignable to the - // the non-primitive type, or are unconstrainted type parameters, or have constraints assignable to the - // non-primitive type, or - // 4. a type parameter whose constraint is - // i. an object type, - // ii. the non-primitive type, or - // iii. a union or intersection with at least one constituent assignable to an object or non-primitive type. - // - // The divergent behavior for type parameters and unions containing type parameters is a workaround for type - // parameters not being narrowable. If the right operand is a concrete type, we can error if there is any chance - // it is a primitive. But if the operand is a type parameter, it cannot be narrowed, so we don't issue an error - // unless *all* instantiations would result in an error. - // // The result is always of the Boolean primitive type. - var rightTypeConstraint = getConstraintOfType(rightType); - if (!allTypesAssignableToKind(rightType, 67108864 /* TypeFlags.NonPrimitive */ | 58982400 /* TypeFlags.InstantiableNonPrimitive */) || - rightTypeConstraint && (isTypeAssignableToKind(rightType, 3145728 /* TypeFlags.UnionOrIntersection */) && !allTypesAssignableToKind(rightTypeConstraint, 67108864 /* TypeFlags.NonPrimitive */ | 58982400 /* TypeFlags.InstantiableNonPrimitive */) || - !maybeTypeOfKind(rightTypeConstraint, 67108864 /* TypeFlags.NonPrimitive */ | 58982400 /* TypeFlags.InstantiableNonPrimitive */ | 524288 /* TypeFlags.Object */))) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_not_be_a_primitive); - } return booleanType; } function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { @@ -79713,7 +80361,7 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } var properties = node.properties; var property = properties[propertyIndex]; - if (property.kind === 296 /* SyntaxKind.PropertyAssignment */ || property.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */) { + if (property.kind === 299 /* SyntaxKind.PropertyAssignment */ || property.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */) { var name = property.name; var exprType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(exprType)) { @@ -79726,9 +80374,9 @@ var ts; } var elementType = getIndexedAccessType(objectLiteralType, exprType, 32 /* AccessFlags.ExpressionPosition */, name); var type = getFlowTypeOfDestructuring(property, elementType); - return checkDestructuringAssignment(property.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */ ? property : property.initializer, type); } - else if (property.kind === 298 /* SyntaxKind.SpreadAssignment */) { + else if (property.kind === 301 /* SyntaxKind.SpreadAssignment */) { if (propertyIndex < properties.length - 1) { error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } @@ -79766,7 +80414,7 @@ var ts; var inBoundsType = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType; for (var i = 0; i < elements.length; i++) { var type = possiblyOutOfBoundsType; - if (node.elements[i].kind === 225 /* SyntaxKind.SpreadElement */) { + if (node.elements[i].kind === 227 /* SyntaxKind.SpreadElement */) { type = inBoundsType = inBoundsType !== null && inBoundsType !== void 0 ? inBoundsType : (checkIteratedTypeOrElementType(65 /* IterationUse.Destructuring */, sourceType, undefinedType, node) || errorType); } checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode); @@ -79776,8 +80424,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 227 /* SyntaxKind.OmittedExpression */) { - if (element.kind !== 225 /* SyntaxKind.SpreadElement */) { + if (element.kind !== 229 /* SyntaxKind.OmittedExpression */) { + if (element.kind !== 227 /* SyntaxKind.SpreadElement */) { var indexType = getNumberLiteralType(elementIndex); if (isArrayLikeType(sourceType)) { // We create a synthetic expression so that getIndexedAccessType doesn't get confused @@ -79795,7 +80443,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 221 /* SyntaxKind.BinaryExpression */ && restExpression.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { + if (restExpression.kind === 223 /* SyntaxKind.BinaryExpression */ && restExpression.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -79811,7 +80459,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -79827,7 +80475,7 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 221 /* SyntaxKind.BinaryExpression */ && target.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { + if (target.kind === 223 /* SyntaxKind.BinaryExpression */ && target.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; // A default value is specified, so remove undefined from the final type. @@ -79835,20 +80483,20 @@ var ts; sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); } } - if (target.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { + if (target.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 204 /* SyntaxKind.ArrayLiteralExpression */) { + if (target.kind === 206 /* SyntaxKind.ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 298 /* SyntaxKind.SpreadAssignment */ ? + var error = target.parent.kind === 301 /* SyntaxKind.SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - var optionalError = target.parent.kind === 298 /* SyntaxKind.SpreadAssignment */ ? + var optionalError = target.parent.kind === 301 /* SyntaxKind.SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access; if (checkReferenceExpression(target, error, optionalError)) { @@ -79873,36 +80521,36 @@ var ts; case 79 /* SyntaxKind.Identifier */: case 10 /* SyntaxKind.StringLiteral */: case 13 /* SyntaxKind.RegularExpressionLiteral */: - case 210 /* SyntaxKind.TaggedTemplateExpression */: - case 223 /* SyntaxKind.TemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: + case 225 /* SyntaxKind.TemplateExpression */: case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: case 8 /* SyntaxKind.NumericLiteral */: case 9 /* SyntaxKind.BigIntLiteral */: case 110 /* SyntaxKind.TrueKeyword */: case 95 /* SyntaxKind.FalseKeyword */: case 104 /* SyntaxKind.NullKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: - case 213 /* SyntaxKind.FunctionExpression */: - case 226 /* SyntaxKind.ClassExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 216 /* SyntaxKind.TypeOfExpression */: - case 230 /* SyntaxKind.NonNullExpression */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 278 /* SyntaxKind.JsxElement */: + case 155 /* SyntaxKind.UndefinedKeyword */: + case 215 /* SyntaxKind.FunctionExpression */: + case 228 /* SyntaxKind.ClassExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 218 /* SyntaxKind.TypeOfExpression */: + case 232 /* SyntaxKind.NonNullExpression */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: + case 281 /* SyntaxKind.JsxElement */: return true; - case 222 /* SyntaxKind.ConditionalExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { @@ -79914,9 +80562,9 @@ var ts; } return false; // Some forms listed here for clarity - case 217 /* SyntaxKind.VoidExpression */: // Explicit opt-out - case 211 /* SyntaxKind.TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 229 /* SyntaxKind.AsExpression */: // Not SEF, but can produce useful type warnings + case 219 /* SyntaxKind.VoidExpression */: // Explicit opt-out + case 213 /* SyntaxKind.TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 231 /* SyntaxKind.AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } @@ -79953,7 +80601,7 @@ var ts; } checkGrammarNullishCoalesceWithLogicalExpression(node); var operator = node.operatorToken.kind; - if (operator === 63 /* SyntaxKind.EqualsToken */ && (node.left.kind === 205 /* SyntaxKind.ObjectLiteralExpression */ || node.left.kind === 204 /* SyntaxKind.ArrayLiteralExpression */)) { + if (operator === 63 /* SyntaxKind.EqualsToken */ && (node.left.kind === 207 /* SyntaxKind.ObjectLiteralExpression */ || node.left.kind === 206 /* SyntaxKind.ArrayLiteralExpression */)) { state.skip = true; setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 108 /* SyntaxKind.ThisKeyword */)); return state; @@ -79975,11 +80623,11 @@ var ts; if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */ || operator === 56 /* SyntaxKind.BarBarToken */ || operator === 60 /* SyntaxKind.QuestionQuestionToken */) { if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */) { var parent = node.parent; - while (parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */ + while (parent.kind === 214 /* SyntaxKind.ParenthesizedExpression */ || ts.isBinaryExpression(parent) && (parent.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */ || parent.operatorToken.kind === 56 /* SyntaxKind.BarBarToken */)) { parent = parent.parent; } - checkTestingKnownTruthyCallableOrAwaitableType(node.left, ts.isIfStatement(parent) ? parent.thenStatement : undefined); + checkTestingKnownTruthyCallableOrAwaitableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } checkTruthinessOfType(leftType, node.left); } @@ -80050,7 +80698,7 @@ var ts; // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 63 /* SyntaxKind.EqualsToken */ && (left.kind === 205 /* SyntaxKind.ObjectLiteralExpression */ || left.kind === 204 /* SyntaxKind.ArrayLiteralExpression */)) { + if (operator === 63 /* SyntaxKind.EqualsToken */ && (left.kind === 207 /* SyntaxKind.ObjectLiteralExpression */ || left.kind === 206 /* SyntaxKind.ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 108 /* SyntaxKind.ThisKeyword */); } var leftType; @@ -80206,6 +80854,7 @@ var ts; var eqType = operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */; error(errorNode, ts.Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); } + checkNaNEquality(errorNode, operator, left, right); reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); }); return booleanType; case 102 /* SyntaxKind.InstanceOfKeyword */: @@ -80401,20 +81050,35 @@ var ts; } } function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) { - var typeName; switch (operatorToken.kind) { case 36 /* SyntaxKind.EqualsEqualsEqualsToken */: case 34 /* SyntaxKind.EqualsEqualsToken */: - typeName = "false"; - break; case 37 /* SyntaxKind.ExclamationEqualsEqualsToken */: case 35 /* SyntaxKind.ExclamationEqualsToken */: - typeName = "true"; + return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap, leftStr, rightStr); + default: + return undefined; } - if (typeName) { - return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr); + } + function checkNaNEquality(errorNode, operator, left, right) { + var isLeftNaN = isGlobalNaN(ts.skipParentheses(left)); + var isRightNaN = isGlobalNaN(ts.skipParentheses(right)); + if (isLeftNaN || isRightNaN) { + var err = error(errorNode, ts.Diagnostics.This_condition_will_always_return_0, ts.tokenToString(operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */ || operator === 34 /* SyntaxKind.EqualsEqualsToken */ ? 95 /* SyntaxKind.FalseKeyword */ : 110 /* SyntaxKind.TrueKeyword */)); + if (isLeftNaN && isRightNaN) + return; + var operatorString = operator === 37 /* SyntaxKind.ExclamationEqualsEqualsToken */ || operator === 35 /* SyntaxKind.ExclamationEqualsToken */ ? ts.tokenToString(53 /* SyntaxKind.ExclamationToken */) : ""; + var location = isLeftNaN ? right : left; + var expression = ts.skipParentheses(location); + ts.addRelatedInfo(err, ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_mean_0, "".concat(operatorString, "Number.isNaN(").concat(ts.isEntityNameExpression(expression) ? ts.entityNameToString(expression) : "...", ")"))); } - return undefined; + } + function isGlobalNaN(expr) { + if (ts.isIdentifier(expr) && expr.escapedText === "NaN") { + var globalNaNSymbol = getGlobalNaNSymbol(); + return !!globalNaNSymbol && globalNaNSymbol === getResolvedSymbol(expr); + } + return false; } } function getBaseTypesIfUnrelated(leftType, rightType, isRelated) { @@ -80495,8 +81159,8 @@ var ts; } } function checkConditionalExpression(node, checkMode) { - checkTruthinessExpression(node.condition); - checkTestingKnownTruthyCallableOrAwaitableType(node.condition, node.whenTrue); + var type = checkTruthinessExpression(node.condition); + checkTestingKnownTruthyCallableOrAwaitableType(node.condition, type, node.whenTrue); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* UnionReduction.Subtype */); @@ -80525,7 +81189,7 @@ var ts; type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* TypeFlags.StringLike */)); } function getContextNode(node) { - if (node.kind === 286 /* SyntaxKind.JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { + if (node.kind === 289 /* SyntaxKind.JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -80579,8 +81243,8 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node, /*excludeJSDocTypeAssertions*/ true); - return node.kind === 211 /* SyntaxKind.TypeAssertionExpression */ || - node.kind === 229 /* SyntaxKind.AsExpression */ || + return node.kind === 213 /* SyntaxKind.TypeAssertionExpression */ || + node.kind === 231 /* SyntaxKind.AsExpression */ || ts.isJSDocTypeAssertion(node); } function checkDeclarationInitializer(declaration, checkMode, contextualType) { @@ -80589,7 +81253,7 @@ var ts; (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, checkMode || 0 /* CheckMode.Normal */) : checkExpressionCached(initializer, checkMode)); - return ts.isParameter(declaration) && declaration.name.kind === 202 /* SyntaxKind.ArrayBindingPattern */ && + return ts.isParameter(declaration) && declaration.name.kind === 204 /* SyntaxKind.ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; } @@ -80599,7 +81263,7 @@ var ts; var elementFlags = type.target.elementFlags.slice(); for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) { var e = patternElements[i]; - if (i < patternElements.length - 1 || !(e.kind === 203 /* SyntaxKind.BindingElement */ && e.dotDotDotToken)) { + if (i < patternElements.length - 1 || !(e.kind === 205 /* SyntaxKind.BindingElement */ && e.dotDotDotToken)) { elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType); elementFlags.push(2 /* ElementFlags.Optional */); if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) { @@ -80667,7 +81331,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (node.name.kind === 164 /* SyntaxKind.ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -80678,7 +81342,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (node.name.kind === 164 /* SyntaxKind.ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -80752,6 +81416,9 @@ var ts; function hasInferenceCandidates(info) { return !!(info.candidates || info.contraCandidates); } + function hasInferenceCandidatesOrDefault(info) { + return !!(info.candidates || info.contraCandidates || hasTypeParameterDefault(info.typeParameter)); + } function hasOverlappingInferences(a, b) { for (var i = 0; i < a.length; i++) { if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) { @@ -80921,11 +81588,11 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 207 /* SyntaxKind.ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 79 /* SyntaxKind.Identifier */ || node.kind === 161 /* SyntaxKind.QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 181 /* SyntaxKind.TypeQuery */ && node.parent.exprName === node)) || - (node.parent.kind === 275 /* SyntaxKind.ExportSpecifier */); // We allow reexporting const enums + var ok = (node.parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 209 /* SyntaxKind.ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 79 /* SyntaxKind.Identifier */ || node.kind === 163 /* SyntaxKind.QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 183 /* SyntaxKind.TypeQuery */ && node.parent.exprName === node)) || + (node.parent.kind === 278 /* SyntaxKind.ExportSpecifier */); // We allow reexporting const enums if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -80950,9 +81617,9 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 226 /* SyntaxKind.ClassExpression */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 228 /* SyntaxKind.ClassExpression */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } } @@ -80983,80 +81650,82 @@ var ts; return trueType; case 95 /* SyntaxKind.FalseKeyword */: return falseType; - case 223 /* SyntaxKind.TemplateExpression */: + case 225 /* SyntaxKind.TemplateExpression */: return checkTemplateExpression(node); case 13 /* SyntaxKind.RegularExpressionLiteral */: return globalRegExpType; - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode, forceTuple); - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return checkPropertyAccessExpression(node, checkMode); - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: return checkQualifiedName(node, checkMode); - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return checkIndexedAccess(node, checkMode); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: if (node.expression.kind === 100 /* SyntaxKind.ImportKeyword */) { return checkImportCallExpression(node); } // falls through - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: return checkCallExpression(node, checkMode); - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 226 /* SyntaxKind.ClassExpression */: + case 228 /* SyntaxKind.ClassExpression */: return checkClassExpression(node); - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 216 /* SyntaxKind.TypeOfExpression */: + case 218 /* SyntaxKind.TypeOfExpression */: return checkTypeOfExpression(node); - case 211 /* SyntaxKind.TypeAssertionExpression */: - case 229 /* SyntaxKind.AsExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: + case 231 /* SyntaxKind.AsExpression */: return checkAssertion(node); - case 230 /* SyntaxKind.NonNullExpression */: + case 232 /* SyntaxKind.NonNullExpression */: return checkNonNullAssertion(node); - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return checkExpressionWithTypeArguments(node); - case 231 /* SyntaxKind.MetaProperty */: + case 235 /* SyntaxKind.SatisfiesExpression */: + return checkSatisfiesExpression(node); + case 233 /* SyntaxKind.MetaProperty */: return checkMetaProperty(node); - case 215 /* SyntaxKind.DeleteExpression */: + case 217 /* SyntaxKind.DeleteExpression */: return checkDeleteExpression(node); - case 217 /* SyntaxKind.VoidExpression */: + case 219 /* SyntaxKind.VoidExpression */: return checkVoidExpression(node); - case 218 /* SyntaxKind.AwaitExpression */: + case 220 /* SyntaxKind.AwaitExpression */: return checkAwaitExpression(node); - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 222 /* SyntaxKind.ConditionalExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 225 /* SyntaxKind.SpreadElement */: + case 227 /* SyntaxKind.SpreadElement */: return checkSpreadExpression(node, checkMode); - case 227 /* SyntaxKind.OmittedExpression */: + case 229 /* SyntaxKind.OmittedExpression */: return undefinedWideningType; - case 224 /* SyntaxKind.YieldExpression */: + case 226 /* SyntaxKind.YieldExpression */: return checkYieldExpression(node); - case 232 /* SyntaxKind.SyntheticExpression */: + case 234 /* SyntaxKind.SyntheticExpression */: return checkSyntheticExpression(node); - case 288 /* SyntaxKind.JsxExpression */: + case 291 /* SyntaxKind.JsxExpression */: return checkJsxExpression(node, checkMode); - case 278 /* SyntaxKind.JsxElement */: + case 281 /* SyntaxKind.JsxElement */: return checkJsxElement(node, checkMode); - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 282 /* SyntaxKind.JsxFragment */: + case 285 /* SyntaxKind.JsxFragment */: return checkJsxFragment(node); - case 286 /* SyntaxKind.JsxAttributes */: + case 289 /* SyntaxKind.JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 280 /* SyntaxKind.JsxOpeningElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -81115,10 +81784,10 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasSyntacticModifier(node, 16476 /* ModifierFlags.ParameterPropertyModifier */)) { - if (!(func.kind === 171 /* SyntaxKind.Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 173 /* SyntaxKind.Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } - if (func.kind === 171 /* SyntaxKind.Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { + if (func.kind === 173 /* SyntaxKind.Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } @@ -81129,13 +81798,13 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 171 /* SyntaxKind.Constructor */ || func.kind === 175 /* SyntaxKind.ConstructSignature */ || func.kind === 180 /* SyntaxKind.ConstructorType */) { + if (func.kind === 173 /* SyntaxKind.Constructor */ || func.kind === 177 /* SyntaxKind.ConstructSignature */ || func.kind === 182 /* SyntaxKind.ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 214 /* SyntaxKind.ArrowFunction */) { + if (func.kind === 216 /* SyntaxKind.ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } - if (func.kind === 172 /* SyntaxKind.GetAccessor */ || func.kind === 173 /* SyntaxKind.SetAccessor */) { + if (func.kind === 174 /* SyntaxKind.GetAccessor */ || func.kind === 175 /* SyntaxKind.SetAccessor */) { error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); } } @@ -81193,13 +81862,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 214 /* SyntaxKind.ArrowFunction */: - case 174 /* SyntaxKind.CallSignature */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 179 /* SyntaxKind.FunctionType */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 216 /* SyntaxKind.ArrowFunction */: + case 176 /* SyntaxKind.CallSignature */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 181 /* SyntaxKind.FunctionType */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -81217,7 +81886,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 202 /* SyntaxKind.ArrayBindingPattern */ || name.kind === 201 /* SyntaxKind.ObjectBindingPattern */) { + else if (name.kind === 204 /* SyntaxKind.ArrayBindingPattern */ || name.kind === 203 /* SyntaxKind.ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -81226,13 +81895,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 176 /* SyntaxKind.IndexSignature */) { + if (node.kind === 178 /* SyntaxKind.IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 179 /* SyntaxKind.FunctionType */ || node.kind === 256 /* SyntaxKind.FunctionDeclaration */ || node.kind === 180 /* SyntaxKind.ConstructorType */ || - node.kind === 174 /* SyntaxKind.CallSignature */ || node.kind === 171 /* SyntaxKind.Constructor */ || - node.kind === 175 /* SyntaxKind.ConstructSignature */) { + else if (node.kind === 181 /* SyntaxKind.FunctionType */ || node.kind === 259 /* SyntaxKind.FunctionDeclaration */ || node.kind === 182 /* SyntaxKind.ConstructorType */ || + node.kind === 176 /* SyntaxKind.CallSignature */ || node.kind === 173 /* SyntaxKind.Constructor */ || + node.kind === 177 /* SyntaxKind.ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -81264,10 +81933,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 175 /* SyntaxKind.ConstructSignature */: + case 177 /* SyntaxKind.ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 174 /* SyntaxKind.CallSignature */: + case 176 /* SyntaxKind.CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -81297,7 +81966,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 176 /* SyntaxKind.IndexSignature */ && node.kind !== 317 /* SyntaxKind.JSDocFunctionType */) { + if (node.kind !== 178 /* SyntaxKind.IndexSignature */ && node.kind !== 320 /* SyntaxKind.JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -81309,7 +81978,7 @@ var ts; var privateIdentifiers = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 171 /* SyntaxKind.Constructor */) { + if (member.kind === 173 /* SyntaxKind.Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) { @@ -81331,16 +82000,16 @@ var ts; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (memberName) { switch (member.kind) { - case 172 /* SyntaxKind.GetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: addName(names, name, memberName, 1 /* DeclarationMeaning.GetAccessor */ | privateStaticFlags); break; - case 173 /* SyntaxKind.SetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: addName(names, name, memberName, 2 /* DeclarationMeaning.SetAccessor */ | privateStaticFlags); break; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: addName(names, name, memberName, 3 /* DeclarationMeaning.GetOrSetAccessor */ | privateStaticFlags); break; - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: addName(names, name, memberName, 8 /* DeclarationMeaning.Method */ | privateStaticFlags); break; } @@ -81412,7 +82081,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 166 /* SyntaxKind.PropertySignature */) { + if (member.kind === 168 /* SyntaxKind.PropertySignature */) { var memberName = void 0; var name = member.name; switch (name.kind) { @@ -81437,7 +82106,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 258 /* SyntaxKind.InterfaceDeclaration */) { + if (node.kind === 261 /* SyntaxKind.InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind @@ -81485,7 +82154,7 @@ var ts; checkVariableLikeDeclaration(node); setNodeLinksForPrivateIdentifierScope(node); // property signatures already report "initializer not allowed in ambient context" elsewhere - if (ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */) && node.kind === 167 /* SyntaxKind.PropertyDeclaration */ && node.initializer) { + if (ts.hasSyntacticModifier(node, 256 /* ModifierFlags.Abstract */) && node.kind === 169 /* SyntaxKind.PropertyDeclaration */ && node.initializer) { error(node, ts.Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -81505,7 +82174,7 @@ var ts; // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // method signatures already report "implementation not allowed in ambient context" elsewhere - if (ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */) && node.kind === 169 /* SyntaxKind.MethodDeclaration */ && node.body) { + if (ts.hasSyntacticModifier(node, 256 /* ModifierFlags.Abstract */) && node.kind === 171 /* SyntaxKind.MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } // Private named methods are only allowed in class declarations @@ -81558,7 +82227,7 @@ var ts; if (ts.isPrivateIdentifierClassElementDeclaration(n)) { return true; } - return n.kind === 167 /* SyntaxKind.PropertyDeclaration */ && + return n.kind === 169 /* SyntaxKind.PropertyDeclaration */ && !ts.isStatic(n) && !!n.initializer; } @@ -81641,7 +82310,7 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 172 /* SyntaxKind.GetAccessor */) { + if (node.kind === 174 /* SyntaxKind.GetAccessor */) { if (!(node.flags & 16777216 /* NodeFlags.Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* NodeFlags.HasImplicitReturn */)) { if (!(node.flags & 512 /* NodeFlags.HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -81651,20 +82320,20 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (node.name.kind === 164 /* SyntaxKind.ComputedPropertyName */) { checkComputedPropertyName(node.name); } if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. var symbol = getSymbolOfNode(node); - var getter = ts.getDeclarationOfKind(symbol, 172 /* SyntaxKind.GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 173 /* SyntaxKind.SetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 174 /* SyntaxKind.GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 175 /* SyntaxKind.SetAccessor */); if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* NodeCheckFlags.TypeChecked */)) { getNodeLinks(getter).flags |= 1 /* NodeCheckFlags.TypeChecked */; var getterFlags = ts.getEffectiveModifierFlags(getter); var setterFlags = ts.getEffectiveModifierFlags(setter); - if ((getterFlags & 128 /* ModifierFlags.Abstract */) !== (setterFlags & 128 /* ModifierFlags.Abstract */)) { + if ((getterFlags & 256 /* ModifierFlags.Abstract */) !== (setterFlags & 256 /* ModifierFlags.Abstract */)) { error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } @@ -81681,7 +82350,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 172 /* SyntaxKind.GetAccessor */) { + if (node.kind === 174 /* SyntaxKind.GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -81690,7 +82359,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) { - if (index < typeParameters.length) { + if (node.typeArguments && index < node.typeArguments.length) { return getTypeFromTypeNode(node.typeArguments[index]); } return getEffectiveTypeArguments(node, typeParameters)[index]; @@ -81727,7 +82396,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 178 /* SyntaxKind.TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 180 /* SyntaxKind.TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } ts.forEach(node.typeArguments, checkSourceElement); @@ -81743,7 +82412,7 @@ var ts; } var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { - if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { + if (ts.some(symbol.declarations, function (d) { return ts.isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* TypeFlags.Enum */ && symbol.flags & 8 /* SymbolFlags.EnumMember */) { @@ -81785,7 +82454,7 @@ var ts; var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember); for (var _i = 0, elementTypes_1 = elementTypes; _i < elementTypes_1.length; _i++) { var e = elementTypes_1[_i]; - if (e.kind !== 197 /* SyntaxKind.NamedTupleMember */ && hasNamedElement) { + if (e.kind !== 199 /* SyntaxKind.NamedTupleMember */ && hasNamedElement) { grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names); break; } @@ -81834,7 +82503,7 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 207 /* SyntaxKind.ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 209 /* SyntaxKind.ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* ObjectFlags.Mapped */ && getMappedTypeModifiers(objectType) & 1 /* MappedTypeModifiers.IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -81899,7 +82568,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 189 /* SyntaxKind.ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 191 /* SyntaxKind.ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -81909,7 +82578,7 @@ var ts; if (!links.typeParametersChecked) { links.typeParametersChecked = true; var typeParameter = getDeclaredTypeOfTypeParameter(symbol); - var declarations = ts.getDeclarationsOfKind(symbol, 163 /* SyntaxKind.TypeParameter */); + var declarations = ts.getDeclarationsOfKind(symbol, 165 /* SyntaxKind.TypeParameter */); if (!areTypeParametersIdentical(declarations, [typeParameter], function (decl) { return [decl]; })) { // Report an error on every conflicting declaration. var name = symbolToString(symbol); @@ -81950,10 +82619,10 @@ var ts; if (node.dotDotDotToken && node.questionToken) { grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest); } - if (node.type.kind === 185 /* SyntaxKind.OptionalType */) { + if (node.type.kind === 187 /* SyntaxKind.OptionalType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type); } - if (node.type.kind === 186 /* SyntaxKind.RestType */) { + if (node.type.kind === 188 /* SyntaxKind.RestType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type); } checkSourceElement(node.type); @@ -81966,9 +82635,9 @@ var ts; var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 258 /* SyntaxKind.InterfaceDeclaration */ && - n.parent.kind !== 257 /* SyntaxKind.ClassDeclaration */ && - n.parent.kind !== 226 /* SyntaxKind.ClassExpression */ && + if (n.parent.kind !== 261 /* SyntaxKind.InterfaceDeclaration */ && + n.parent.kind !== 260 /* SyntaxKind.ClassDeclaration */ && + n.parent.kind !== 228 /* SyntaxKind.ClassExpression */ && n.flags & 16777216 /* NodeFlags.Ambient */) { if (!(flags & 2 /* ModifierFlags.Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -82008,7 +82677,7 @@ var ts; else if (deviation & (8 /* ModifierFlags.Private */ | 16 /* ModifierFlags.Protected */)) { error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } - else if (deviation & 128 /* ModifierFlags.Abstract */) { + else if (deviation & 256 /* ModifierFlags.Abstract */) { error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); @@ -82025,7 +82694,7 @@ var ts; }); } } - var flagsToCheck = 1 /* ModifierFlags.Export */ | 2 /* ModifierFlags.Ambient */ | 8 /* ModifierFlags.Private */ | 16 /* ModifierFlags.Protected */ | 128 /* ModifierFlags.Abstract */; + var flagsToCheck = 1 /* ModifierFlags.Export */ | 2 /* ModifierFlags.Ambient */ | 8 /* ModifierFlags.Private */ | 16 /* ModifierFlags.Protected */ | 256 /* ModifierFlags.Abstract */; var someNodeFlags = 0 /* ModifierFlags.None */; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; @@ -82064,7 +82733,7 @@ var ts; // Both are literal property names that are the same. ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 169 /* SyntaxKind.MethodDeclaration */ || node.kind === 168 /* SyntaxKind.MethodSignature */) && + var reportError = (node.kind === 171 /* SyntaxKind.MethodDeclaration */ || node.kind === 170 /* SyntaxKind.MethodSignature */) && ts.isStatic(node) !== ts.isStatic(subsequentNode); // we can get here in two cases // 1. mixed static and instance class members @@ -82089,7 +82758,7 @@ var ts; else { // Report different errors regarding non-consecutive blocks of declarations depending on whether // the node in question is abstract. - if (ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)) { + if (ts.hasSyntacticModifier(node, 256 /* ModifierFlags.Abstract */)) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -82106,7 +82775,7 @@ var ts; var current = declarations_5[_i]; var node = current; var inAmbientContext = node.flags & 16777216 /* NodeFlags.Ambient */; - var inAmbientContextOrInterface = node.parent && (node.parent.kind === 258 /* SyntaxKind.InterfaceDeclaration */ || node.parent.kind === 182 /* SyntaxKind.TypeLiteral */) || inAmbientContext; + var inAmbientContextOrInterface = node.parent && (node.parent.kind === 261 /* SyntaxKind.InterfaceDeclaration */ || node.parent.kind === 184 /* SyntaxKind.TypeLiteral */) || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -82117,10 +82786,10 @@ var ts; // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one previousDeclaration = undefined; } - if ((node.kind === 257 /* SyntaxKind.ClassDeclaration */ || node.kind === 226 /* SyntaxKind.ClassExpression */) && !inAmbientContext) { + if ((node.kind === 260 /* SyntaxKind.ClassDeclaration */ || node.kind === 228 /* SyntaxKind.ClassExpression */) && !inAmbientContext) { hasNonAmbientClass = true; } - if (node.kind === 256 /* SyntaxKind.FunctionDeclaration */ || node.kind === 169 /* SyntaxKind.MethodDeclaration */ || node.kind === 168 /* SyntaxKind.MethodSignature */ || node.kind === 171 /* SyntaxKind.Constructor */) { + if (node.kind === 259 /* SyntaxKind.FunctionDeclaration */ || node.kind === 171 /* SyntaxKind.MethodDeclaration */ || node.kind === 170 /* SyntaxKind.MethodSignature */ || node.kind === 173 /* SyntaxKind.Constructor */) { functionDeclarations.push(node); var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; @@ -82165,12 +82834,12 @@ var ts; }); } if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* SymbolFlags.Function */ && declarations) { - var relatedDiagnostics_1 = ts.filter(declarations, function (d) { return d.kind === 257 /* SyntaxKind.ClassDeclaration */; }) + var relatedDiagnostics_1 = ts.filter(declarations, function (d) { return d.kind === 260 /* SyntaxKind.ClassDeclaration */; }) .map(function (d) { return ts.createDiagnosticForNode(d, ts.Diagnostics.Consider_adding_a_declare_modifier_to_this_class); }); ts.forEach(declarations, function (declaration) { - var diagnostic = declaration.kind === 257 /* SyntaxKind.ClassDeclaration */ + var diagnostic = declaration.kind === 260 /* SyntaxKind.ClassDeclaration */ ? ts.Diagnostics.Class_declaration_cannot_implement_overload_list_for_0 - : declaration.kind === 256 /* SyntaxKind.FunctionDeclaration */ + : declaration.kind === 259 /* SyntaxKind.FunctionDeclaration */ ? ts.Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient : undefined; if (diagnostic) { @@ -82180,7 +82849,7 @@ var ts; } // Abstract methods can't have an implementation -- in particular, they don't need one. if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !ts.hasSyntacticModifier(lastSeenNonAmbientDeclaration, 128 /* ModifierFlags.Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + !ts.hasSyntacticModifier(lastSeenNonAmbientDeclaration, 256 /* ModifierFlags.Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -82226,9 +82895,9 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var d = _a[_i]; var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* ModifierFlags.Export */ | 512 /* ModifierFlags.Default */); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* ModifierFlags.Export */ | 1024 /* ModifierFlags.Default */); if (effectiveDeclarationFlags & 1 /* ModifierFlags.Export */) { - if (effectiveDeclarationFlags & 512 /* ModifierFlags.Default */) { + if (effectiveDeclarationFlags & 1024 /* ModifierFlags.Default */) { defaultExportedDeclarationSpaces |= declarationSpaces; } else { @@ -82261,26 +82930,26 @@ var ts; function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases. // falls through - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 339 /* SyntaxKind.JSDocEnumTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: return 2 /* DeclarationSpaces.ExportType */; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* ModuleInstanceState.NonInstantiated */ ? 4 /* DeclarationSpaces.ExportNamespace */ | 1 /* DeclarationSpaces.ExportValue */ : 4 /* DeclarationSpaces.ExportNamespace */; - case 257 /* SyntaxKind.ClassDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 299 /* SyntaxKind.EnumMember */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 302 /* SyntaxKind.EnumMember */: return 2 /* DeclarationSpaces.ExportType */ | 1 /* DeclarationSpaces.ExportValue */; - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: return 2 /* DeclarationSpaces.ExportType */ | 1 /* DeclarationSpaces.ExportValue */ | 4 /* DeclarationSpaces.ExportNamespace */; - case 271 /* SyntaxKind.ExportAssignment */: - case 221 /* SyntaxKind.BinaryExpression */: + case 274 /* SyntaxKind.ExportAssignment */: + case 223 /* SyntaxKind.BinaryExpression */: var node_2 = d; var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values @@ -82290,19 +82959,19 @@ var ts; d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 268 /* SyntaxKind.NamespaceImport */: - case 267 /* SyntaxKind.ImportClause */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 271 /* SyntaxKind.NamespaceImport */: + case 270 /* SyntaxKind.ImportClause */: var result_12 = 0 /* DeclarationSpaces.None */; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); return result_12; - case 254 /* SyntaxKind.VariableDeclaration */: - case 203 /* SyntaxKind.BindingElement */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 270 /* SyntaxKind.ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + case 257 /* SyntaxKind.VariableDeclaration */: + case 205 /* SyntaxKind.BindingElement */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 273 /* SyntaxKind.ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 case 79 /* SyntaxKind.Identifier */: // https://github.com/microsoft/TypeScript/issues/36098 // Identifiers are used as declarations of assignment declarations whose parents may be // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});` @@ -82346,7 +83015,7 @@ var ts; return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; } // primitives with a `{ then() }` won't be unwrapped/adopted. - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217 @@ -82413,7 +83082,7 @@ var ts; * Determines whether a type is an object with a callable `then` member. */ function isThenableType(type) { - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { // primitive types cannot be considered "thenable" since they are not objects. return false; } @@ -82447,7 +83116,7 @@ var ts; // We only need `Awaited` if `T` is a type variable that has no base constraint, or the base constraint of `T` is `any`, `unknown`, `{}`, `object`, // or is promise-like. if (baseConstraint ? - baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint) : + baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { return true; } @@ -82715,20 +83384,20 @@ var ts; var headMessage; var expectedReturnType; switch (node.parent.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: headMessage = ts.Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 167 /* SyntaxKind.PropertyDeclaration */: - case 164 /* SyntaxKind.Parameter */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 166 /* SyntaxKind.Parameter */: headMessage = ts.Diagnostics.Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any; expectedReturnType = voidType; break; - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: headMessage = ts.Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); @@ -82787,15 +83456,15 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 188 /* SyntaxKind.IntersectionType */: - case 187 /* SyntaxKind.UnionType */: + case 190 /* SyntaxKind.IntersectionType */: + case 189 /* SyntaxKind.UnionType */: return getEntityNameForDecoratorMetadataFromTypeList(node.types); - case 189 /* SyntaxKind.ConditionalType */: + case 191 /* SyntaxKind.ConditionalType */: return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); - case 191 /* SyntaxKind.ParenthesizedType */: - case 197 /* SyntaxKind.NamedTupleMember */: + case 193 /* SyntaxKind.ParenthesizedType */: + case 199 /* SyntaxKind.NamedTupleMember */: return getEntityNameForDecoratorMetadata(node.type); - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return node.typeName; } } @@ -82804,13 +83473,13 @@ var ts; var commonEntityName; for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { var typeNode = types_21[_i]; - while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */ || typeNode.kind === 197 /* SyntaxKind.NamedTupleMember */) { + while (typeNode.kind === 193 /* SyntaxKind.ParenthesizedType */ || typeNode.kind === 199 /* SyntaxKind.NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } - if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { + if (typeNode.kind === 144 /* SyntaxKind.NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 196 /* SyntaxKind.LiteralType */ && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */ || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 198 /* SyntaxKind.LiteralType */ && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */ || typeNode.kind === 155 /* SyntaxKind.UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); @@ -82856,14 +83525,14 @@ var ts; return; } checkExternalEmitHelpers(firstDecorator, 8 /* ExternalEmitHelpers.Decorate */); - if (node.kind === 164 /* SyntaxKind.Parameter */) { + if (node.kind === 166 /* SyntaxKind.Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* ExternalEmitHelpers.Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* ExternalEmitHelpers.Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -82872,23 +83541,23 @@ var ts; } } break; - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - var otherKind = node.kind === 172 /* SyntaxKind.GetAccessor */ ? 173 /* SyntaxKind.SetAccessor */ : 172 /* SyntaxKind.GetAccessor */; + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + var otherKind = node.kind === 174 /* SyntaxKind.GetAccessor */ ? 175 /* SyntaxKind.SetAccessor */ : 174 /* SyntaxKind.GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -82990,7 +83659,7 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: return node; - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return node.name; default: return undefined; @@ -83004,7 +83673,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (node.name && node.name.kind === 164 /* SyntaxKind.ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -83030,7 +83699,7 @@ var ts; checkFunctionOrConstructorSymbol(symbol); } } - var body = node.kind === 168 /* SyntaxKind.MethodSignature */ ? undefined : node.body; + var body = node.kind === 170 /* SyntaxKind.MethodSignature */ ? undefined : node.body; checkSourceElement(body); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node)); addLazyDiagnostic(checkFunctionOrMethodDeclarationDiagnostics); @@ -83076,42 +83745,42 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 305 /* SyntaxKind.SourceFile */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 235 /* SyntaxKind.Block */: - case 263 /* SyntaxKind.CaseBlock */: - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: + case 308 /* SyntaxKind.SourceFile */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 238 /* SyntaxKind.Block */: + case 266 /* SyntaxKind.CaseBlock */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 171 /* SyntaxKind.Constructor */: - case 213 /* SyntaxKind.FunctionExpression */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 214 /* SyntaxKind.ArrowFunction */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 173 /* SyntaxKind.Constructor */: + case 215 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 216 /* SyntaxKind.ArrowFunction */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 168 /* SyntaxKind.MethodSignature */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; - case 190 /* SyntaxKind.InferType */: + case 192 /* SyntaxKind.InferType */: checkUnusedInferTypeParameter(node, addDiagnostic); break; default: @@ -83121,7 +83790,7 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + var message = ts.isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(declaration, 0 /* UnusedKind.Local */, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { @@ -83131,11 +83800,11 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 169 /* SyntaxKind.MethodDeclaration */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - if (member.kind === 173 /* SyntaxKind.SetAccessor */ && member.symbol.flags & 32768 /* SymbolFlags.GetAccessor */) { + case 171 /* SyntaxKind.MethodDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + if (member.kind === 175 /* SyntaxKind.SetAccessor */ && member.symbol.flags & 32768 /* SymbolFlags.GetAccessor */) { // Already would have reported an error on the getter. break; } @@ -83146,7 +83815,7 @@ var ts; addDiagnostic(member, 0 /* UnusedKind.Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8 /* ModifierFlags.Private */)) { @@ -83154,9 +83823,9 @@ var ts; } } break; - case 176 /* SyntaxKind.IndexSignature */: - case 234 /* SyntaxKind.SemicolonClassElement */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 178 /* SyntaxKind.IndexSignature */: + case 237 /* SyntaxKind.SemicolonClassElement */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: // Can't be private break; default: @@ -83184,7 +83853,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 190 /* SyntaxKind.InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 192 /* SyntaxKind.InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) { var sourceFile = ts.getSourceFileOfNode(parent); var range = ts.isJSDocTemplateTag(parent) @@ -83290,7 +83959,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0 /* UnusedKind.Local */, unuseds.length === 1 @@ -83308,7 +83977,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* UnusedKind.Parameter */ : 0 /* UnusedKind.Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 254 /* SyntaxKind.VariableDeclaration */ && bindingPattern.parent.parent.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 257 /* SyntaxKind.VariableDeclaration */ && bindingPattern.parent.parent.kind === 258 /* SyntaxKind.VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -83329,7 +83998,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0 /* UnusedKind.Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 237 /* SyntaxKind.VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 240 /* SyntaxKind.VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { @@ -83359,22 +84028,22 @@ var ts; switch (name.kind) { case 79 /* SyntaxKind.Identifier */: return ts.idText(name); - case 202 /* SyntaxKind.ArrayBindingPattern */: - case 201 /* SyntaxKind.ObjectBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: + case 203 /* SyntaxKind.ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 267 /* SyntaxKind.ImportClause */ || node.kind === 270 /* SyntaxKind.ImportSpecifier */ || node.kind === 268 /* SyntaxKind.NamespaceImport */; + return node.kind === 270 /* SyntaxKind.ImportClause */ || node.kind === 273 /* SyntaxKind.ImportSpecifier */ || node.kind === 271 /* SyntaxKind.NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 267 /* SyntaxKind.ImportClause */ ? decl : decl.kind === 268 /* SyntaxKind.NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 270 /* SyntaxKind.ImportClause */ ? decl : decl.kind === 271 /* SyntaxKind.NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 235 /* SyntaxKind.Block */) { + if (node.kind === 238 /* SyntaxKind.Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -83409,13 +84078,13 @@ var ts; if ((identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) !== name) { return false; } - if (node.kind === 167 /* SyntaxKind.PropertyDeclaration */ || - node.kind === 166 /* SyntaxKind.PropertySignature */ || - node.kind === 169 /* SyntaxKind.MethodDeclaration */ || - node.kind === 168 /* SyntaxKind.MethodSignature */ || - node.kind === 172 /* SyntaxKind.GetAccessor */ || - node.kind === 173 /* SyntaxKind.SetAccessor */ || - node.kind === 296 /* SyntaxKind.PropertyAssignment */) { + if (node.kind === 169 /* SyntaxKind.PropertyDeclaration */ || + node.kind === 168 /* SyntaxKind.PropertySignature */ || + node.kind === 171 /* SyntaxKind.MethodDeclaration */ || + node.kind === 170 /* SyntaxKind.MethodSignature */ || + node.kind === 174 /* SyntaxKind.GetAccessor */ || + node.kind === 175 /* SyntaxKind.SetAccessor */ || + node.kind === 299 /* SyntaxKind.PropertyAssignment */) { // it is ok to have member named '_super', '_this', `Promise`, etc. - member access is always qualified return false; } @@ -83481,7 +84150,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 305 /* SyntaxKind.SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 308 /* SyntaxKind.SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -83496,7 +84165,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 305 /* SyntaxKind.SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* NodeFlags.HasAsyncFunctions */) { + if (parent.kind === 308 /* SyntaxKind.SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* NodeFlags.HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -83596,7 +84265,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 254 /* SyntaxKind.VariableDeclaration */ && !node.initializer) { + if (node.kind === 257 /* SyntaxKind.VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -83608,17 +84277,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* SymbolFlags.BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* NodeFlags.BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 255 /* SyntaxKind.VariableDeclarationList */); - var container = varDeclList.parent.kind === 237 /* SyntaxKind.VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 258 /* SyntaxKind.VariableDeclarationList */); + var container = varDeclList.parent.kind === 240 /* SyntaxKind.VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 235 /* SyntaxKind.Block */ && ts.isFunctionLike(container.parent) || - container.kind === 262 /* SyntaxKind.ModuleBlock */ || - container.kind === 261 /* SyntaxKind.ModuleDeclaration */ || - container.kind === 305 /* SyntaxKind.SourceFile */); + (container.kind === 238 /* SyntaxKind.Block */ && ts.isFunctionLike(container.parent) || + container.kind === 265 /* SyntaxKind.ModuleBlock */ || + container.kind === 264 /* SyntaxKind.ModuleDeclaration */ || + container.kind === 308 /* SyntaxKind.SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -83649,7 +84318,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (node.name.kind === 164 /* SyntaxKind.ComputedPropertyName */) { checkComputedPropertyName(node.name); if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkExpressionCached(node.initializer); @@ -83671,7 +84340,7 @@ var ts; checkExternalEmitHelpers(node, 4 /* ExternalEmitHelpers.Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 164 /* SyntaxKind.ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -83693,7 +84362,7 @@ var ts; } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 202 /* SyntaxKind.ArrayBindingPattern */ && languageVersion < 2 /* ScriptTarget.ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 204 /* SyntaxKind.ArrayBindingPattern */ && languageVersion < 2 /* ScriptTarget.ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* ExternalEmitHelpers.Read */); } ts.forEach(node.name.elements, checkSourceElement); @@ -83705,7 +84374,7 @@ var ts; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = ts.hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; + var needCheckInitializer = ts.hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 246 /* SyntaxKind.ForInStatement */; var needCheckWidenedType = !ts.some(node.name.elements, ts.not(ts.isOmittedExpression)); if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error @@ -83733,7 +84402,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.kind === 203 /* SyntaxKind.BindingElement */ ? node.parent.parent : node)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.kind === 205 /* SyntaxKind.BindingElement */ ? node.parent.parent : node)) { checkAliasSymbol(node); return; } @@ -83747,7 +84416,7 @@ var ts; ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 246 /* SyntaxKind.ForInStatement */) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); } } @@ -83773,10 +84442,10 @@ var ts; error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 167 /* SyntaxKind.PropertyDeclaration */ && node.kind !== 166 /* SyntaxKind.PropertySignature */) { + if (node.kind !== 169 /* SyntaxKind.PropertyDeclaration */ && node.kind !== 168 /* SyntaxKind.PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 254 /* SyntaxKind.VariableDeclaration */ || node.kind === 203 /* SyntaxKind.BindingElement */) { + if (node.kind === 257 /* SyntaxKind.VariableDeclaration */ || node.kind === 205 /* SyntaxKind.BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionsForDeclarationName(node, node.name); @@ -83784,7 +84453,7 @@ var ts; } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 167 /* SyntaxKind.PropertyDeclaration */ || nextDeclaration.kind === 166 /* SyntaxKind.PropertySignature */ + var message = nextDeclaration.kind === 169 /* SyntaxKind.PropertyDeclaration */ || nextDeclaration.kind === 168 /* SyntaxKind.PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; var declName = ts.declarationNameToString(nextDeclarationName); @@ -83794,8 +84463,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 164 /* SyntaxKind.Parameter */ && right.kind === 254 /* SyntaxKind.VariableDeclaration */) || - (left.kind === 254 /* SyntaxKind.VariableDeclaration */ && right.kind === 164 /* SyntaxKind.Parameter */)) { + if ((left.kind === 166 /* SyntaxKind.Parameter */ && right.kind === 257 /* SyntaxKind.VariableDeclaration */) || + (left.kind === 257 /* SyntaxKind.VariableDeclaration */ && right.kind === 166 /* SyntaxKind.Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -83804,8 +84473,8 @@ var ts; } var interestingFlags = 8 /* ModifierFlags.Private */ | 16 /* ModifierFlags.Protected */ | - 256 /* ModifierFlags.Async */ | - 128 /* ModifierFlags.Abstract */ | + 512 /* ModifierFlags.Async */ | + 256 /* ModifierFlags.Abstract */ | 64 /* ModifierFlags.Readonly */ | 32 /* ModifierFlags.Static */; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); @@ -83834,15 +84503,15 @@ var ts; function checkIfStatement(node) { // Grammar checking checkGrammarStatementInAmbientContext(node); - checkTruthinessExpression(node.expression); - checkTestingKnownTruthyCallableOrAwaitableType(node.expression, node.thenStatement); + var type = checkTruthinessExpression(node.expression); + checkTestingKnownTruthyCallableOrAwaitableType(node.expression, type, node.thenStatement); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 236 /* SyntaxKind.EmptyStatement */) { + if (node.thenStatement.kind === 239 /* SyntaxKind.EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); } - function checkTestingKnownTruthyCallableOrAwaitableType(condExpr, body) { + function checkTestingKnownTruthyCallableOrAwaitableType(condExpr, condType, body) { if (!strictNullChecks) return; helper(condExpr, body); @@ -83857,7 +84526,7 @@ var ts; : condExpr; if (ts.isModuleExportsAccessExpression(location)) return; - var type = checkTruthinessExpression(location); + var type = location === condExpr ? condType : checkTruthinessExpression(location); var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) && isTypeAssertion(location.expression); if (!(getTypeFacts(type) & 4194304 /* TypeFacts.Truthy */) || isPropertyExpressionCast) return; @@ -83971,12 +84640,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 258 /* SyntaxKind.VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (node.initializer.kind === 258 /* SyntaxKind.VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -84016,14 +84685,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (node.initializer.kind === 258 /* SyntaxKind.VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node); // There may be a destructuring assignment on the left side - if (varExpr.kind === 204 /* SyntaxKind.ArrayLiteralExpression */ || varExpr.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { + if (varExpr.kind === 206 /* SyntaxKind.ArrayLiteralExpression */ || varExpr.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -84055,7 +84724,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (node.initializer.kind === 258 /* SyntaxKind.VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -84069,7 +84738,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 204 /* SyntaxKind.ArrayLiteralExpression */ || varExpr.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { + if (varExpr.kind === 206 /* SyntaxKind.ArrayLiteralExpression */ || varExpr.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -84551,7 +85220,16 @@ var ts; var message = allowAsyncIterables ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator; - return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + var suggestAwait = + // for (const x of Promise<...>) or [...Promise<...>] + !!getAwaitedTypeOfPromise(type) + // for (const x of AsyncIterable<...>) + || (!allowAsyncIterables && + ts.isForOfStatement(errorNode.parent) && + errorNode.parent.expression === errorNode && + getGlobalAsyncIterableType(/** reportErrors */ false) !== emptyGenericType && + isTypeAssignableTo(type, getGlobalAsyncIterableType(/** reportErrors */ false))); + return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. @@ -84869,12 +85547,12 @@ var ts; var functionFlags = ts.getFunctionFlags(container); if (strictNullChecks || node.expression || returnType.flags & 131072 /* TypeFlags.Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (container.kind === 173 /* SyntaxKind.SetAccessor */) { + if (container.kind === 175 /* SyntaxKind.SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (container.kind === 171 /* SyntaxKind.Constructor */) { + else if (container.kind === 173 /* SyntaxKind.Constructor */) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -84892,7 +85570,7 @@ var ts; } } } - else if (container.kind !== 171 /* SyntaxKind.Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(container, returnType)) { + else if (container.kind !== 173 /* SyntaxKind.Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(container, returnType)) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -84921,7 +85599,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 290 /* SyntaxKind.DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 293 /* SyntaxKind.DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -84930,7 +85608,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (clause.kind === 289 /* SyntaxKind.CaseClause */) { + if (clause.kind === 292 /* SyntaxKind.CaseClause */) { addLazyDiagnostic(createLazyCaseClauseDiagnostics(clause)); } ts.forEach(clause.statements, checkSourceElement); @@ -84967,7 +85645,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 250 /* SyntaxKind.LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 253 /* SyntaxKind.LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -85062,9 +85740,9 @@ var ts; return; } var indexInfos = getApplicableIndexInfos(type, propNameType); - var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; - var propDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || - name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; + var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 261 /* SyntaxKind.InterfaceDeclaration */) : undefined; + var propDeclaration = declaration && declaration.kind === 223 /* SyntaxKind.BinaryExpression */ || + name && name.kind === 164 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; var _loop_30 = function (info) { var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; @@ -85089,7 +85767,7 @@ var ts; function checkIndexConstraintForIndexSignature(type, checkInfo) { var declaration = checkInfo.declaration; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); - var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; + var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 261 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; var _loop_31 = function (info) { if (info === checkInfo) @@ -85161,7 +85839,7 @@ var ts; } else { ts.forEach(jsdocParameters, function (_a, index) { - var name = _a.name; + var name = _a.name, isNameFirst = _a.isNameFirst; if (excludedParameters.has(index) || ts.isIdentifier(name) && parameters.has(name.escapedText)) { return; } @@ -85171,7 +85849,9 @@ var ts; } } else { - errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + if (!isNameFirst) { + errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + } } }); } @@ -85209,7 +85889,7 @@ var ts; function checkTypeParametersNotReferenced(root, typeParameters, index) { visit(root); function visit(node) { - if (node.kind === 178 /* SyntaxKind.TypeReference */) { + if (node.kind === 180 /* SyntaxKind.TypeReference */) { var type = getTypeFromTypeReference(node); if (type.flags & 262144 /* TypeFlags.TypeParameter */) { for (var i = index; i < typeParameters.length; i++) { @@ -85299,7 +85979,7 @@ var ts; if (firstDecorator && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { grammarErrorOnNode(firstDecorator, ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); } - if (!node.name && !ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)) { + if (!node.name && !ts.hasSyntacticModifier(node, 1024 /* ModifierFlags.Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -85366,7 +86046,7 @@ var ts; } else { var constructSignatures = getSignaturesOfType(baseConstructorType, 1 /* SignatureKind.Construct */); - if (constructSignatures.some(function (signature) { return signature.flags & 4 /* SignatureFlags.Abstract */; }) && !ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)) { + if (constructSignatures.some(function (signature) { return signature.flags & 4 /* SignatureFlags.Abstract */; }) && !ts.hasSyntacticModifier(node, 256 /* ModifierFlags.Abstract */)) { error(node.name || node, ts.Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract); } } @@ -85601,7 +86281,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 257 /* SyntaxKind.ClassDeclaration */ || d.kind === 258 /* SyntaxKind.InterfaceDeclaration */; + return d.kind === 260 /* SyntaxKind.ClassDeclaration */ || d.kind === 261 /* SyntaxKind.InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -85642,7 +86322,7 @@ var ts; // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. - if (baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && (!derivedClassDecl || !ts.hasSyntacticModifier(derivedClassDecl, 128 /* ModifierFlags.Abstract */))) { + if (baseDeclarationFlags & 256 /* ModifierFlags.Abstract */ && (!derivedClassDecl || !ts.hasSyntacticModifier(derivedClassDecl, 256 /* ModifierFlags.Abstract */))) { // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) @@ -85656,7 +86336,7 @@ var ts; return "continue-basePropertyCheck"; } } - if (derivedClassDecl.kind === 226 /* SyntaxKind.ClassExpression */) { + if (derivedClassDecl.kind === 228 /* SyntaxKind.ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -85691,11 +86371,11 @@ var ts; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } else if (useDefineForClassFields) { - var uninitialized = (_c = derived.declarations) === null || _c === void 0 ? void 0 : _c.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); + var uninitialized = (_c = derived.declarations) === null || _c === void 0 ? void 0 : _c.find(function (d) { return d.kind === 169 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* SymbolFlags.Transient */) - && !(baseDeclarationFlags & 128 /* ModifierFlags.Abstract */) - && !(derivedDeclarationFlags & 128 /* ModifierFlags.Abstract */) + && !(baseDeclarationFlags & 256 /* ModifierFlags.Abstract */) + && !(derivedDeclarationFlags & 256 /* ModifierFlags.Abstract */) && !((_d = derived.declarations) === null || _d === void 0 ? void 0 : _d.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; @@ -85738,7 +86418,7 @@ var ts; } } function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) { - return baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && (!ts.isPropertyDeclaration(declaration) || !declaration.initializer) + return baseDeclarationFlags & 256 /* ModifierFlags.Abstract */ && (!ts.isPropertyDeclaration(declaration) || !declaration.initializer) || ts.isInterfaceDeclaration(declaration.parent); } function getNonInheritedProperties(type, baseTypes, properties) { @@ -85820,7 +86500,7 @@ var ts; } } function isPropertyWithoutInitializer(node) { - return node.kind === 167 /* SyntaxKind.PropertyDeclaration */ && + return node.kind === 169 /* SyntaxKind.PropertyDeclaration */ && !ts.hasAbstractModifier(node) && !node.exclamationToken && !node.initializer; @@ -85863,7 +86543,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 258 /* SyntaxKind.InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 261 /* SyntaxKind.InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -85896,7 +86576,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); checkExportsOnMergedDeclarations(node); checkTypeParameters(node.typeParameters); - if (node.type.kind === 138 /* SyntaxKind.IntrinsicKeyword */) { + if (node.type.kind === 139 /* SyntaxKind.IntrinsicKeyword */) { if (!intrinsicTypeKinds.has(node.name.escapedText) || ts.length(node.typeParameters) !== 1) { error(node.type, ts.Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types); } @@ -85982,7 +86662,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { @@ -85992,7 +86672,7 @@ var ts; } } break; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -86021,7 +86701,7 @@ var ts; case 8 /* SyntaxKind.NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return evaluate(expr.expression); case 79 /* SyntaxKind.Identifier */: var identifier = expr; @@ -86029,13 +86709,13 @@ var ts; return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 207 /* SyntaxKind.ElementAccessExpression */: - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: if (isConstantMemberAccess(expr)) { var type = getTypeOfExpression(expr.expression); if (type.symbol && type.symbol.flags & 384 /* SymbolFlags.Enum */) { var name = void 0; - if (expr.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + if (expr.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { name = expr.name.escapedText; } else { @@ -86072,8 +86752,8 @@ var ts; return false; } return node.kind === 79 /* SyntaxKind.Identifier */ || - node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 207 /* SyntaxKind.ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.kind === 208 /* SyntaxKind.PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 209 /* SyntaxKind.ElementAccessExpression */ && isConstantMemberAccess(node.expression) && ts.isStringLiteralLike(node.argumentExpression); } function checkEnumDeclaration(node) { @@ -86107,7 +86787,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 260 /* SyntaxKind.EnumDeclaration */) { + if (declaration.kind !== 263 /* SyntaxKind.EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -86136,8 +86816,8 @@ var ts; if (declarations) { for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { var declaration = declarations_9[_i]; - if ((declaration.kind === 257 /* SyntaxKind.ClassDeclaration */ || - (declaration.kind === 256 /* SyntaxKind.FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 260 /* SyntaxKind.ClassDeclaration */ || + (declaration.kind === 259 /* SyntaxKind.FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 16777216 /* NodeFlags.Ambient */)) { return declaration; } @@ -86208,7 +86888,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 257 /* SyntaxKind.ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 260 /* SyntaxKind.ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* NodeCheckFlags.LexicalModuleMergesWithClass */; @@ -86251,56 +86931,43 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { - var _a; switch (node.kind) { - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { - var decl = _b[_i]; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 271 /* SyntaxKind.ExportAssignment */: - case 272 /* SyntaxKind.ExportDeclaration */: + case 274 /* SyntaxKind.ExportAssignment */: + case 275 /* SyntaxKind.ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 266 /* SyntaxKind.ImportDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 203 /* SyntaxKind.BindingElement */: - case 254 /* SyntaxKind.VariableDeclaration */: + case 205 /* SyntaxKind.BindingElement */: + case 257 /* SyntaxKind.VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { - var el = _d[_c]; + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } break; } // falls through - case 257 /* SyntaxKind.ClassDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } - var symbol = getSymbolOfNode(node); - if (symbol) { - // module augmentations cannot introduce new names on the top level scope of the module - // this is done it two steps - // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error - // 2. main check - report error if value declaration of the parent symbol is module augmentation) - var reportError = !(symbol.flags & 33554432 /* SymbolFlags.Transient */); - if (!reportError) { - // symbol should not originate in augmentation - reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } break; } } @@ -86308,12 +86975,12 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: return node; - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: do { node = node.left; } while (node.kind !== 79 /* SyntaxKind.Identifier */); return node; - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: do { if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) { return node.name; @@ -86333,9 +87000,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 305 /* SyntaxKind.SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 272 /* SyntaxKind.ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 265 /* SyntaxKind.ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 308 /* SyntaxKind.SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 275 /* SyntaxKind.ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -86382,8 +87049,8 @@ var ts; var errorNode = ts.isImportOrExportSpecifier(node) ? node.propertyName || node.name : ts.isNamedDeclaration(node) ? node.name : node; - ts.Debug.assert(node.kind !== 274 /* SyntaxKind.NamespaceExport */); - if (node.kind === 275 /* SyntaxKind.ExportSpecifier */) { + ts.Debug.assert(node.kind !== 277 /* SyntaxKind.NamespaceExport */); + if (node.kind === 278 /* SyntaxKind.ExportSpecifier */) { var diag = error(errorNode, ts.Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); var alreadyExportedSymbol = (_b = (_a = ts.getSourceFileOfNode(node).symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.get((node.propertyName || node.name).escapedText); if (alreadyExportedSymbol === target) { @@ -86394,7 +87061,7 @@ var ts; } } else { - ts.Debug.assert(node.kind !== 254 /* SyntaxKind.VariableDeclaration */); + ts.Debug.assert(node.kind !== 257 /* SyntaxKind.VariableDeclaration */); var importDeclaration = ts.findAncestor(node, ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration)); var moduleSpecifier = (_e = (importDeclaration && ((_d = ts.tryGetModuleSpecifierFromDeclaration(importDeclaration)) === null || _d === void 0 ? void 0 : _d.text))) !== null && _e !== void 0 ? _e : "..."; var importedIdentifier = ts.unescapeLeadingUnderscores(ts.isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName); @@ -86402,11 +87069,12 @@ var ts; } return; } + var targetFlags = getAllSymbolFlags(target); var excludedMeanings = (symbol.flags & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */) ? 111551 /* SymbolFlags.Value */ : 0) | (symbol.flags & 788968 /* SymbolFlags.Type */ ? 788968 /* SymbolFlags.Type */ : 0) | (symbol.flags & 1920 /* SymbolFlags.Namespace */ ? 1920 /* SymbolFlags.Namespace */ : 0); - if (target.flags & excludedMeanings) { - var message = node.kind === 275 /* SyntaxKind.ExportSpecifier */ ? + if (targetFlags & excludedMeanings) { + var message = node.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -86415,26 +87083,26 @@ var ts; && !ts.isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 16777216 /* NodeFlags.Ambient */)) { var typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol); - var isType = !(target.flags & 111551 /* SymbolFlags.Value */); + var isType = !(targetFlags & 111551 /* SymbolFlags.Value */); if (isType || typeOnlyAlias) { switch (node.kind) { - case 267 /* SyntaxKind.ImportClause */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: { + case 270 /* SyntaxKind.ImportClause */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: { if (compilerOptions.preserveValueImports) { ts.Debug.assertIsDefined(node.name, "An ImportClause with a symbol should have a name"); var message = isType ? ts.Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled : ts.Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled; - var name = ts.idText(node.kind === 270 /* SyntaxKind.ImportSpecifier */ ? node.propertyName || node.name : node.name); + var name = ts.idText(node.kind === 273 /* SyntaxKind.ImportSpecifier */ ? node.propertyName || node.name : node.name); addTypeOnlyDeclarationRelatedInfo(error(node, message, name), isType ? undefined : typeOnlyAlias, name); } - if (isType && node.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ && ts.hasEffectiveModifier(node, 1 /* ModifierFlags.Export */)) { + if (isType && node.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ && ts.hasEffectiveModifier(node, 1 /* ModifierFlags.Export */)) { error(node, ts.Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_the_isolatedModules_flag_is_provided); } break; } - case 275 /* SyntaxKind.ExportSpecifier */: { + case 278 /* SyntaxKind.ExportSpecifier */: { // Don't allow re-exporting an export that will be elided when `--isolatedModules` is set. // The exception is that `import type { A } from './a'; export { A }` is allowed // because single-file analysis can determine that the export should be dropped. @@ -86493,7 +87161,7 @@ var ts; function checkImportBinding(node) { checkCollisionsForDeclarationName(node, node.name); checkAliasSymbol(node); - if (node.kind === 270 /* SyntaxKind.ImportSpecifier */ && + if (node.kind === 273 /* SyntaxKind.ImportSpecifier */ && ts.idText(node.propertyName || node.name) === "default" && ts.getESModuleInterop(compilerOptions) && moduleKind !== ts.ModuleKind.System && (moduleKind < ts.ModuleKind.ES2015 || ts.getSourceFileOfNode(node).impliedNodeFormat === ts.ModuleKind.CommonJS)) { @@ -86543,7 +87211,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { + if (importClause.namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */) { checkImportBinding(importClause.namedBindings); if (moduleKind !== ts.ModuleKind.System && (moduleKind < ts.ModuleKind.ES2015 || ts.getSourceFileOfNode(node).impliedNodeFormat === ts.ModuleKind.CommonJS) && ts.getESModuleInterop(compilerOptions)) { // import * as ns from "foo"; @@ -86572,17 +87240,18 @@ var ts; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 277 /* SyntaxKind.ExternalModuleReference */) { + if (node.moduleReference.kind !== 280 /* SyntaxKind.ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 111551 /* SymbolFlags.Value */) { + var targetFlags = getAllSymbolFlags(target); + if (targetFlags & 111551 /* SymbolFlags.Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* SymbolFlags.Value */ | 1920 /* SymbolFlags.Namespace */).flags & 1920 /* SymbolFlags.Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 788968 /* SymbolFlags.Type */) { + if (targetFlags & 788968 /* SymbolFlags.Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -86615,10 +87284,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 265 /* SyntaxKind.ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 265 /* SyntaxKind.ModuleBlock */ && !node.moduleSpecifier && node.flags & 16777216 /* NodeFlags.Ambient */; - if (node.parent.kind !== 305 /* SyntaxKind.SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 308 /* SyntaxKind.SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -86653,7 +87322,7 @@ var ts; function checkGrammarExportDeclaration(node) { var _a; if (node.isTypeOnly) { - if (((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) === 273 /* SyntaxKind.NamedExports */) { + if (((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) === 276 /* SyntaxKind.NamedExports */) { return checkGrammarNamedImportsOrExports(node.exportClause); } else { @@ -86663,7 +87332,7 @@ var ts; return false; } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 305 /* SyntaxKind.SourceFile */ || node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 261 /* SyntaxKind.ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 308 /* SyntaxKind.SourceFile */ || node.parent.kind === 265 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 264 /* SyntaxKind.ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -86721,7 +87390,7 @@ var ts; markExportAsReferenced(node); } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); - if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (!target || getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); } } @@ -86743,8 +87412,8 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 305 /* SyntaxKind.SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 261 /* SyntaxKind.ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 308 /* SyntaxKind.SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 264 /* SyntaxKind.ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -86768,7 +87437,7 @@ var ts; markAliasReferenced(sym, id); // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`) var target = sym.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(sym) : sym; - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { // However if it is a value, we need to check it's being used correctly checkExpressionCached(node.expression); } @@ -86876,181 +87545,181 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 261 /* SyntaxKind.ModuleDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } - if (kind >= 237 /* SyntaxKind.FirstStatement */ && kind <= 253 /* SyntaxKind.LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { + if (kind >= 240 /* SyntaxKind.FirstStatement */ && kind <= 256 /* SyntaxKind.LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected); } switch (kind) { - case 163 /* SyntaxKind.TypeParameter */: + case 165 /* SyntaxKind.TypeParameter */: return checkTypeParameter(node); - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return checkParameter(node); - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: return checkPropertyDeclaration(node); - case 166 /* SyntaxKind.PropertySignature */: + case 168 /* SyntaxKind.PropertySignature */: return checkPropertySignature(node); - case 180 /* SyntaxKind.ConstructorType */: - case 179 /* SyntaxKind.FunctionType */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 176 /* SyntaxKind.IndexSignature */: + case 182 /* SyntaxKind.ConstructorType */: + case 181 /* SyntaxKind.FunctionType */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 178 /* SyntaxKind.IndexSignature */: return checkSignatureDeclaration(node); - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: return checkMethodDeclaration(node); - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: return checkClassStaticBlockDeclaration(node); - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return checkConstructorDeclaration(node); - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return checkAccessorDeclaration(node); - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return checkTypeReferenceNode(node); - case 177 /* SyntaxKind.TypePredicate */: + case 179 /* SyntaxKind.TypePredicate */: return checkTypePredicate(node); - case 181 /* SyntaxKind.TypeQuery */: + case 183 /* SyntaxKind.TypeQuery */: return checkTypeQuery(node); - case 182 /* SyntaxKind.TypeLiteral */: + case 184 /* SyntaxKind.TypeLiteral */: return checkTypeLiteral(node); - case 183 /* SyntaxKind.ArrayType */: + case 185 /* SyntaxKind.ArrayType */: return checkArrayType(node); - case 184 /* SyntaxKind.TupleType */: + case 186 /* SyntaxKind.TupleType */: return checkTupleType(node); - case 187 /* SyntaxKind.UnionType */: - case 188 /* SyntaxKind.IntersectionType */: + case 189 /* SyntaxKind.UnionType */: + case 190 /* SyntaxKind.IntersectionType */: return checkUnionOrIntersectionType(node); - case 191 /* SyntaxKind.ParenthesizedType */: - case 185 /* SyntaxKind.OptionalType */: - case 186 /* SyntaxKind.RestType */: + case 193 /* SyntaxKind.ParenthesizedType */: + case 187 /* SyntaxKind.OptionalType */: + case 188 /* SyntaxKind.RestType */: return checkSourceElement(node.type); - case 192 /* SyntaxKind.ThisType */: + case 194 /* SyntaxKind.ThisType */: return checkThisType(node); - case 193 /* SyntaxKind.TypeOperator */: + case 195 /* SyntaxKind.TypeOperator */: return checkTypeOperator(node); - case 189 /* SyntaxKind.ConditionalType */: + case 191 /* SyntaxKind.ConditionalType */: return checkConditionalType(node); - case 190 /* SyntaxKind.InferType */: + case 192 /* SyntaxKind.InferType */: return checkInferType(node); - case 198 /* SyntaxKind.TemplateLiteralType */: + case 200 /* SyntaxKind.TemplateLiteralType */: return checkTemplateLiteralType(node); - case 200 /* SyntaxKind.ImportType */: + case 202 /* SyntaxKind.ImportType */: return checkImportType(node); - case 197 /* SyntaxKind.NamedTupleMember */: + case 199 /* SyntaxKind.NamedTupleMember */: return checkNamedTupleMember(node); - case 328 /* SyntaxKind.JSDocAugmentsTag */: + case 331 /* SyntaxKind.JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 329 /* SyntaxKind.JSDocImplementsTag */: + case 332 /* SyntaxKind.JSDocImplementsTag */: return checkJSDocImplementsTag(node); - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 339 /* SyntaxKind.JSDocEnumTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: return checkJSDocTypeAliasTag(node); - case 344 /* SyntaxKind.JSDocTemplateTag */: + case 347 /* SyntaxKind.JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 343 /* SyntaxKind.JSDocTypeTag */: + case 346 /* SyntaxKind.JSDocTypeTag */: return checkJSDocTypeTag(node); - case 324 /* SyntaxKind.JSDocLink */: - case 325 /* SyntaxKind.JSDocLinkCode */: - case 326 /* SyntaxKind.JSDocLinkPlain */: + case 327 /* SyntaxKind.JSDocLink */: + case 328 /* SyntaxKind.JSDocLinkCode */: + case 329 /* SyntaxKind.JSDocLinkPlain */: return checkJSDocLinkLikeTag(node); - case 340 /* SyntaxKind.JSDocParameterTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: return checkJSDocParameterTag(node); - case 347 /* SyntaxKind.JSDocPropertyTag */: + case 350 /* SyntaxKind.JSDocPropertyTag */: return checkJSDocPropertyTag(node); - case 317 /* SyntaxKind.JSDocFunctionType */: + case 320 /* SyntaxKind.JSDocFunctionType */: checkJSDocFunctionType(node); // falls through - case 315 /* SyntaxKind.JSDocNonNullableType */: - case 314 /* SyntaxKind.JSDocNullableType */: - case 312 /* SyntaxKind.JSDocAllType */: - case 313 /* SyntaxKind.JSDocUnknownType */: - case 322 /* SyntaxKind.JSDocTypeLiteral */: + case 318 /* SyntaxKind.JSDocNonNullableType */: + case 317 /* SyntaxKind.JSDocNullableType */: + case 315 /* SyntaxKind.JSDocAllType */: + case 316 /* SyntaxKind.JSDocUnknownType */: + case 325 /* SyntaxKind.JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 318 /* SyntaxKind.JSDocVariadicType */: + case 321 /* SyntaxKind.JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 309 /* SyntaxKind.JSDocTypeExpression */: + case 312 /* SyntaxKind.JSDocTypeExpression */: return checkSourceElement(node.type); - case 333 /* SyntaxKind.JSDocPublicTag */: - case 335 /* SyntaxKind.JSDocProtectedTag */: - case 334 /* SyntaxKind.JSDocPrivateTag */: + case 336 /* SyntaxKind.JSDocPublicTag */: + case 338 /* SyntaxKind.JSDocProtectedTag */: + case 337 /* SyntaxKind.JSDocPrivateTag */: return checkJSDocAccessibilityModifiers(node); - case 194 /* SyntaxKind.IndexedAccessType */: + case 196 /* SyntaxKind.IndexedAccessType */: return checkIndexedAccessType(node); - case 195 /* SyntaxKind.MappedType */: + case 197 /* SyntaxKind.MappedType */: return checkMappedType(node); - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return checkFunctionDeclaration(node); - case 235 /* SyntaxKind.Block */: - case 262 /* SyntaxKind.ModuleBlock */: + case 238 /* SyntaxKind.Block */: + case 265 /* SyntaxKind.ModuleBlock */: return checkBlock(node); - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return checkVariableStatement(node); - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: return checkExpressionStatement(node); - case 239 /* SyntaxKind.IfStatement */: + case 242 /* SyntaxKind.IfStatement */: return checkIfStatement(node); - case 240 /* SyntaxKind.DoStatement */: + case 243 /* SyntaxKind.DoStatement */: return checkDoStatement(node); - case 241 /* SyntaxKind.WhileStatement */: + case 244 /* SyntaxKind.WhileStatement */: return checkWhileStatement(node); - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return checkForStatement(node); - case 243 /* SyntaxKind.ForInStatement */: + case 246 /* SyntaxKind.ForInStatement */: return checkForInStatement(node); - case 244 /* SyntaxKind.ForOfStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return checkForOfStatement(node); - case 245 /* SyntaxKind.ContinueStatement */: - case 246 /* SyntaxKind.BreakStatement */: + case 248 /* SyntaxKind.ContinueStatement */: + case 249 /* SyntaxKind.BreakStatement */: return checkBreakOrContinueStatement(node); - case 247 /* SyntaxKind.ReturnStatement */: + case 250 /* SyntaxKind.ReturnStatement */: return checkReturnStatement(node); - case 248 /* SyntaxKind.WithStatement */: + case 251 /* SyntaxKind.WithStatement */: return checkWithStatement(node); - case 249 /* SyntaxKind.SwitchStatement */: + case 252 /* SyntaxKind.SwitchStatement */: return checkSwitchStatement(node); - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: return checkLabeledStatement(node); - case 251 /* SyntaxKind.ThrowStatement */: + case 254 /* SyntaxKind.ThrowStatement */: return checkThrowStatement(node); - case 252 /* SyntaxKind.TryStatement */: + case 255 /* SyntaxKind.TryStatement */: return checkTryStatement(node); - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return checkVariableDeclaration(node); - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: return checkBindingElement(node); - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: return checkClassDeclaration(node); - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return checkEnumDeclaration(node); - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return checkModuleDeclaration(node); - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return checkImportDeclaration(node); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: return checkExportDeclaration(node); - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: return checkExportAssignment(node); - case 236 /* SyntaxKind.EmptyStatement */: - case 253 /* SyntaxKind.DebuggerStatement */: + case 239 /* SyntaxKind.EmptyStatement */: + case 256 /* SyntaxKind.DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 276 /* SyntaxKind.MissingDeclaration */: + case 279 /* SyntaxKind.MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -87157,36 +87826,36 @@ var ts; currentNode = node; instantiationCount = 0; switch (node.kind) { - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: - case 210 /* SyntaxKind.TaggedTemplateExpression */: - case 165 /* SyntaxKind.Decorator */: - case 280 /* SyntaxKind.JsxOpeningElement */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: + case 167 /* SyntaxKind.Decorator */: + case 283 /* SyntaxKind.JsxOpeningElement */: // These node kinds are deferred checked when overload resolution fails // To save on work, we ensure the arguments are checked just once, in // a deferred way resolveUntypedCall(node); break; - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: checkAccessorDeclaration(node); break; - case 226 /* SyntaxKind.ClassExpression */: + case 228 /* SyntaxKind.ClassExpression */: checkClassExpressionDeferred(node); break; - case 163 /* SyntaxKind.TypeParameter */: + case 165 /* SyntaxKind.TypeParameter */: checkTypeParameterDeferred(node); break; - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: checkJsxSelfClosingElementDeferred(node); break; - case 278 /* SyntaxKind.JsxElement */: + case 281 /* SyntaxKind.JsxElement */: checkJsxElementDeferred(node); break; } @@ -87359,17 +88028,17 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: if (!ts.isExternalModule(location)) break; // falls through - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* SymbolFlags.ModuleMember */); break; - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* SymbolFlags.EnumMember */); break; - case 226 /* SyntaxKind.ClassExpression */: + case 228 /* SyntaxKind.ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -87377,8 +88046,8 @@ var ts; // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration. // falls through - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -87387,7 +88056,7 @@ var ts; copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* SymbolFlags.Type */); } break; - case 213 /* SyntaxKind.FunctionExpression */: + case 215 /* SyntaxKind.FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -87434,7 +88103,7 @@ var ts; if (meaning) { source.forEach(function (symbol) { // Similar condition as in `resolveNameHelper` - if (!ts.getDeclarationOfKind(symbol, 275 /* SyntaxKind.ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 274 /* SyntaxKind.NamespaceExport */)) { + if (!ts.getDeclarationOfKind(symbol, 278 /* SyntaxKind.ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 277 /* SyntaxKind.NamespaceExport */)) { copySymbol(symbol, meaning); } }); @@ -87443,41 +88112,21 @@ var ts; } function isTypeDeclarationName(name) { return name.kind === 79 /* SyntaxKind.Identifier */ && - isTypeDeclaration(name.parent) && + ts.isTypeDeclaration(name.parent) && ts.getNameOfDeclaration(name.parent) === name; } - function isTypeDeclaration(node) { - switch (node.kind) { - case 163 /* SyntaxKind.TypeParameter */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 339 /* SyntaxKind.JSDocEnumTag */: - return true; - case 267 /* SyntaxKind.ImportClause */: - return node.isTypeOnly; - case 270 /* SyntaxKind.ImportSpecifier */: - case 275 /* SyntaxKind.ExportSpecifier */: - return node.parent.parent.isTypeOnly; - default: - return false; - } - } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 161 /* SyntaxKind.QualifiedName */) { + while (node.parent.kind === 163 /* SyntaxKind.QualifiedName */) { node = node.parent; } - return node.parent.kind === 178 /* SyntaxKind.TypeReference */; + return node.parent.kind === 180 /* SyntaxKind.TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + while (node.parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */; + return node.parent.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -87505,13 +88154,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 161 /* SyntaxKind.QualifiedName */) { + while (nodeOnRightSide.parent.kind === 163 /* SyntaxKind.QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 271 /* SyntaxKind.ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 274 /* SyntaxKind.ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -87537,7 +88186,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 200 /* SyntaxKind.ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 202 /* SyntaxKind.ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -87547,7 +88196,7 @@ var ts; return getSymbolOfNode(name.parent); } if (ts.isInJSFile(name) && - name.parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && + name.parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */ && name.parent === name.parent.parent.left) { // Check if this is a special property assignment if (!ts.isPrivateIdentifier(name) && !ts.isJSDocMemberName(name)) { @@ -87557,7 +88206,7 @@ var ts; } } } - if (name.parent.kind === 271 /* SyntaxKind.ExportAssignment */ && ts.isEntityNameExpression(name)) { + if (name.parent.kind === 274 /* SyntaxKind.ExportAssignment */ && ts.isEntityNameExpression(name)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(name, /*all meanings*/ 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */ | 2097152 /* SymbolFlags.Alias */, /*ignoreErrors*/ true); @@ -87567,7 +88216,7 @@ var ts; } else if (ts.isEntityName(name) && isInRightSideOfImportOrExportAssignment(name)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(name, 265 /* SyntaxKind.ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(name, 268 /* SyntaxKind.ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true); } @@ -87585,7 +88234,7 @@ var ts; if (isHeritageClauseElementIdentifier(name)) { var meaning = 0 /* SymbolFlags.None */; // In an interface or class, we're definitely interested in a type. - if (name.parent.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */) { + if (name.parent.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */) { meaning = 788968 /* SymbolFlags.Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) { @@ -87601,10 +88250,10 @@ var ts; return entityNameSymbol; } } - if (name.parent.kind === 340 /* SyntaxKind.JSDocParameterTag */) { + if (name.parent.kind === 343 /* SyntaxKind.JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(name.parent); } - if (name.parent.kind === 163 /* SyntaxKind.TypeParameter */ && name.parent.parent.kind === 344 /* SyntaxKind.JSDocTemplateTag */) { + if (name.parent.kind === 165 /* SyntaxKind.TypeParameter */ && name.parent.parent.kind === 347 /* SyntaxKind.JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(name.parent); return typeParameter && typeParameter.symbol; @@ -87628,18 +88277,53 @@ var ts; return resolveJSDocMemberName(name, /*ignoreErrors*/ false, getSymbolOfNode(container)); } } + if (result && isJSDoc_1) { + var container = ts.getJSDocHost(name); + if (container && ts.isEnumMember(container) && container === result.valueDeclaration) { + return resolveEntityName(name, meaning, /*ignoreErrors*/ true, /* dontResolveAlias */ true, ts.getSourceFileOfNode(container)) || result; + } + } return result; } else if (ts.isPrivateIdentifier(name)) { return getSymbolForPrivateIdentifierExpression(name); } - else if (name.kind === 206 /* SyntaxKind.PropertyAccessExpression */ || name.kind === 161 /* SyntaxKind.QualifiedName */) { + else if (name.kind === 208 /* SyntaxKind.PropertyAccessExpression */ || name.kind === 163 /* SyntaxKind.QualifiedName */) { var links = getNodeLinks(name); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (name.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + if (name.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { checkPropertyAccessExpression(name, 0 /* CheckMode.Normal */); + if (!links.resolvedSymbol) { + var expressionType = checkExpressionCached(name.expression); + var infos = getApplicableIndexInfos(expressionType, getLiteralTypeFromPropertyName(name.name)); + if (infos.length && expressionType.members) { + var resolved = resolveStructuredTypeMembers(expressionType); + var symbol = resolved.members.get("__index" /* InternalSymbolName.Index */); + if (infos === getIndexInfosOfType(expressionType)) { + links.resolvedSymbol = symbol; + } + else if (symbol) { + var symbolLinks_1 = getSymbolLinks(symbol); + var declarationList = ts.mapDefined(infos, function (i) { return i.declaration; }); + var nodeListId = ts.map(declarationList, getNodeId).join(","); + if (!symbolLinks_1.filteredIndexSymbolCache) { + symbolLinks_1.filteredIndexSymbolCache = new ts.Map(); + } + if (symbolLinks_1.filteredIndexSymbolCache.has(nodeListId)) { + links.resolvedSymbol = symbolLinks_1.filteredIndexSymbolCache.get(nodeListId); + } + else { + var copy = createSymbol(131072 /* SymbolFlags.Signature */, "__index" /* InternalSymbolName.Index */); + copy.declarations = ts.mapDefined(infos, function (i) { return i.declaration; }); + copy.parent = expressionType.aliasSymbol ? expressionType.aliasSymbol : expressionType.symbol ? expressionType.symbol : getSymbolAtLocation(copy.declarations[0].parent); + symbolLinks_1.filteredIndexSymbolCache.set(nodeListId, copy); + links.resolvedSymbol = symbolLinks_1.filteredIndexSymbolCache.get(nodeListId); + } + } + } + } } else { checkQualifiedName(name, 0 /* CheckMode.Normal */); @@ -87654,11 +88338,11 @@ var ts; } } else if (isTypeReferenceIdentifier(name)) { - var meaning = name.parent.kind === 178 /* SyntaxKind.TypeReference */ ? 788968 /* SymbolFlags.Type */ : 1920 /* SymbolFlags.Namespace */; + var meaning = name.parent.kind === 180 /* SyntaxKind.TypeReference */ ? 788968 /* SymbolFlags.Type */ : 1920 /* SymbolFlags.Namespace */; var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); return symbol && symbol !== unknownSymbol ? symbol : getUnresolvedSymbolForEntityName(name); } - if (name.parent.kind === 177 /* SyntaxKind.TypePredicate */) { + if (name.parent.kind === 179 /* SyntaxKind.TypePredicate */) { return resolveEntityName(name, /*meaning*/ 1 /* SymbolFlags.FunctionScopedVariable */); } return undefined; @@ -87692,7 +88376,7 @@ var ts; } } function getSymbolAtLocation(node, ignoreErrors) { - if (node.kind === 305 /* SyntaxKind.SourceFile */) { + if (node.kind === 308 /* SyntaxKind.SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -87715,8 +88399,8 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfNameOrPropertyAccessExpression(node); } - else if (parent.kind === 203 /* SyntaxKind.BindingElement */ && - grandParent.kind === 201 /* SyntaxKind.ObjectBindingPattern */ && + else if (parent.kind === 205 /* SyntaxKind.BindingElement */ && + grandParent.kind === 203 /* SyntaxKind.ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -87743,8 +88427,8 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: case 80 /* SyntaxKind.PrivateIdentifier */: - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 161 /* SyntaxKind.QualifiedName */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 163 /* SyntaxKind.QualifiedName */: if (!ts.isThisInTypeQuery(node)) { return getSymbolOfNameOrPropertyAccessExpression(node); } @@ -87761,14 +88445,14 @@ var ts; return checkExpression(node).symbol; } // falls through - case 192 /* SyntaxKind.ThisType */: + case 194 /* SyntaxKind.ThisType */: return getTypeFromThisTypeNode(node).symbol; case 106 /* SyntaxKind.SuperKeyword */: return checkExpression(node).symbol; - case 134 /* SyntaxKind.ConstructorKeyword */: + case 135 /* SyntaxKind.ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 171 /* SyntaxKind.Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 173 /* SyntaxKind.Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -87779,7 +88463,7 @@ var ts; // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 266 /* SyntaxKind.ImportDeclaration */ || node.parent.kind === 272 /* SyntaxKind.ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 269 /* SyntaxKind.ImportDeclaration */ || node.parent.kind === 275 /* SyntaxKind.ExportDeclaration */) && node.parent.moduleSpecifier === node) || ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node, ignoreErrors); @@ -87801,14 +88485,14 @@ var ts; case 38 /* SyntaxKind.EqualsGreaterThanToken */: case 84 /* SyntaxKind.ClassKeyword */: return getSymbolOfNode(node.parent); - case 200 /* SyntaxKind.ImportType */: + case 202 /* SyntaxKind.ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined; case 93 /* SyntaxKind.ExportKeyword */: return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined; case 100 /* SyntaxKind.ImportKeyword */: case 103 /* SyntaxKind.NewKeyword */: return ts.isMetaProperty(node.parent) ? checkMetaPropertyKeyword(node.parent).symbol : undefined; - case 231 /* SyntaxKind.MetaProperty */: + case 233 /* SyntaxKind.MetaProperty */: return checkExpression(node).symbol; default: return undefined; @@ -87824,7 +88508,7 @@ var ts; return undefined; } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */) { + if (location && location.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 111551 /* SymbolFlags.Value */ | 2097152 /* SymbolFlags.Alias */); } return undefined; @@ -87863,7 +88547,7 @@ var ts; var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } - if (isTypeDeclaration(node)) { + if (ts.isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration var symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); @@ -87906,23 +88590,23 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfAssignmentPattern(expr) { - ts.Debug.assert(expr.kind === 205 /* SyntaxKind.ObjectLiteralExpression */ || expr.kind === 204 /* SyntaxKind.ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 207 /* SyntaxKind.ObjectLiteralExpression */ || expr.kind === 206 /* SyntaxKind.ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 244 /* SyntaxKind.ForOfStatement */) { + if (expr.parent.kind === 247 /* SyntaxKind.ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 221 /* SyntaxKind.BinaryExpression */) { + if (expr.parent.kind === 223 /* SyntaxKind.BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 296 /* SyntaxKind.PropertyAssignment */) { + if (expr.parent.kind === 299 /* SyntaxKind.PropertyAssignment */) { var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); @@ -87970,7 +88654,7 @@ var ts; case 8 /* SyntaxKind.NumericLiteral */: case 10 /* SyntaxKind.StringLiteral */: return getStringLiteralType(name.text); - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: var nameType = checkComputedPropertyName(name); return isTypeAssignableToKind(nameType, 12288 /* TypeFlags.ESSymbolLike */) ? nameType : stringType; default: @@ -88058,7 +88742,7 @@ var ts; return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 111551 /* SymbolFlags.Value */); + return s && !!(getAllSymbolFlags(s) & 111551 /* SymbolFlags.Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -88088,7 +88772,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* SymbolFlags.ValueModule */ && ((_a = parentSymbol_1.valueDeclaration) === null || _a === void 0 ? void 0 : _a.kind) === 305 /* SyntaxKind.SourceFile */) { + if (parentSymbol_1.flags & 512 /* SymbolFlags.ValueModule */ && ((_a = parentSymbol_1.valueDeclaration) === null || _a === void 0 ? void 0 : _a.kind) === 308 /* SyntaxKind.SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -88108,10 +88792,10 @@ var ts; } var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { - var symbol = getReferencedValueSymbol(node); + var symbol = getReferencedValueOrAliasSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -88120,7 +88804,7 @@ var ts; function isSymbolOfDestructuredElementOfCatchBinding(symbol) { return symbol.valueDeclaration && ts.isBindingElement(symbol.valueDeclaration) - && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 292 /* SyntaxKind.CatchClause */; + && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 295 /* SyntaxKind.CatchClause */; } function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418 /* SymbolFlags.BlockScoped */ && symbol.valueDeclaration && !ts.isSourceFile(symbol.valueDeclaration)) { @@ -88151,7 +88835,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* NodeCheckFlags.BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 235 /* SyntaxKind.Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 238 /* SyntaxKind.Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -88192,19 +88876,19 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return isAliasResolvedToValue(getSymbolOfNode(node)); - case 267 /* SyntaxKind.ImportClause */: - case 268 /* SyntaxKind.NamespaceImport */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 275 /* SyntaxKind.ExportSpecifier */: + case 270 /* SyntaxKind.ImportClause */: + case 271 /* SyntaxKind.NamespaceImport */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: var symbol = getSymbolOfNode(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); - case 272 /* SyntaxKind.ExportDeclaration */: + return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */); + case 275 /* SyntaxKind.ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || ts.some(exportClause.elements, isValueAliasDeclaration)); - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: return node.expression && node.expression.kind === 79 /* SyntaxKind.Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; @@ -88213,7 +88897,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 305 /* SyntaxKind.SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 308 /* SyntaxKind.SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -88221,6 +88905,7 @@ var ts; return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); } function isAliasResolvedToValue(symbol) { + var _a; if (!symbol) { return false; } @@ -88230,7 +88915,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 111551 /* SymbolFlags.Value */) && + return !!(((_a = getAllSymbolFlags(target)) !== null && _a !== void 0 ? _a : -1) & 111551 /* SymbolFlags.Value */) && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -88245,7 +88930,7 @@ var ts; } var target = getSymbolLinks(symbol).aliasTarget; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* ModifierFlags.Export */ && - target.flags & 111551 /* SymbolFlags.Value */ && + getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */ && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; @@ -88323,15 +89008,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 299 /* SyntaxKind.EnumMember */: - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 302 /* SyntaxKind.EnumMember */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 299 /* SyntaxKind.EnumMember */) { + if (node.kind === 302 /* SyntaxKind.EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -88424,7 +89109,7 @@ var ts; function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { - return ts.factory.createToken(130 /* SyntaxKind.AnyKeyword */); + return ts.factory.createToken(131 /* SyntaxKind.AnyKeyword */); } // Get type of the symbol if this is the valid symbol otherwise get type at location var symbol = getSymbolOfNode(declaration); @@ -88443,7 +89128,7 @@ var ts; function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { - return ts.factory.createToken(130 /* SyntaxKind.AnyKeyword */); + return ts.factory.createToken(131 /* SyntaxKind.AnyKeyword */); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* NodeBuilderFlags.MultilineObjectLiterals */, tracker); @@ -88451,12 +89136,14 @@ var ts; function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { - return ts.factory.createToken(130 /* SyntaxKind.AnyKeyword */); + return ts.factory.createToken(131 /* SyntaxKind.AnyKeyword */); } var type = getWidenedType(getRegularTypeOfExpression(expr)); return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* NodeBuilderFlags.MultilineObjectLiterals */, tracker); } function hasGlobalName(name) { + // deno: seems ok not to bother with nodeGlobals here since + // this is just a public api function that we don't bother with return globals.has(ts.escapeLeadingUnderscores(name)); } function getReferencedValueSymbol(reference, startInDeclarationContainer) { @@ -88475,6 +89162,25 @@ var ts; } return resolveName(location, reference.escapedText, 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */ | 2097152 /* SymbolFlags.Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } + /** + * Get either a value-meaning symbol or an alias symbol. + * Unlike `getReferencedValueSymbol`, if the cached resolved symbol is the unknown symbol, + * we call `resolveName` to find a symbol. + * This is because when caching the resolved symbol, we only consider value symbols, but here + * we want to also get an alias symbol if one exists. + */ + function getReferencedValueOrAliasSymbol(reference) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol && resolvedSymbol !== unknownSymbol) { + return resolvedSymbol; + } + return resolveName(reference, reference.escapedText, 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */ | 2097152 /* SymbolFlags.Alias */, + /*nodeNotFoundMessage*/ undefined, + /*nameArg*/ undefined, + /*isUse*/ true, + /*excludeGlobals*/ undefined, + /*getSpellingSuggestions*/ undefined); + } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); @@ -88608,12 +89314,12 @@ var ts; getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 - var otherKind = accessor.kind === 173 /* SyntaxKind.SetAccessor */ ? 172 /* SyntaxKind.GetAccessor */ : 173 /* SyntaxKind.SetAccessor */; + var otherKind = accessor.kind === 175 /* SyntaxKind.SetAccessor */ ? 174 /* SyntaxKind.GetAccessor */ : 175 /* SyntaxKind.SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 173 /* SyntaxKind.SetAccessor */ ? accessor : otherAccessor; - var getAccessor = accessor.kind === 172 /* SyntaxKind.GetAccessor */ ? accessor : otherAccessor; + var setAccessor = accessor.kind === 175 /* SyntaxKind.SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 174 /* SyntaxKind.GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -88629,7 +89335,7 @@ var ts; }, getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) { var n = ts.getParseTreeNode(node); - ts.Debug.assert(n && n.kind === 305 /* SyntaxKind.SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); + ts.Debug.assert(n && n.kind === 308 /* SyntaxKind.SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); var sym = getSymbolOfNode(node); if (!sym) { return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); @@ -88666,7 +89372,7 @@ var ts; return false; } function isInHeritageClause(node) { - return node.parent && node.parent.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 291 /* SyntaxKind.HeritageClause */; + return node.parent && node.parent.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 294 /* SyntaxKind.HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -88679,12 +89385,12 @@ var ts; // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries var meaning; - if (node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (node.parent.kind === 164 /* SyntaxKind.ComputedPropertyName */) { meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; } else { meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; - if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 208 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; } } @@ -88733,7 +89439,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 305 /* SyntaxKind.SourceFile */ && current.flags & 512 /* SymbolFlags.ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 308 /* SyntaxKind.SourceFile */ && current.flags & 512 /* SymbolFlags.ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -88761,12 +89467,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 261 /* SyntaxKind.ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 264 /* SyntaxKind.ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 305 /* SyntaxKind.SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 308 /* SyntaxKind.SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -88984,14 +89690,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 169 /* SyntaxKind.MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 171 /* SyntaxKind.MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 172 /* SyntaxKind.GetAccessor */ || node.kind === 173 /* SyntaxKind.SetAccessor */) { + else if (node.kind === 174 /* SyntaxKind.GetAccessor */ || node.kind === 175 /* SyntaxKind.SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (ts.hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -89010,26 +89716,26 @@ var ts; var modifier = _a[_i]; if (ts.isDecorator(modifier)) continue; - if (modifier.kind !== 145 /* SyntaxKind.ReadonlyKeyword */) { - if (node.kind === 166 /* SyntaxKind.PropertySignature */ || node.kind === 168 /* SyntaxKind.MethodSignature */) { + if (modifier.kind !== 146 /* SyntaxKind.ReadonlyKeyword */) { + if (node.kind === 168 /* SyntaxKind.PropertySignature */ || node.kind === 170 /* SyntaxKind.MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 176 /* SyntaxKind.IndexSignature */ && (modifier.kind !== 124 /* SyntaxKind.StaticKeyword */ || !ts.isClassLike(node.parent))) { + if (node.kind === 178 /* SyntaxKind.IndexSignature */ && (modifier.kind !== 124 /* SyntaxKind.StaticKeyword */ || !ts.isClassLike(node.parent))) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } - if (modifier.kind !== 101 /* SyntaxKind.InKeyword */ && modifier.kind !== 144 /* SyntaxKind.OutKeyword */) { - if (node.kind === 163 /* SyntaxKind.TypeParameter */) { + if (modifier.kind !== 101 /* SyntaxKind.InKeyword */ && modifier.kind !== 145 /* SyntaxKind.OutKeyword */) { + if (node.kind === 165 /* SyntaxKind.TypeParameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_parameter, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 85 /* SyntaxKind.ConstKeyword */: - if (node.kind !== 260 /* SyntaxKind.EnumDeclaration */) { + if (node.kind !== 263 /* SyntaxKind.EnumDeclaration */) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(85 /* SyntaxKind.ConstKeyword */)); } break; - case 159 /* SyntaxKind.OverrideKeyword */: + case 161 /* SyntaxKind.OverrideKeyword */: // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. if (flags & 16384 /* ModifierFlags.Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); @@ -89040,7 +89746,10 @@ var ts; else if (flags & 64 /* ModifierFlags.Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); } - else if (flags & 256 /* ModifierFlags.Async */) { + else if (flags & 128 /* ModifierFlags.Accessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "accessor"); + } + else if (flags & 512 /* ModifierFlags.Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); } flags |= 16384 /* ModifierFlags.Override */; @@ -89059,16 +89768,19 @@ var ts; else if (flags & 32 /* ModifierFlags.Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } + else if (flags & 128 /* ModifierFlags.Accessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "accessor"); + } else if (flags & 64 /* ModifierFlags.Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); } - else if (flags & 256 /* ModifierFlags.Async */) { + else if (flags & 512 /* ModifierFlags.Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 305 /* SyntaxKind.SourceFile */) { + else if (node.parent.kind === 265 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 308 /* SyntaxKind.SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } - else if (flags & 128 /* ModifierFlags.Abstract */) { + else if (flags & 256 /* ModifierFlags.Abstract */) { if (modifier.kind === 121 /* SyntaxKind.PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } @@ -89088,16 +89800,19 @@ var ts; else if (flags & 64 /* ModifierFlags.Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); } - else if (flags & 256 /* ModifierFlags.Async */) { + else if (flags & 512 /* ModifierFlags.Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 305 /* SyntaxKind.SourceFile */) { + else if (flags & 128 /* ModifierFlags.Accessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "accessor"); + } + else if (node.parent.kind === 265 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 308 /* SyntaxKind.SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 164 /* SyntaxKind.Parameter */) { + else if (node.kind === 166 /* SyntaxKind.Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } - else if (flags & 128 /* ModifierFlags.Abstract */) { + else if (flags & 256 /* ModifierFlags.Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } else if (flags & 16384 /* ModifierFlags.Override */) { @@ -89106,11 +89821,26 @@ var ts; flags |= 32 /* ModifierFlags.Static */; lastStatic = modifier; break; - case 145 /* SyntaxKind.ReadonlyKeyword */: + case 127 /* SyntaxKind.AccessorKeyword */: + if (flags & 128 /* ModifierFlags.Accessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "accessor"); + } + else if (flags & 64 /* ModifierFlags.Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "readonly"); + } + else if (flags & 2 /* ModifierFlags.Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "declare"); + } + else if (node.kind !== 169 /* SyntaxKind.PropertyDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.accessor_modifier_can_only_appear_on_a_property_declaration); + } + flags |= 128 /* ModifierFlags.Accessor */; + break; + case 146 /* SyntaxKind.ReadonlyKeyword */: if (flags & 64 /* ModifierFlags.Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 167 /* SyntaxKind.PropertyDeclaration */ && node.kind !== 166 /* SyntaxKind.PropertySignature */ && node.kind !== 176 /* SyntaxKind.IndexSignature */ && node.kind !== 164 /* SyntaxKind.Parameter */) { + else if (node.kind !== 169 /* SyntaxKind.PropertyDeclaration */ && node.kind !== 168 /* SyntaxKind.PropertySignature */ && node.kind !== 178 /* SyntaxKind.IndexSignature */ && node.kind !== 166 /* SyntaxKind.Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } @@ -89123,35 +89853,35 @@ var ts; else if (flags & 2 /* ModifierFlags.Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (flags & 128 /* ModifierFlags.Abstract */) { + else if (flags & 256 /* ModifierFlags.Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); } - else if (flags & 256 /* ModifierFlags.Async */) { + else if (flags & 512 /* ModifierFlags.Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } else if (ts.isClassLike(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export"); } - else if (node.kind === 164 /* SyntaxKind.Parameter */) { + else if (node.kind === 166 /* SyntaxKind.Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* ModifierFlags.Export */; break; case 88 /* SyntaxKind.DefaultKeyword */: - var container = node.parent.kind === 305 /* SyntaxKind.SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 261 /* SyntaxKind.ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 308 /* SyntaxKind.SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 264 /* SyntaxKind.ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } else if (!(flags & 1 /* ModifierFlags.Export */)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "default"); } - flags |= 512 /* ModifierFlags.Default */; + flags |= 1024 /* ModifierFlags.Default */; break; - case 135 /* SyntaxKind.DeclareKeyword */: + case 136 /* SyntaxKind.DeclareKeyword */: if (flags & 2 /* ModifierFlags.Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } - else if (flags & 256 /* ModifierFlags.Async */) { + else if (flags & 512 /* ModifierFlags.Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (flags & 16384 /* ModifierFlags.Override */) { @@ -89160,10 +89890,10 @@ var ts; else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare"); } - else if (node.kind === 164 /* SyntaxKind.Parameter */) { + else if (node.kind === 166 /* SyntaxKind.Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 16777216 /* NodeFlags.Ambient */) && node.parent.kind === 262 /* SyntaxKind.ModuleBlock */) { + else if ((node.parent.flags & 16777216 /* NodeFlags.Ambient */) && node.parent.kind === 265 /* SyntaxKind.ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { @@ -89173,18 +89903,18 @@ var ts; lastDeclare = modifier; break; case 126 /* SyntaxKind.AbstractKeyword */: - if (flags & 128 /* ModifierFlags.Abstract */) { + if (flags & 256 /* ModifierFlags.Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 257 /* SyntaxKind.ClassDeclaration */ && - node.kind !== 180 /* SyntaxKind.ConstructorType */) { - if (node.kind !== 169 /* SyntaxKind.MethodDeclaration */ && - node.kind !== 167 /* SyntaxKind.PropertyDeclaration */ && - node.kind !== 172 /* SyntaxKind.GetAccessor */ && - node.kind !== 173 /* SyntaxKind.SetAccessor */) { + if (node.kind !== 260 /* SyntaxKind.ClassDeclaration */ && + node.kind !== 182 /* SyntaxKind.ConstructorType */) { + if (node.kind !== 171 /* SyntaxKind.MethodDeclaration */ && + node.kind !== 169 /* SyntaxKind.PropertyDeclaration */ && + node.kind !== 174 /* SyntaxKind.GetAccessor */ && + node.kind !== 175 /* SyntaxKind.SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 257 /* SyntaxKind.ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* ModifierFlags.Abstract */))) { + if (!(node.parent.kind === 260 /* SyntaxKind.ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 256 /* ModifierFlags.Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* ModifierFlags.Static */) { @@ -89193,39 +89923,42 @@ var ts; if (flags & 8 /* ModifierFlags.Private */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } - if (flags & 256 /* ModifierFlags.Async */ && lastAsync) { + if (flags & 512 /* ModifierFlags.Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } if (flags & 16384 /* ModifierFlags.Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); } + if (flags & 128 /* ModifierFlags.Accessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "accessor"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 80 /* SyntaxKind.PrivateIdentifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); } - flags |= 128 /* ModifierFlags.Abstract */; + flags |= 256 /* ModifierFlags.Abstract */; break; - case 131 /* SyntaxKind.AsyncKeyword */: - if (flags & 256 /* ModifierFlags.Async */) { + case 132 /* SyntaxKind.AsyncKeyword */: + if (flags & 512 /* ModifierFlags.Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 /* ModifierFlags.Ambient */ || node.parent.flags & 16777216 /* NodeFlags.Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 164 /* SyntaxKind.Parameter */) { + else if (node.kind === 166 /* SyntaxKind.Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } - if (flags & 128 /* ModifierFlags.Abstract */) { + if (flags & 256 /* ModifierFlags.Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } - flags |= 256 /* ModifierFlags.Async */; + flags |= 512 /* ModifierFlags.Async */; lastAsync = modifier; break; case 101 /* SyntaxKind.InKeyword */: - case 144 /* SyntaxKind.OutKeyword */: + case 145 /* SyntaxKind.OutKeyword */: var inOutFlag = modifier.kind === 101 /* SyntaxKind.InKeyword */ ? 32768 /* ModifierFlags.In */ : 65536 /* ModifierFlags.Out */; var inOutText = modifier.kind === 101 /* SyntaxKind.InKeyword */ ? "in" : "out"; - if (node.kind !== 163 /* SyntaxKind.TypeParameter */ || !(ts.isInterfaceDeclaration(node.parent) || ts.isClassLike(node.parent) || ts.isTypeAliasDeclaration(node.parent))) { + if (node.kind !== 165 /* SyntaxKind.TypeParameter */ || !(ts.isInterfaceDeclaration(node.parent) || ts.isClassLike(node.parent) || ts.isTypeAliasDeclaration(node.parent))) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias, inOutText); } if (flags & inOutFlag) { @@ -89238,28 +89971,28 @@ var ts; break; } } - if (node.kind === 171 /* SyntaxKind.Constructor */) { + if (node.kind === 173 /* SyntaxKind.Constructor */) { if (flags & 32 /* ModifierFlags.Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 16384 /* ModifierFlags.Override */) { return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 } - if (flags & 256 /* ModifierFlags.Async */) { + if (flags & 512 /* ModifierFlags.Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } return false; } - else if ((node.kind === 266 /* SyntaxKind.ImportDeclaration */ || node.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) && flags & 2 /* ModifierFlags.Ambient */) { + else if ((node.kind === 269 /* SyntaxKind.ImportDeclaration */ || node.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */) && flags & 2 /* ModifierFlags.Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 164 /* SyntaxKind.Parameter */ && (flags & 16476 /* ModifierFlags.ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 166 /* SyntaxKind.Parameter */ && (flags & 16476 /* ModifierFlags.ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 164 /* SyntaxKind.Parameter */ && (flags & 16476 /* ModifierFlags.ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 166 /* SyntaxKind.Parameter */ && (flags & 16476 /* ModifierFlags.ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } - if (flags & 256 /* ModifierFlags.Async */) { + if (flags & 512 /* ModifierFlags.Async */) { return checkGrammarAsyncModifier(node, lastAsync); } return false; @@ -89277,47 +90010,47 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 171 /* SyntaxKind.Constructor */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 176 /* SyntaxKind.IndexSignature */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 266 /* SyntaxKind.ImportDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 272 /* SyntaxKind.ExportDeclaration */: - case 271 /* SyntaxKind.ExportAssignment */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 164 /* SyntaxKind.Parameter */: - case 163 /* SyntaxKind.TypeParameter */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 173 /* SyntaxKind.Constructor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 178 /* SyntaxKind.IndexSignature */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: + case 274 /* SyntaxKind.ExportAssignment */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 166 /* SyntaxKind.Parameter */: + case 165 /* SyntaxKind.TypeParameter */: return false; - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 264 /* SyntaxKind.NamespaceExportDeclaration */: - case 179 /* SyntaxKind.FunctionType */: - case 276 /* SyntaxKind.MissingDeclaration */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 267 /* SyntaxKind.NamespaceExportDeclaration */: + case 181 /* SyntaxKind.FunctionType */: + case 279 /* SyntaxKind.MissingDeclaration */: return true; default: - if (node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 305 /* SyntaxKind.SourceFile */) { + if (node.parent.kind === 265 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 308 /* SyntaxKind.SourceFile */) { return false; } switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 131 /* SyntaxKind.AsyncKeyword */); - case 257 /* SyntaxKind.ClassDeclaration */: - case 180 /* SyntaxKind.ConstructorType */: + case 259 /* SyntaxKind.FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 132 /* SyntaxKind.AsyncKeyword */); + case 260 /* SyntaxKind.ClassDeclaration */: + case 182 /* SyntaxKind.ConstructorType */: return nodeHasAnyModifiersExcept(node, 126 /* SyntaxKind.AbstractKeyword */); - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 237 /* SyntaxKind.VariableStatement */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 240 /* SyntaxKind.VariableStatement */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return true; - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 85 /* SyntaxKind.ConstKeyword */); default: ts.Debug.assertNever(node); @@ -89335,10 +90068,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 169 /* SyntaxKind.MethodDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -89567,20 +90300,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 162 /* SyntaxKind.ComputedPropertyName */) { + if (node.kind !== 164 /* SyntaxKind.ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 221 /* SyntaxKind.BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* SyntaxKind.CommaToken */) { + if (computedPropertyName.expression.kind === 223 /* SyntaxKind.BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* SyntaxKind.CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 256 /* SyntaxKind.FunctionDeclaration */ || - node.kind === 213 /* SyntaxKind.FunctionExpression */ || - node.kind === 169 /* SyntaxKind.MethodDeclaration */); + ts.Debug.assert(node.kind === 259 /* SyntaxKind.FunctionDeclaration */ || + node.kind === 215 /* SyntaxKind.FunctionExpression */ || + node.kind === 171 /* SyntaxKind.MethodDeclaration */); if (node.flags & 16777216 /* NodeFlags.Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -89599,7 +90332,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 298 /* SyntaxKind.SpreadAssignment */) { + if (prop.kind === 301 /* SyntaxKind.SpreadAssignment */) { if (inDestructuring) { // a rest property cannot be destructured any further var expression = ts.skipParentheses(prop.expression); @@ -89610,11 +90343,11 @@ var ts; continue; } var name = prop.name; - if (name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (name.kind === 164 /* SyntaxKind.ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); @@ -89626,7 +90359,7 @@ var ts; if (ts.canHaveModifiers(prop) && prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (ts.isModifier(mod) && (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */)) { + if (ts.isModifier(mod) && (mod.kind !== 132 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 171 /* SyntaxKind.MethodDeclaration */)) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -89647,8 +90380,8 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 296 /* SyntaxKind.PropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); @@ -89657,13 +90390,13 @@ var ts; } currentKind = 4 /* DeclarationMeaning.PropertyAssignment */; break; - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: currentKind = 8 /* DeclarationMeaning.Method */; break; - case 172 /* SyntaxKind.GetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: currentKind = 1 /* DeclarationMeaning.GetAccessor */; break; - case 173 /* SyntaxKind.SetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: currentKind = 2 /* DeclarationMeaning.SetAccessor */; break; default: @@ -89706,7 +90439,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 287 /* SyntaxKind.JsxSpreadAttribute */) { + if (attr.kind === 290 /* SyntaxKind.JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -89716,7 +90449,7 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 288 /* SyntaxKind.JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 291 /* SyntaxKind.JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -89751,7 +90484,7 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 244 /* SyntaxKind.ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 247 /* SyntaxKind.ForOfStatement */ && forInOrOfStatement.awaitModifier) { if (!(forInOrOfStatement.flags & 32768 /* NodeFlags.AwaitContext */)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); if (ts.isInTopLevelContext(forInOrOfStatement)) { @@ -89785,7 +90518,7 @@ var ts; if (!hasParseDiagnostics(sourceFile)) { var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 171 /* SyntaxKind.Constructor */) { + if (func && func.kind !== 173 /* SyntaxKind.Constructor */) { ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* FunctionFlags.Async */) === 0, "Enclosing function should never be an async function."); var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); @@ -89802,7 +90535,7 @@ var ts; grammarErrorOnNode(forInOrOfStatement.initializer, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async); return false; } - if (forInOrOfStatement.initializer.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 258 /* SyntaxKind.VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -89817,20 +90550,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 243 /* SyntaxKind.ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 246 /* SyntaxKind.ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 243 /* SyntaxKind.ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 246 /* SyntaxKind.ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 243 /* SyntaxKind.ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 246 /* SyntaxKind.ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -89840,22 +90573,22 @@ var ts; return false; } function checkGrammarAccessor(accessor) { - if (!(accessor.flags & 16777216 /* NodeFlags.Ambient */) && (accessor.parent.kind !== 182 /* SyntaxKind.TypeLiteral */) && (accessor.parent.kind !== 258 /* SyntaxKind.InterfaceDeclaration */)) { + if (!(accessor.flags & 16777216 /* NodeFlags.Ambient */) && (accessor.parent.kind !== 184 /* SyntaxKind.TypeLiteral */) && (accessor.parent.kind !== 261 /* SyntaxKind.InterfaceDeclaration */)) { if (languageVersion < 1 /* ScriptTarget.ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } if (languageVersion < 2 /* ScriptTarget.ES2015 */ && ts.isPrivateIdentifier(accessor.name)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); } - if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128 /* ModifierFlags.Abstract */)) { + if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 256 /* ModifierFlags.Abstract */)) { return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } if (accessor.body) { - if (ts.hasSyntacticModifier(accessor, 128 /* ModifierFlags.Abstract */)) { + if (ts.hasSyntacticModifier(accessor, 256 /* ModifierFlags.Abstract */)) { return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); } - if (accessor.parent.kind === 182 /* SyntaxKind.TypeLiteral */ || accessor.parent.kind === 258 /* SyntaxKind.InterfaceDeclaration */) { + if (accessor.parent.kind === 184 /* SyntaxKind.TypeLiteral */ || accessor.parent.kind === 261 /* SyntaxKind.InterfaceDeclaration */) { return grammarErrorOnNode(accessor.body, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } } @@ -89863,11 +90596,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, accessor.kind === 172 /* SyntaxKind.GetAccessor */ ? + return grammarErrorOnNode(accessor.name, accessor.kind === 174 /* SyntaxKind.GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - if (accessor.kind === 173 /* SyntaxKind.SetAccessor */) { + if (accessor.kind === 175 /* SyntaxKind.SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -89889,17 +90622,17 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 172 /* SyntaxKind.GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 174 /* SyntaxKind.GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 172 /* SyntaxKind.GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 174 /* SyntaxKind.GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } function checkGrammarTypeOperatorNode(node) { - if (node.operator === 154 /* SyntaxKind.UniqueKeyword */) { - if (node.type.kind !== 151 /* SyntaxKind.SymbolKeyword */) { - return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(151 /* SyntaxKind.SymbolKeyword */)); + if (node.operator === 156 /* SyntaxKind.UniqueKeyword */) { + if (node.type.kind !== 153 /* SyntaxKind.SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(153 /* SyntaxKind.SymbolKeyword */)); } var parent = ts.walkUpParenthesizedTypes(node.parent); if (ts.isInJSFile(parent) && ts.isJSDocTypeExpression(parent)) { @@ -89909,7 +90642,7 @@ var ts; } } switch (parent.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: var decl = parent; if (decl.name.kind !== 79 /* SyntaxKind.Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); @@ -89921,13 +90654,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: if (!ts.isStatic(parent) || !ts.hasEffectiveReadonlyModifier(parent)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 166 /* SyntaxKind.PropertySignature */: + case 168 /* SyntaxKind.PropertySignature */: if (!ts.hasSyntacticModifier(parent, 64 /* ModifierFlags.Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -89936,9 +90669,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); } } - else if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { - if (node.type.kind !== 183 /* SyntaxKind.ArrayType */ && node.type.kind !== 184 /* SyntaxKind.TupleType */) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(151 /* SyntaxKind.SymbolKeyword */)); + else if (node.operator === 146 /* SyntaxKind.ReadonlyKeyword */) { + if (node.type.kind !== 185 /* SyntaxKind.ArrayType */ && node.type.kind !== 186 /* SyntaxKind.TupleType */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(153 /* SyntaxKind.SymbolKeyword */)); } } } @@ -89951,10 +90684,10 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 169 /* SyntaxKind.MethodDeclaration */) { - if (node.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { + if (node.kind === 171 /* SyntaxKind.MethodDeclaration */) { + if (node.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 131 /* SyntaxKind.AsyncKeyword */)) { + if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 132 /* SyntaxKind.AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { @@ -89983,14 +90716,14 @@ var ts; if (node.flags & 16777216 /* NodeFlags.Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 169 /* SyntaxKind.MethodDeclaration */ && !node.body) { + else if (node.kind === 171 /* SyntaxKind.MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 258 /* SyntaxKind.InterfaceDeclaration */) { + else if (node.parent.kind === 261 /* SyntaxKind.InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 182 /* SyntaxKind.TypeLiteral */) { + else if (node.parent.kind === 184 /* SyntaxKind.TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -90001,11 +90734,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 245 /* SyntaxKind.ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 248 /* SyntaxKind.ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -90013,8 +90746,8 @@ var ts; return false; } break; - case 249 /* SyntaxKind.SwitchStatement */: - if (node.kind === 246 /* SyntaxKind.BreakStatement */ && !node.label) { + case 252 /* SyntaxKind.SwitchStatement */: + if (node.kind === 249 /* SyntaxKind.BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -90029,13 +90762,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 246 /* SyntaxKind.BreakStatement */ + var message = node.kind === 249 /* SyntaxKind.BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 246 /* SyntaxKind.BreakStatement */ + var message = node.kind === 249 /* SyntaxKind.BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -90059,12 +90792,12 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return ts.isStringOrNumericLiteralLike(expr) || - expr.kind === 219 /* SyntaxKind.PrefixUnaryExpression */ && expr.operator === 40 /* SyntaxKind.MinusToken */ && + expr.kind === 221 /* SyntaxKind.PrefixUnaryExpression */ && expr.operator === 40 /* SyntaxKind.MinusToken */ && expr.operand.kind === 8 /* SyntaxKind.NumericLiteral */; } function isBigIntLiteralExpression(expr) { return expr.kind === 9 /* SyntaxKind.BigIntLiteral */ || - expr.kind === 219 /* SyntaxKind.PrefixUnaryExpression */ && expr.operator === 40 /* SyntaxKind.MinusToken */ && + expr.kind === 221 /* SyntaxKind.PrefixUnaryExpression */ && expr.operator === 40 /* SyntaxKind.MinusToken */ && expr.operand.kind === 9 /* SyntaxKind.BigIntLiteral */; } function isSimpleLiteralEnumReference(expr) { @@ -90092,7 +90825,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */ && node.parent.parent.kind !== 244 /* SyntaxKind.ForOfStatement */) { + if (node.parent.parent.kind !== 246 /* SyntaxKind.ForInStatement */ && node.parent.parent.kind !== 247 /* SyntaxKind.ForOfStatement */) { if (node.flags & 16777216 /* NodeFlags.Ambient */) { checkAmbientInitializer(node); } @@ -90105,7 +90838,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 237 /* SyntaxKind.VariableStatement */ || !node.type || node.initializer || node.flags & 16777216 /* NodeFlags.Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 240 /* SyntaxKind.VariableStatement */ || !node.type || node.initializer || node.flags & 16777216 /* NodeFlags.Ambient */)) { var message = node.initializer ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type @@ -90172,15 +90905,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 239 /* SyntaxKind.IfStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 248 /* SyntaxKind.WithStatement */: - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: + case 242 /* SyntaxKind.IfStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 251 /* SyntaxKind.WithStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return false; - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -90274,8 +91007,14 @@ var ts; if (languageVersion < 2 /* ScriptTarget.ES2015 */ && ts.isPrivateIdentifier(node.name)) { return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); } + if (languageVersion < 2 /* ScriptTarget.ES2015 */ && ts.isAutoAccessorPropertyDeclaration(node)) { + return grammarErrorOnNode(node.name, ts.Diagnostics.Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } + if (ts.isAutoAccessorPropertyDeclaration(node) && checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_accessor_property_cannot_be_declared_optional)) { + return true; + } } - else if (node.parent.kind === 258 /* SyntaxKind.InterfaceDeclaration */) { + else if (node.parent.kind === 261 /* SyntaxKind.InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -90321,14 +91060,14 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 258 /* SyntaxKind.InterfaceDeclaration */ || - node.kind === 259 /* SyntaxKind.TypeAliasDeclaration */ || - node.kind === 266 /* SyntaxKind.ImportDeclaration */ || - node.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ || - node.kind === 272 /* SyntaxKind.ExportDeclaration */ || - node.kind === 271 /* SyntaxKind.ExportAssignment */ || - node.kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ || - ts.hasSyntacticModifier(node, 2 /* ModifierFlags.Ambient */ | 1 /* ModifierFlags.Export */ | 512 /* ModifierFlags.Default */)) { + if (node.kind === 261 /* SyntaxKind.InterfaceDeclaration */ || + node.kind === 262 /* SyntaxKind.TypeAliasDeclaration */ || + node.kind === 269 /* SyntaxKind.ImportDeclaration */ || + node.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ || + node.kind === 275 /* SyntaxKind.ExportDeclaration */ || + node.kind === 274 /* SyntaxKind.ExportAssignment */ || + node.kind === 267 /* SyntaxKind.NamespaceExportDeclaration */ || + ts.hasSyntacticModifier(node, 2 /* ModifierFlags.Ambient */ | 1 /* ModifierFlags.Export */ | 1024 /* ModifierFlags.Default */)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier); @@ -90336,7 +91075,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 237 /* SyntaxKind.VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 240 /* SyntaxKind.VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -90359,7 +91098,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 235 /* SyntaxKind.Block */ || node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 305 /* SyntaxKind.SourceFile */) { + if (node.parent.kind === 238 /* SyntaxKind.Block */ || node.parent.kind === 265 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 308 /* SyntaxKind.SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -90381,10 +91120,10 @@ var ts; if (languageVersion >= 1 /* ScriptTarget.ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 196 /* SyntaxKind.LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 198 /* SyntaxKind.LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 299 /* SyntaxKind.EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 302 /* SyntaxKind.EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -90469,7 +91208,7 @@ var ts; if (node.isTypeOnly && node.name && node.namedBindings) { return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both); } - if (node.isTypeOnly && ((_a = node.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 269 /* SyntaxKind.NamedImports */) { + if (node.isTypeOnly && ((_a = node.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 272 /* SyntaxKind.NamedImports */) { return checkGrammarNamedImportsOrExports(node.namedBindings); } return false; @@ -90477,7 +91216,7 @@ var ts; function checkGrammarNamedImportsOrExports(namedBindings) { return !!ts.forEach(namedBindings.elements, function (specifier) { if (specifier.isTypeOnly) { - return grammarErrorOnFirstToken(specifier, specifier.kind === 270 /* SyntaxKind.ImportSpecifier */ + return grammarErrorOnFirstToken(specifier, specifier.kind === 273 /* SyntaxKind.ImportSpecifier */ ? ts.Diagnostics.The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement : ts.Diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement); } @@ -90491,7 +91230,7 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments); } var nodeArguments = node.arguments; - if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext) { + if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext && moduleKind !== ts.ModuleKind.Node16) { // We are allowed trailing comma after proposal-import-assertions. checkGrammarForDisallowedTrailingComma(nodeArguments); if (nodeArguments.length > 1) { @@ -90600,14 +91339,14 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 256 /* SyntaxKind.FunctionDeclaration */ && declaration.kind !== 169 /* SyntaxKind.MethodDeclaration */) || + return (declaration.kind !== 259 /* SyntaxKind.FunctionDeclaration */ && declaration.kind !== 171 /* SyntaxKind.MethodDeclaration */) || !!declaration.body; } /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 270 /* SyntaxKind.ImportSpecifier */: - case 275 /* SyntaxKind.ExportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); @@ -90875,6 +91614,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var _a; function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -90941,7 +91681,6 @@ var ts; return nodes; } ts.visitNodes = visitNodes; - /* @internal */ function visitArray(nodes, visitor, test, start, count) { if (nodes === undefined) { return nodes; @@ -91089,12 +91828,10 @@ var ts; return updated; } ts.visitFunctionBody = visitFunctionBody; - /** - * Visits an iteration body, adding any block-scoped variables required by the transformation. - */ - function visitIterationBody(body, visitor, context) { + function visitIterationBody(body, visitor, context, nodeVisitor) { + if (nodeVisitor === void 0) { nodeVisitor = visitNode; } context.startBlockScope(); - var updated = visitNode(body, visitor, ts.isStatement, context.factory.liftToBlock); + var updated = nodeVisitor(body, visitor, ts.isStatement, context.factory.liftToBlock); var declarations = context.endBlockScope(); if (ts.some(declarations)) { if (ts.isBlock(updated)) { @@ -91113,456 +91850,446 @@ var ts; if (node === undefined) { return undefined; } - var kind = node.kind; - // No need to visit nodes with no children. - if ((kind > 0 /* SyntaxKind.FirstToken */ && kind <= 160 /* SyntaxKind.LastToken */) || kind === 192 /* SyntaxKind.ThisType */) { - return node; - } - var factory = context.factory; - switch (kind) { - // Names - case 79 /* SyntaxKind.Identifier */: - ts.Debug.type(node); - return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNodeOrTypeParameterDeclaration)); - case 161 /* SyntaxKind.QualifiedName */: - ts.Debug.type(node); - return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier)); - case 162 /* SyntaxKind.ComputedPropertyName */: - ts.Debug.type(node); - return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - // Signature elements - case 163 /* SyntaxKind.TypeParameter */: - ts.Debug.type(node); - return factory.updateTypeParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); - case 164 /* SyntaxKind.Parameter */: - ts.Debug.type(node); - return factory.updateParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 165 /* SyntaxKind.Decorator */: - ts.Debug.type(node); - return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - // Type elements - case 166 /* SyntaxKind.PropertySignature */: - ts.Debug.type(node); - return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 167 /* SyntaxKind.PropertyDeclaration */: - ts.Debug.type(node); - return factory.updatePropertyDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), - // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too - nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 168 /* SyntaxKind.MethodSignature */: - ts.Debug.type(node); - return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 169 /* SyntaxKind.MethodDeclaration */: - ts.Debug.type(node); - return factory.updateMethodDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 171 /* SyntaxKind.Constructor */: - ts.Debug.type(node); - return factory.updateConstructorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 172 /* SyntaxKind.GetAccessor */: - ts.Debug.type(node); - return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 173 /* SyntaxKind.SetAccessor */: - ts.Debug.type(node); - return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - ts.Debug.type(node); - context.startLexicalEnvironment(); - context.suspendLexicalEnvironment(); - return factory.updateClassStaticBlockDeclaration(node, visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 174 /* SyntaxKind.CallSignature */: - ts.Debug.type(node); - return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 175 /* SyntaxKind.ConstructSignature */: - ts.Debug.type(node); - return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 176 /* SyntaxKind.IndexSignature */: - ts.Debug.type(node); - return factory.updateIndexSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - // Types - case 177 /* SyntaxKind.TypePredicate */: - ts.Debug.type(node); - return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, ts.isAssertsKeyword), nodeVisitor(node.parameterName, visitor, ts.isIdentifierOrThisTypeNode), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 178 /* SyntaxKind.TypeReference */: - ts.Debug.type(node); - return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 179 /* SyntaxKind.FunctionType */: - ts.Debug.type(node); - return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 180 /* SyntaxKind.ConstructorType */: - ts.Debug.type(node); - return factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 181 /* SyntaxKind.TypeQuery */: - ts.Debug.type(node); - return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 182 /* SyntaxKind.TypeLiteral */: - ts.Debug.type(node); - return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 183 /* SyntaxKind.ArrayType */: - ts.Debug.type(node); - return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode)); - case 184 /* SyntaxKind.TupleType */: - ts.Debug.type(node); - return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode)); - case 185 /* SyntaxKind.OptionalType */: - ts.Debug.type(node); - return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 186 /* SyntaxKind.RestType */: - ts.Debug.type(node); - return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 187 /* SyntaxKind.UnionType */: - ts.Debug.type(node); - return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 188 /* SyntaxKind.IntersectionType */: - ts.Debug.type(node); - return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 189 /* SyntaxKind.ConditionalType */: - ts.Debug.type(node); - return factory.updateConditionalTypeNode(node, nodeVisitor(node.checkType, visitor, ts.isTypeNode), nodeVisitor(node.extendsType, visitor, ts.isTypeNode), nodeVisitor(node.trueType, visitor, ts.isTypeNode), nodeVisitor(node.falseType, visitor, ts.isTypeNode)); - case 190 /* SyntaxKind.InferType */: - ts.Debug.type(node); - return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 200 /* SyntaxKind.ImportType */: - ts.Debug.type(node); - return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 295 /* SyntaxKind.ImportTypeAssertionContainer */: - ts.Debug.type(node); - return factory.updateImportTypeAssertionContainer(node, nodeVisitor(node.assertClause, visitor, ts.isNode), node.multiLine); - case 197 /* SyntaxKind.NamedTupleMember */: - ts.Debug.type(node); - return factory.updateNamedTupleMember(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 191 /* SyntaxKind.ParenthesizedType */: - ts.Debug.type(node); - return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 193 /* SyntaxKind.TypeOperator */: - ts.Debug.type(node); - return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 194 /* SyntaxKind.IndexedAccessType */: - ts.Debug.type(node); - return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); - case 195 /* SyntaxKind.MappedType */: - ts.Debug.type(node); - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 196 /* SyntaxKind.LiteralType */: - ts.Debug.type(node); - return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); - case 198 /* SyntaxKind.TemplateLiteralType */: - ts.Debug.type(node); - return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan)); - case 199 /* SyntaxKind.TemplateLiteralTypeSpan */: - ts.Debug.type(node); - return factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); - // Binding patterns - case 201 /* SyntaxKind.ObjectBindingPattern */: - ts.Debug.type(node); - return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 202 /* SyntaxKind.ArrayBindingPattern */: - ts.Debug.type(node); - return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 203 /* SyntaxKind.BindingElement */: - ts.Debug.type(node); - return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); - // Expression - case 204 /* SyntaxKind.ArrayLiteralExpression */: - ts.Debug.type(node); - return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 205 /* SyntaxKind.ObjectLiteralExpression */: - ts.Debug.type(node); - return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 206 /* SyntaxKind.PropertyAccessExpression */: - if (node.flags & 32 /* NodeFlags.OptionalChain */) { - ts.Debug.type(node); - return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.name, visitor, ts.isMemberName)); - } - ts.Debug.type(node); - return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isMemberName)); - case 207 /* SyntaxKind.ElementAccessExpression */: - if (node.flags & 32 /* NodeFlags.OptionalChain */) { - ts.Debug.type(node); - return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); - } - ts.Debug.type(node); - return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); - case 208 /* SyntaxKind.CallExpression */: - if (node.flags & 32 /* NodeFlags.OptionalChain */) { - ts.Debug.type(node); - return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - } - ts.Debug.type(node); - return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 209 /* SyntaxKind.NewExpression */: - ts.Debug.type(node); - return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 210 /* SyntaxKind.TaggedTemplateExpression */: - ts.Debug.type(node); - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); - case 211 /* SyntaxKind.TypeAssertionExpression */: - ts.Debug.type(node); - return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 212 /* SyntaxKind.ParenthesizedExpression */: - ts.Debug.type(node); - return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 213 /* SyntaxKind.FunctionExpression */: - ts.Debug.type(node); - return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 214 /* SyntaxKind.ArrowFunction */: - ts.Debug.type(node); - return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isEqualsGreaterThanToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 215 /* SyntaxKind.DeleteExpression */: - ts.Debug.type(node); - return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 216 /* SyntaxKind.TypeOfExpression */: - ts.Debug.type(node); - return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 217 /* SyntaxKind.VoidExpression */: - ts.Debug.type(node); - return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 218 /* SyntaxKind.AwaitExpression */: - ts.Debug.type(node); - return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 219 /* SyntaxKind.PrefixUnaryExpression */: - ts.Debug.type(node); - return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 220 /* SyntaxKind.PostfixUnaryExpression */: - ts.Debug.type(node); - return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 221 /* SyntaxKind.BinaryExpression */: - ts.Debug.type(node); - return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isBinaryOperatorToken), nodeVisitor(node.right, visitor, ts.isExpression)); - case 222 /* SyntaxKind.ConditionalExpression */: - ts.Debug.type(node); - return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isColonToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); - case 223 /* SyntaxKind.TemplateExpression */: - ts.Debug.type(node); - return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 224 /* SyntaxKind.YieldExpression */: - ts.Debug.type(node); - return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 225 /* SyntaxKind.SpreadElement */: - ts.Debug.type(node); - return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 226 /* SyntaxKind.ClassExpression */: - ts.Debug.type(node); - return factory.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: - ts.Debug.type(node); - return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 229 /* SyntaxKind.AsExpression */: - ts.Debug.type(node); - return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 230 /* SyntaxKind.NonNullExpression */: - if (node.flags & 32 /* NodeFlags.OptionalChain */) { - ts.Debug.type(node); - return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - } - ts.Debug.type(node); - return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 231 /* SyntaxKind.MetaProperty */: - ts.Debug.type(node); - return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - // Misc - case 233 /* SyntaxKind.TemplateSpan */: - ts.Debug.type(node); - return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); - // Element - case 235 /* SyntaxKind.Block */: - ts.Debug.type(node); - return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 237 /* SyntaxKind.VariableStatement */: - ts.Debug.type(node); - return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 238 /* SyntaxKind.ExpressionStatement */: - ts.Debug.type(node); - return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 239 /* SyntaxKind.IfStatement */: - ts.Debug.type(node); - return factory.updateIfStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.thenStatement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.elseStatement, visitor, ts.isStatement, factory.liftToBlock)); - case 240 /* SyntaxKind.DoStatement */: - ts.Debug.type(node); - return factory.updateDoStatement(node, visitIterationBody(node.statement, visitor, context), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 241 /* SyntaxKind.WhileStatement */: - ts.Debug.type(node); - return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); - case 242 /* SyntaxKind.ForStatement */: - ts.Debug.type(node); - return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); - case 243 /* SyntaxKind.ForInStatement */: - ts.Debug.type(node); - return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); - case 244 /* SyntaxKind.ForOfStatement */: - ts.Debug.type(node); - return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isAwaitKeyword), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); - case 245 /* SyntaxKind.ContinueStatement */: - ts.Debug.type(node); - return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 246 /* SyntaxKind.BreakStatement */: - ts.Debug.type(node); - return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 247 /* SyntaxKind.ReturnStatement */: - ts.Debug.type(node); - return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 248 /* SyntaxKind.WithStatement */: - ts.Debug.type(node); - return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 249 /* SyntaxKind.SwitchStatement */: - ts.Debug.type(node); - return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock)); - case 250 /* SyntaxKind.LabeledStatement */: - ts.Debug.type(node); - return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 251 /* SyntaxKind.ThrowStatement */: - ts.Debug.type(node); - return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 252 /* SyntaxKind.TryStatement */: - ts.Debug.type(node); - return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock)); - case 254 /* SyntaxKind.VariableDeclaration */: - ts.Debug.type(node); - return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 255 /* SyntaxKind.VariableDeclarationList */: - ts.Debug.type(node); - return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 256 /* SyntaxKind.FunctionDeclaration */: - ts.Debug.type(node); - return factory.updateFunctionDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 257 /* SyntaxKind.ClassDeclaration */: - ts.Debug.type(node); - return factory.updateClassDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 258 /* SyntaxKind.InterfaceDeclaration */: - ts.Debug.type(node); - return factory.updateInterfaceDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 259 /* SyntaxKind.TypeAliasDeclaration */: - ts.Debug.type(node); - return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 260 /* SyntaxKind.EnumDeclaration */: - ts.Debug.type(node); - return factory.updateEnumDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 261 /* SyntaxKind.ModuleDeclaration */: - ts.Debug.type(node); - return factory.updateModuleDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); - case 262 /* SyntaxKind.ModuleBlock */: - ts.Debug.type(node); - return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 263 /* SyntaxKind.CaseBlock */: - ts.Debug.type(node); - return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 264 /* SyntaxKind.NamespaceExportDeclaration */: - ts.Debug.type(node); - return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - ts.Debug.type(node); - return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); - case 266 /* SyntaxKind.ImportDeclaration */: - ts.Debug.type(node); - return factory.updateImportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); - case 293 /* SyntaxKind.AssertClause */: - ts.Debug.type(node); - return factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine); - case 294 /* SyntaxKind.AssertEntry */: - ts.Debug.type(node); - return factory.updateAssertEntry(node, nodeVisitor(node.name, visitor, ts.isAssertionKey), nodeVisitor(node.value, visitor, ts.isExpressionNode)); - case 267 /* SyntaxKind.ImportClause */: - ts.Debug.type(node); - return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 268 /* SyntaxKind.NamespaceImport */: - ts.Debug.type(node); - return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 274 /* SyntaxKind.NamespaceExport */: - ts.Debug.type(node); - return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 269 /* SyntaxKind.NamedImports */: - ts.Debug.type(node); - return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 270 /* SyntaxKind.ImportSpecifier */: - ts.Debug.type(node); - return factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 271 /* SyntaxKind.ExportAssignment */: - ts.Debug.type(node); - return factory.updateExportAssignment(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 272 /* SyntaxKind.ExportDeclaration */: - ts.Debug.type(node); - return factory.updateExportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); - case 273 /* SyntaxKind.NamedExports */: - ts.Debug.type(node); - return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 275 /* SyntaxKind.ExportSpecifier */: - ts.Debug.type(node); - return factory.updateExportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); - // Module references - case 277 /* SyntaxKind.ExternalModuleReference */: - ts.Debug.type(node); - return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - // JSX - case 278 /* SyntaxKind.JsxElement */: - ts.Debug.type(node); - return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement)); - case 279 /* SyntaxKind.JsxSelfClosingElement */: - ts.Debug.type(node); - return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 280 /* SyntaxKind.JsxOpeningElement */: - ts.Debug.type(node); - return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 281 /* SyntaxKind.JsxClosingElement */: - ts.Debug.type(node); - return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 282 /* SyntaxKind.JsxFragment */: - ts.Debug.type(node); - return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 285 /* SyntaxKind.JsxAttribute */: - ts.Debug.type(node); - return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 286 /* SyntaxKind.JsxAttributes */: - ts.Debug.type(node); - return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 287 /* SyntaxKind.JsxSpreadAttribute */: - ts.Debug.type(node); - return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 288 /* SyntaxKind.JsxExpression */: - ts.Debug.type(node); - return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - // Clauses - case 289 /* SyntaxKind.CaseClause */: - ts.Debug.type(node); - return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 290 /* SyntaxKind.DefaultClause */: - ts.Debug.type(node); - return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 291 /* SyntaxKind.HeritageClause */: - ts.Debug.type(node); - return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 292 /* SyntaxKind.CatchClause */: - ts.Debug.type(node); - return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock)); - // Property assignments - case 296 /* SyntaxKind.PropertyAssignment */: - ts.Debug.type(node); - return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - ts.Debug.type(node); - return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 298 /* SyntaxKind.SpreadAssignment */: - ts.Debug.type(node); - return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - // Enum - case 299 /* SyntaxKind.EnumMember */: - ts.Debug.type(node); - return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); - // Top-level nodes - case 305 /* SyntaxKind.SourceFile */: - ts.Debug.type(node); - return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context)); - // Transformation nodes - case 350 /* SyntaxKind.PartiallyEmittedExpression */: - ts.Debug.type(node); - return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 351 /* SyntaxKind.CommaListExpression */: - ts.Debug.type(node); - return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - default: - // No need to visit nodes with no children. - return node; - } + var fn = visitEachChildTable[node.kind]; + return fn === undefined ? node : fn(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor); } ts.visitEachChild = visitEachChild; + // NOTE: Before you can add a new method to `visitEachChildTable`, you must first ensure the `Node` subtype you + // wish to add is defined in the `HasChildren` union in types.ts. + var visitEachChildTable = (_a = {}, + _a[79 /* SyntaxKind.Identifier */] = function visitEachChildOfIdentifier(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNodeOrTypeParameterDeclaration)); + }, + _a[163 /* SyntaxKind.QualifiedName */] = function visitEachChildOfQualifiedName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier)); + }, + _a[164 /* SyntaxKind.ComputedPropertyName */] = function visitEachChildOfComputedPropertyName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + // Signature elements + _a[165 /* SyntaxKind.TypeParameter */] = function visitEachChildOfTypeParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); + }, + _a[166 /* SyntaxKind.Parameter */] = function visitEachChildOfParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + }, + _a[167 /* SyntaxKind.Decorator */] = function visitEachChildOfDecorator(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + // Type elements + _a[168 /* SyntaxKind.PropertySignature */] = function visitEachChildOfPropertySignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[169 /* SyntaxKind.PropertyDeclaration */] = function visitEachChildOfPropertyDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + var _a; + return context.factory.updatePropertyDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), + // QuestionToken and ExclamationToken are mutually exclusive in PropertyDeclaration + nodeVisitor((_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + }, + _a[170 /* SyntaxKind.MethodSignature */] = function visitEachChildOfMethodSignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[171 /* SyntaxKind.MethodDeclaration */] = function visitEachChildOfMethodDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateMethodDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + }, + _a[173 /* SyntaxKind.Constructor */] = function visitEachChildOfConstructorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateConstructorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + }, + _a[174 /* SyntaxKind.GetAccessor */] = function visitEachChildOfGetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateGetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + }, + _a[175 /* SyntaxKind.SetAccessor */] = function visitEachChildOfSetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateSetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + }, + _a[172 /* SyntaxKind.ClassStaticBlockDeclaration */] = function visitEachChildOfClassStaticBlockDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + context.startLexicalEnvironment(); + context.suspendLexicalEnvironment(); + return context.factory.updateClassStaticBlockDeclaration(node, visitFunctionBody(node.body, visitor, context, nodeVisitor)); + }, + _a[176 /* SyntaxKind.CallSignature */] = function visitEachChildOfCallSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[177 /* SyntaxKind.ConstructSignature */] = function visitEachChildOfConstructSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[178 /* SyntaxKind.IndexSignature */] = function visitEachChildOfIndexSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateIndexSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + // Types + _a[179 /* SyntaxKind.TypePredicate */] = function visitEachChildOfTypePredicateNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, ts.isAssertsKeyword), nodeVisitor(node.parameterName, visitor, ts.isIdentifierOrThisTypeNode), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[180 /* SyntaxKind.TypeReference */] = function visitEachChildOfTypeReferenceNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + }, + _a[181 /* SyntaxKind.FunctionType */] = function visitEachChildOfFunctionTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[182 /* SyntaxKind.ConstructorType */] = function visitEachChildOfConstructorTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[183 /* SyntaxKind.TypeQuery */] = function visitEachChildOfTypeQueryNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + }, + _a[184 /* SyntaxKind.TypeLiteral */] = function visitEachChildOfTypeLiteralNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); + }, + _a[185 /* SyntaxKind.ArrayType */] = function visitEachChildOfArrayTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode)); + }, + _a[186 /* SyntaxKind.TupleType */] = function visitEachChildOfTupleTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode)); + }, + _a[187 /* SyntaxKind.OptionalType */] = function visitEachChildOfOptionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[188 /* SyntaxKind.RestType */] = function visitEachChildOfRestTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[189 /* SyntaxKind.UnionType */] = function visitEachChildOfUnionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + }, + _a[190 /* SyntaxKind.IntersectionType */] = function visitEachChildOfIntersectionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + }, + _a[191 /* SyntaxKind.ConditionalType */] = function visitEachChildOfConditionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateConditionalTypeNode(node, nodeVisitor(node.checkType, visitor, ts.isTypeNode), nodeVisitor(node.extendsType, visitor, ts.isTypeNode), nodeVisitor(node.trueType, visitor, ts.isTypeNode), nodeVisitor(node.falseType, visitor, ts.isTypeNode)); + }, + _a[192 /* SyntaxKind.InferType */] = function visitEachChildOfInferTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); + }, + _a[202 /* SyntaxKind.ImportType */] = function visitEachChildOfImportTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isImportTypeAssertionContainer), nodeVisitor(node.qualifier, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + }, + _a[298 /* SyntaxKind.ImportTypeAssertionContainer */] = function visitEachChildOfImportTypeAssertionContainer(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportTypeAssertionContainer(node, nodeVisitor(node.assertClause, visitor, ts.isAssertClause), node.multiLine); + }, + _a[199 /* SyntaxKind.NamedTupleMember */] = function visitEachChildOfNamedTupleMember(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateNamedTupleMember(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[193 /* SyntaxKind.ParenthesizedType */] = function visitEachChildOfParenthesizedType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[195 /* SyntaxKind.TypeOperator */] = function visitEachChildOfTypeOperatorNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[196 /* SyntaxKind.IndexedAccessType */] = function visitEachChildOfIndexedAccessType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); + }, + _a[197 /* SyntaxKind.MappedType */] = function visitEachChildOfMappedType(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodesVisitor(node.members, visitor, ts.isTypeElement)); + }, + _a[198 /* SyntaxKind.LiteralType */] = function visitEachChildOfLiteralTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); + }, + _a[200 /* SyntaxKind.TemplateLiteralType */] = function visitEachChildOfTemplateLiteralType(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan)); + }, + _a[201 /* SyntaxKind.TemplateLiteralTypeSpan */] = function visitEachChildOfTemplateLiteralTypeSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + }, + // Binding patterns + _a[203 /* SyntaxKind.ObjectBindingPattern */] = function visitEachChildOfObjectBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); + }, + _a[204 /* SyntaxKind.ArrayBindingPattern */] = function visitEachChildOfArrayBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); + }, + _a[205 /* SyntaxKind.BindingElement */] = function visitEachChildOfBindingElement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); + }, + // Expression + _a[206 /* SyntaxKind.ArrayLiteralExpression */] = function visitEachChildOfArrayLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + }, + _a[207 /* SyntaxKind.ObjectLiteralExpression */] = function visitEachChildOfObjectLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + }, + _a[208 /* SyntaxKind.PropertyAccessExpression */] = function visitEachChildOfPropertyAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return ts.isPropertyAccessChain(node) ? + context.factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.name, visitor, ts.isMemberName)) : + context.factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isMemberName)); + }, + _a[209 /* SyntaxKind.ElementAccessExpression */] = function visitEachChildOfElementAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return ts.isElementAccessChain(node) ? + context.factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)) : + context.factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); + }, + _a[210 /* SyntaxKind.CallExpression */] = function visitEachChildOfCallExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return ts.isCallChain(node) ? + context.factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)) : + context.factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + }, + _a[211 /* SyntaxKind.NewExpression */] = function visitEachChildOfNewExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + }, + _a[212 /* SyntaxKind.TaggedTemplateExpression */] = function visitEachChildOfTaggedTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + }, + _a[213 /* SyntaxKind.TypeAssertionExpression */] = function visitEachChildOfTypeAssertionExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[214 /* SyntaxKind.ParenthesizedExpression */] = function visitEachChildOfParenthesizedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[215 /* SyntaxKind.FunctionExpression */] = function visitEachChildOfFunctionExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + }, + _a[216 /* SyntaxKind.ArrowFunction */] = function visitEachChildOfArrowFunction(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isEqualsGreaterThanToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + }, + _a[217 /* SyntaxKind.DeleteExpression */] = function visitEachChildOfDeleteExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[218 /* SyntaxKind.TypeOfExpression */] = function visitEachChildOfTypeOfExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[219 /* SyntaxKind.VoidExpression */] = function visitEachChildOfVoidExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[220 /* SyntaxKind.AwaitExpression */] = function visitEachChildOfAwaitExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[221 /* SyntaxKind.PrefixUnaryExpression */] = function visitEachChildOfPrefixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); + }, + _a[222 /* SyntaxKind.PostfixUnaryExpression */] = function visitEachChildOfPostfixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); + }, + _a[223 /* SyntaxKind.BinaryExpression */] = function visitEachChildOfBinaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isBinaryOperatorToken), nodeVisitor(node.right, visitor, ts.isExpression)); + }, + _a[224 /* SyntaxKind.ConditionalExpression */] = function visitEachChildOfConditionalExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isColonToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); + }, + _a[225 /* SyntaxKind.TemplateExpression */] = function visitEachChildOfTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); + }, + _a[226 /* SyntaxKind.YieldExpression */] = function visitEachChildOfYieldExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[227 /* SyntaxKind.SpreadElement */] = function visitEachChildOfSpreadElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[228 /* SyntaxKind.ClassExpression */] = function visitEachChildOfClassExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + }, + _a[230 /* SyntaxKind.ExpressionWithTypeArguments */] = function visitEachChildOfExpressionWithTypeArguments(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + }, + _a[231 /* SyntaxKind.AsExpression */] = function visitEachChildOfAsExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[235 /* SyntaxKind.SatisfiesExpression */] = function visitEachChildOfSatisfiesExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateSatisfiesExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[232 /* SyntaxKind.NonNullExpression */] = function visitEachChildOfNonNullExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return ts.isOptionalChain(node) ? + context.factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression)) : + context.factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[233 /* SyntaxKind.MetaProperty */] = function visitEachChildOfMetaProperty(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); + }, + // Misc + _a[236 /* SyntaxKind.TemplateSpan */] = function visitEachChildOfTemplateSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + }, + // Element + _a[238 /* SyntaxKind.Block */] = function visitEachChildOfBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + }, + _a[240 /* SyntaxKind.VariableStatement */] = function visitEachChildOfVariableStatement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList)); + }, + _a[241 /* SyntaxKind.ExpressionStatement */] = function visitEachChildOfExpressionStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[242 /* SyntaxKind.IfStatement */] = function visitEachChildOfIfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateIfStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.thenStatement, visitor, ts.isStatement, context.factory.liftToBlock), nodeVisitor(node.elseStatement, visitor, ts.isStatement, context.factory.liftToBlock)); + }, + _a[243 /* SyntaxKind.DoStatement */] = function visitEachChildOfDoStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateDoStatement(node, visitIterationBody(node.statement, visitor, context, nodeVisitor), nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[244 /* SyntaxKind.WhileStatement */] = function visitEachChildOfWhileStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context, nodeVisitor)); + }, + _a[245 /* SyntaxKind.ForStatement */] = function visitEachChildOfForStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context, nodeVisitor)); + }, + _a[246 /* SyntaxKind.ForInStatement */] = function visitEachChildOfForInStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context, nodeVisitor)); + }, + _a[247 /* SyntaxKind.ForOfStatement */] = function visitEachChildOfForOfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isAwaitKeyword), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context, nodeVisitor)); + }, + _a[248 /* SyntaxKind.ContinueStatement */] = function visitEachChildOfContinueStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); + }, + _a[249 /* SyntaxKind.BreakStatement */] = function visitEachChildOfBreakStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); + }, + _a[250 /* SyntaxKind.ReturnStatement */] = function visitEachChildOfReturnStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[251 /* SyntaxKind.WithStatement */] = function visitEachChildOfWithStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, context.factory.liftToBlock)); + }, + _a[252 /* SyntaxKind.SwitchStatement */] = function visitEachChildOfSwitchStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock)); + }, + _a[253 /* SyntaxKind.LabeledStatement */] = function visitEachChildOfLabeledStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, context.factory.liftToBlock)); + }, + _a[254 /* SyntaxKind.ThrowStatement */] = function visitEachChildOfThrowStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[255 /* SyntaxKind.TryStatement */] = function visitEachChildOfTryStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock)); + }, + _a[257 /* SyntaxKind.VariableDeclaration */] = function visitEachChildOfVariableDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + }, + _a[258 /* SyntaxKind.VariableDeclarationList */] = function visitEachChildOfVariableDeclarationList(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); + }, + _a[259 /* SyntaxKind.FunctionDeclaration */] = function visitEachChildOfFunctionDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateFunctionDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + }, + _a[260 /* SyntaxKind.ClassDeclaration */] = function visitEachChildOfClassDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateClassDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + }, + _a[261 /* SyntaxKind.InterfaceDeclaration */] = function visitEachChildOfInterfaceDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateInterfaceDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + }, + _a[262 /* SyntaxKind.TypeAliasDeclaration */] = function visitEachChildOfTypeAliasDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeAliasDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + }, + _a[263 /* SyntaxKind.EnumDeclaration */] = function visitEachChildOfEnumDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateEnumDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + }, + _a[264 /* SyntaxKind.ModuleDeclaration */] = function visitEachChildOfModuleDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateModuleDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + }, + _a[265 /* SyntaxKind.ModuleBlock */] = function visitEachChildOfModuleBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + }, + _a[266 /* SyntaxKind.CaseBlock */] = function visitEachChildOfCaseBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + }, + _a[267 /* SyntaxKind.NamespaceExportDeclaration */] = function visitEachChildOfNamespaceExportDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); + }, + _a[268 /* SyntaxKind.ImportEqualsDeclaration */] = function visitEachChildOfImportEqualsDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportEqualsDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); + }, + _a[269 /* SyntaxKind.ImportDeclaration */] = function visitEachChildOfImportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + }, + _a[296 /* SyntaxKind.AssertClause */] = function visitEachChildOfAssertClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine); + }, + _a[297 /* SyntaxKind.AssertEntry */] = function visitEachChildOfAssertEntry(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateAssertEntry(node, nodeVisitor(node.name, visitor, ts.isAssertionKey), nodeVisitor(node.value, visitor, ts.isExpression)); + }, + _a[270 /* SyntaxKind.ImportClause */] = function visitEachChildOfImportClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings)); + }, + _a[271 /* SyntaxKind.NamespaceImport */] = function visitEachChildOfNamespaceImport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); + }, + _a[277 /* SyntaxKind.NamespaceExport */] = function visitEachChildOfNamespaceExport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); + }, + _a[272 /* SyntaxKind.NamedImports */] = function visitEachChildOfNamedImports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); + }, + _a[273 /* SyntaxKind.ImportSpecifier */] = function visitEachChildOfImportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); + }, + _a[274 /* SyntaxKind.ExportAssignment */] = function visitEachChildOfExportAssignment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExportAssignment(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[275 /* SyntaxKind.ExportDeclaration */] = function visitEachChildOfExportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + }, + _a[276 /* SyntaxKind.NamedExports */] = function visitEachChildOfNamedExports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + }, + _a[278 /* SyntaxKind.ExportSpecifier */] = function visitEachChildOfExportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); + }, + // Module references + _a[280 /* SyntaxKind.ExternalModuleReference */] = function visitEachChildOfExternalModuleReference(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + // JSX + _a[281 /* SyntaxKind.JsxElement */] = function visitEachChildOfJsxElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement)); + }, + _a[282 /* SyntaxKind.JsxSelfClosingElement */] = function visitEachChildOfJsxSelfClosingElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); + }, + _a[283 /* SyntaxKind.JsxOpeningElement */] = function visitEachChildOfJsxOpeningElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); + }, + _a[284 /* SyntaxKind.JsxClosingElement */] = function visitEachChildOfJsxClosingElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression)); + }, + _a[285 /* SyntaxKind.JsxFragment */] = function visitEachChildOfJsxFragment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment)); + }, + _a[288 /* SyntaxKind.JsxAttribute */] = function visitEachChildOfJsxAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + }, + _a[289 /* SyntaxKind.JsxAttributes */] = function visitEachChildOfJsxAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); + }, + _a[290 /* SyntaxKind.JsxSpreadAttribute */] = function visitEachChildOfJsxSpreadAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[291 /* SyntaxKind.JsxExpression */] = function visitEachChildOfJsxExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + // Clauses + _a[292 /* SyntaxKind.CaseClause */] = function visitEachChildOfCaseClause(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); + }, + _a[293 /* SyntaxKind.DefaultClause */] = function visitEachChildOfDefaultClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + }, + _a[294 /* SyntaxKind.HeritageClause */] = function visitEachChildOfHeritageClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); + }, + _a[295 /* SyntaxKind.CatchClause */] = function visitEachChildOfCatchClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock)); + }, + // Property assignments + _a[299 /* SyntaxKind.PropertyAssignment */] = function visitEachChildOfPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); + }, + _a[300 /* SyntaxKind.ShorthandPropertyAssignment */] = function visitEachChildOfShorthandPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression)); + }, + _a[301 /* SyntaxKind.SpreadAssignment */] = function visitEachChildOfSpreadAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + // Enum + _a[302 /* SyntaxKind.EnumMember */] = function visitEachChildOfEnumMember(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); + }, + // Top-level nodes + _a[308 /* SyntaxKind.SourceFile */] = function visitEachChildOfSourceFile(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context, /*start*/ undefined, /*ensureUseStrict*/ undefined, nodesVisitor)); + }, + // Transformation nodes + _a[353 /* SyntaxKind.PartiallyEmittedExpression */] = function visitEachChildOfPartiallyEmittedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + }, + _a[354 /* SyntaxKind.CommaListExpression */] = function visitEachChildOfCommaListExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + }, + _a); /** * Extracts the single node from a NodeArray. * @@ -91630,7 +92357,7 @@ var ts; exit(); return sourceIndex; } - /* eslint-disable boolean-trivia, no-null/no-null */ + /* eslint-disable local/boolean-trivia, no-null/no-null */ function setSourceContent(sourceIndex, content) { enter(); if (content !== null) { @@ -91643,7 +92370,7 @@ var ts; } exit(); } - /* eslint-enable boolean-trivia, no-null/no-null */ + /* eslint-enable local/boolean-trivia, no-null/no-null */ function addName(name) { enter(); if (!nameToNameIndexMap) @@ -92245,7 +92972,7 @@ var ts; function chainBundle(context, transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 305 /* SyntaxKind.SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 308 /* SyntaxKind.SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -92296,7 +93023,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -92309,13 +93036,13 @@ var ts; hasImportDefault = true; } break; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - if (node.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */) { + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + if (node.moduleReference.kind === 280 /* SyntaxKind.ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -92346,13 +93073,13 @@ var ts; addExportedNamesForExportDeclaration(node); } break; - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) { var decl = _c[_b]; @@ -92360,9 +93087,9 @@ var ts; } } break; - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - if (ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)) { + if (ts.hasSyntacticModifier(node, 1024 /* ModifierFlags.Default */)) { // export default function() { } if (!hasExportDefault) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node)); @@ -92380,9 +93107,9 @@ var ts; } } break; - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - if (ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)) { + if (ts.hasSyntacticModifier(node, 1024 /* ModifierFlags.Default */)) { // export default class { } if (!hasExportDefault) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node)); @@ -92560,7 +93287,7 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member) { - return member.kind === 167 /* SyntaxKind.PropertyDeclaration */ + return member.kind === 169 /* SyntaxKind.PropertyDeclaration */ && member.initializer !== undefined; } ts.isInitializedProperty = isInitializedProperty; @@ -92570,7 +93297,7 @@ var ts; * @param member The class element node. */ function isNonStaticMethodOrAccessorWithPrivateName(member) { - return !ts.isStatic(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); + return !ts.isStatic(member) && (ts.isMethodOrAccessor(member) || ts.isAutoAccessorPropertyDeclaration(member)) && ts.isPrivateIdentifier(member.name); } ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; /** @@ -92624,12 +93351,12 @@ var ts; */ function getAllDecoratorsOfClassElement(member, parent) { switch (member.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return getAllDecoratorsOfAccessors(member, parent); - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -93290,8 +94017,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(206 /* SyntaxKind.PropertyAccessExpression */); - context.enableSubstitution(207 /* SyntaxKind.ElementAccessExpression */); + context.enableSubstitution(208 /* SyntaxKind.PropertyAccessExpression */); + context.enableSubstitution(209 /* SyntaxKind.ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -93311,14 +94038,14 @@ var ts; var applicableSubstitutions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 306 /* SyntaxKind.Bundle */) { + if (node.kind === 309 /* SyntaxKind.Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 308 /* SyntaxKind.InputFiles */) { + if (prepend.kind === 311 /* SyntaxKind.InputFiles */) { return ts.createUnparsedSourceFile(prepend, "js"); } return prepend; @@ -93367,15 +94094,15 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 305 /* SyntaxKind.SourceFile */: - case 263 /* SyntaxKind.CaseBlock */: - case 262 /* SyntaxKind.ModuleBlock */: - case 235 /* SyntaxKind.Block */: + case 308 /* SyntaxKind.SourceFile */: + case 266 /* SyntaxKind.CaseBlock */: + case 265 /* SyntaxKind.ModuleBlock */: + case 238 /* SyntaxKind.Block */: currentLexicalScope = node; currentScopeFirstDeclarationsOfName = undefined; break; - case 257 /* SyntaxKind.ClassDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 2 /* ModifierFlags.Ambient */)) { break; } @@ -93387,7 +94114,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 257 /* SyntaxKind.ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)); + ts.Debug.assert(node.kind === 260 /* SyntaxKind.ClassDeclaration */ || ts.hasSyntacticModifier(node, 1024 /* ModifierFlags.Default */)); } break; } @@ -93426,10 +94153,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 271 /* SyntaxKind.ExportAssignment */: - case 272 /* SyntaxKind.ExportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 274 /* SyntaxKind.ExportAssignment */: + case 275 /* SyntaxKind.ExportDeclaration */: return visitElidableStatement(node); default: return visitorWorker(node); @@ -93450,13 +94177,13 @@ var ts; return node; } switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return visitImportDeclaration(node); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: return visitExportAssignment(node); - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -93476,11 +94203,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 272 /* SyntaxKind.ExportDeclaration */ || - node.kind === 266 /* SyntaxKind.ImportDeclaration */ || - node.kind === 267 /* SyntaxKind.ImportClause */ || - (node.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ && - node.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */)) { + if (node.kind === 275 /* SyntaxKind.ExportDeclaration */ || + node.kind === 269 /* SyntaxKind.ImportDeclaration */ || + node.kind === 270 /* SyntaxKind.ImportClause */ || + (node.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ && + node.moduleReference.kind === 280 /* SyntaxKind.ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -93504,27 +94231,27 @@ var ts; */ function classElementVisitorWorker(node, parent) { switch (node.kind) { - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return visitConstructor(node); - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. return visitPropertyDeclaration(node, parent); - case 172 /* SyntaxKind.GetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node, parent); - case 173 /* SyntaxKind.SetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node, parent); - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node, parent); - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: return ts.visitEachChild(node, visitor, context); - case 234 /* SyntaxKind.SemicolonClassElement */: + case 237 /* SyntaxKind.SemicolonClassElement */: return node; - case 176 /* SyntaxKind.IndexSignature */: + case 178 /* SyntaxKind.IndexSignature */: // Index signatures are elided return; default: @@ -93536,17 +94263,17 @@ var ts; } function objectLiteralElementVisitorWorker(node, parent) { switch (node.kind) { - case 296 /* SyntaxKind.PropertyAssignment */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 298 /* SyntaxKind.SpreadAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 301 /* SyntaxKind.SpreadAssignment */: return visitor(node); - case 172 /* SyntaxKind.GetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node, parent); - case 173 /* SyntaxKind.SetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node, parent); - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node, parent); @@ -93557,7 +94284,7 @@ var ts; function modifierVisitor(node) { if (ts.isDecorator(node)) return undefined; - if (ts.modifierToFlag(node.kind) & 116958 /* ModifierFlags.TypeScriptModifier */) { + if (ts.modifierToFlag(node.kind) & 117086 /* ModifierFlags.TypeScriptModifier */) { return undefined; } else if (currentNamespace && node.kind === 93 /* SyntaxKind.ExportKeyword */) { @@ -93585,58 +94312,58 @@ var ts; case 121 /* SyntaxKind.PrivateKeyword */: case 122 /* SyntaxKind.ProtectedKeyword */: case 126 /* SyntaxKind.AbstractKeyword */: - case 159 /* SyntaxKind.OverrideKeyword */: + case 161 /* SyntaxKind.OverrideKeyword */: case 85 /* SyntaxKind.ConstKeyword */: - case 135 /* SyntaxKind.DeclareKeyword */: - case 145 /* SyntaxKind.ReadonlyKeyword */: + case 136 /* SyntaxKind.DeclareKeyword */: + case 146 /* SyntaxKind.ReadonlyKeyword */: case 101 /* SyntaxKind.InKeyword */: - case 144 /* SyntaxKind.OutKeyword */: + case 145 /* SyntaxKind.OutKeyword */: // TypeScript accessibility and readonly modifiers are elided // falls through - case 183 /* SyntaxKind.ArrayType */: - case 184 /* SyntaxKind.TupleType */: - case 185 /* SyntaxKind.OptionalType */: - case 186 /* SyntaxKind.RestType */: - case 182 /* SyntaxKind.TypeLiteral */: - case 177 /* SyntaxKind.TypePredicate */: - case 163 /* SyntaxKind.TypeParameter */: - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 133 /* SyntaxKind.BooleanKeyword */: - case 150 /* SyntaxKind.StringKeyword */: - case 147 /* SyntaxKind.NumberKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: + case 185 /* SyntaxKind.ArrayType */: + case 186 /* SyntaxKind.TupleType */: + case 187 /* SyntaxKind.OptionalType */: + case 188 /* SyntaxKind.RestType */: + case 184 /* SyntaxKind.TypeLiteral */: + case 179 /* SyntaxKind.TypePredicate */: + case 165 /* SyntaxKind.TypeParameter */: + case 131 /* SyntaxKind.AnyKeyword */: + case 157 /* SyntaxKind.UnknownKeyword */: + case 134 /* SyntaxKind.BooleanKeyword */: + case 152 /* SyntaxKind.StringKeyword */: + case 148 /* SyntaxKind.NumberKeyword */: + case 144 /* SyntaxKind.NeverKeyword */: case 114 /* SyntaxKind.VoidKeyword */: - case 151 /* SyntaxKind.SymbolKeyword */: - case 180 /* SyntaxKind.ConstructorType */: - case 179 /* SyntaxKind.FunctionType */: - case 181 /* SyntaxKind.TypeQuery */: - case 178 /* SyntaxKind.TypeReference */: - case 187 /* SyntaxKind.UnionType */: - case 188 /* SyntaxKind.IntersectionType */: - case 189 /* SyntaxKind.ConditionalType */: - case 191 /* SyntaxKind.ParenthesizedType */: - case 192 /* SyntaxKind.ThisType */: - case 193 /* SyntaxKind.TypeOperator */: - case 194 /* SyntaxKind.IndexedAccessType */: - case 195 /* SyntaxKind.MappedType */: - case 196 /* SyntaxKind.LiteralType */: + case 153 /* SyntaxKind.SymbolKeyword */: + case 182 /* SyntaxKind.ConstructorType */: + case 181 /* SyntaxKind.FunctionType */: + case 183 /* SyntaxKind.TypeQuery */: + case 180 /* SyntaxKind.TypeReference */: + case 189 /* SyntaxKind.UnionType */: + case 190 /* SyntaxKind.IntersectionType */: + case 191 /* SyntaxKind.ConditionalType */: + case 193 /* SyntaxKind.ParenthesizedType */: + case 194 /* SyntaxKind.ThisType */: + case 195 /* SyntaxKind.TypeOperator */: + case 196 /* SyntaxKind.IndexedAccessType */: + case 197 /* SyntaxKind.MappedType */: + case 198 /* SyntaxKind.LiteralType */: // TypeScript type nodes are elided. // falls through - case 176 /* SyntaxKind.IndexSignature */: + case 178 /* SyntaxKind.IndexSignature */: // TypeScript index signatures are elided. return undefined; - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return factory.createNotEmittedStatement(node); - case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 267 /* SyntaxKind.NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return factory.createNotEmittedStatement(node); - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -93646,7 +94373,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 226 /* SyntaxKind.ClassExpression */: + case 228 /* SyntaxKind.ClassExpression */: // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -93656,34 +94383,34 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 291 /* SyntaxKind.HeritageClause */: + case 294 /* SyntaxKind.HeritageClause */: // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 171 /* SyntaxKind.Constructor */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: return ts.Debug.fail("Class and object literal elements must be visited with their respective visitors"); - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 213 /* SyntaxKind.FunctionExpression */: + case 215 /* SyntaxKind.FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -93693,40 +94420,42 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 211 /* SyntaxKind.TypeAssertionExpression */: - case 229 /* SyntaxKind.AsExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: + case 231 /* SyntaxKind.AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 208 /* SyntaxKind.CallExpression */: + case 235 /* SyntaxKind.SatisfiesExpression */: + return visitSatisfiesExpression(node); + case 210 /* SyntaxKind.CallExpression */: return visitCallExpression(node); - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: return visitNewExpression(node); - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 230 /* SyntaxKind.NonNullExpression */: + case 232 /* SyntaxKind.NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return visitVariableDeclaration(node); - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: return visitJsxSelfClosingElement(node); - case 280 /* SyntaxKind.JsxOpeningElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax @@ -93996,10 +94725,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */; + return kind === 171 /* SyntaxKind.MethodDeclaration */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 175 /* SyntaxKind.SetAccessor */ + || kind === 169 /* SyntaxKind.PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -94009,7 +94738,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 169 /* SyntaxKind.MethodDeclaration */; + return node.kind === 171 /* SyntaxKind.MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -94020,12 +94749,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return true; } return false; @@ -94115,7 +94844,7 @@ var ts; return !ts.nodeIsMissing(node.body); } function visitPropertyDeclaration(node, parent) { - var isAmbient = node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */); + var isAmbient = node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 256 /* ModifierFlags.Abstract */); if (isAmbient && !ts.hasDecorators(node)) { return undefined; } @@ -94223,7 +94952,7 @@ var ts; * @param node The declaration node. */ function shouldEmitAccessorDeclaration(node) { - return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)); + return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 256 /* ModifierFlags.Abstract */)); } function visitGetAccessor(node, parent) { if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { @@ -94365,6 +95094,10 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); return factory.createPartiallyEmittedExpression(expression, node); } + function visitSatisfiesExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return factory.createPartiallyEmittedExpression(expression, node); + } function visitCallExpression(node) { return factory.updateCallExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression), /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); @@ -94578,12 +95311,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([ factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 305 /* SyntaxKind.SourceFile */ ? 0 /* NodeFlags.None */ : 1 /* NodeFlags.Let */)); + ], currentLexicalScope.kind === 308 /* SyntaxKind.SourceFile */ ? 0 /* NodeFlags.None */ : 1 /* NodeFlags.Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 260 /* SyntaxKind.EnumDeclaration */) { + if (node.kind === 263 /* SyntaxKind.EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -94708,7 +95441,7 @@ var ts; var statementsLocation; var blockLocation; if (node.body) { - if (node.body.kind === 262 /* SyntaxKind.ModuleBlock */) { + if (node.body.kind === 265 /* SyntaxKind.ModuleBlock */) { saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = node.body.statements; blockLocation = node.body; @@ -94755,13 +95488,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (!node.body || node.body.kind !== 262 /* SyntaxKind.ModuleBlock */) { + if (!node.body || node.body.kind !== 265 /* SyntaxKind.ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* EmitFlags.NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 261 /* SyntaxKind.ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 264 /* SyntaxKind.ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -94808,7 +95541,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 268 /* SyntaxKind.NamespaceImport */) { + if (node.kind === 271 /* SyntaxKind.NamespaceImport */) { // Elide a namespace import if it is not referenced. return shouldEmitAliasDeclaration(node) ? node : undefined; } @@ -94966,7 +95699,7 @@ var ts; */ function isNamedExternalModuleExport(node) { return isExternalModuleExport(node) - && !ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */); + && !ts.hasSyntacticModifier(node, 1024 /* ModifierFlags.Default */); } /** * Gets a value indicating whether the node is the default export of an external module. @@ -94975,7 +95708,7 @@ var ts; */ function isDefaultExternalModuleExport(node) { return isExternalModuleExport(node) - && ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */); + && ts.hasSyntacticModifier(node, 1024 /* ModifierFlags.Default */); } function addExportMemberAssignment(statements, node) { var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node)); @@ -95020,16 +95753,16 @@ var ts; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. context.enableSubstitution(79 /* SyntaxKind.Identifier */); - context.enableSubstitution(297 /* SyntaxKind.ShorthandPropertyAssignment */); + context.enableSubstitution(300 /* SyntaxKind.ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(261 /* SyntaxKind.ModuleDeclaration */); + context.enableEmitNotification(264 /* SyntaxKind.ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 261 /* SyntaxKind.ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 264 /* SyntaxKind.ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 260 /* SyntaxKind.EnumDeclaration */; + return ts.getOriginalNode(node).kind === 263 /* SyntaxKind.EnumDeclaration */; } /** * Hook for node emit. @@ -95090,9 +95823,9 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: return substituteExpressionIdentifier(node); - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -95107,9 +95840,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 305 /* SyntaxKind.SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* TypeScriptSubstitutionFlags.NamespaceExports */ && container.kind === 261 /* SyntaxKind.ModuleDeclaration */) || - (applicableSubstitutions & 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */ && container.kind === 260 /* SyntaxKind.EnumDeclaration */); + if (container && container.kind !== 308 /* SyntaxKind.SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* TypeScriptSubstitutionFlags.NamespaceExports */ && container.kind === 264 /* SyntaxKind.ModuleDeclaration */) || + (applicableSubstitutions & 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */ && container.kind === 263 /* SyntaxKind.EnumDeclaration */); if (substitute) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), /*location*/ node); @@ -95148,9 +95881,10 @@ var ts; return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined; } function shouldEmitAliasDeclaration(node) { - return compilerOptions.preserveValueImports - ? resolver.isValueAliasDeclaration(node) - : resolver.isReferencedAliasDeclaration(node); + return ts.isInJSFile(node) || + (compilerOptions.preserveValueImports + ? resolver.isValueAliasDeclaration(node) + : resolver.isReferencedAliasDeclaration(node)); } } ts.transformTypeScript = transformTypeScript; @@ -95198,13 +95932,24 @@ var ts; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); + // Always transform field initializers using Set semantics when `useDefineForClassFields: false`. + var shouldTransformInitializersUsingSet = !useDefineForClassFields; + // Transform field initializers using Define semantics when `useDefineForClassFields: true` and target < ES2022. + var shouldTransformInitializersUsingDefine = useDefineForClassFields && languageVersion < 9 /* ScriptTarget.ES2022 */; + var shouldTransformInitializers = shouldTransformInitializersUsingSet || shouldTransformInitializersUsingDefine; + // We need to transform private members and class static blocks when target < ES2022. var shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < 9 /* ScriptTarget.ES2022 */; + // We need to transform `accessor` fields when target < ESNext + var shouldTransformAutoAccessors = languageVersion < 99 /* ScriptTarget.ESNext */; // We need to transform `this` in a static initializer into a reference to the class - // when targeting < ES2022 since the assignment will be moved outside of the class body. + // when target < ES2022 since the assignment will be moved outside of the class body. var shouldTransformThisInStaticInitializers = languageVersion < 9 /* ScriptTarget.ES2022 */; - // We don't need to transform `super` property access when targeting ES5, ES3 because + // We don't need to transform `super` property access when target <= ES5 because // the es2015 transformation handles those. var shouldTransformSuperInStaticInitializers = shouldTransformThisInStaticInitializers && languageVersion >= 2 /* ScriptTarget.ES2015 */; + var shouldTransformAnything = shouldTransformInitializers || + shouldTransformPrivateElementsOrClassStaticBlocks || + shouldTransformAutoAccessors; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -95224,98 +95969,149 @@ var ts; var classLexicalEnvironmentStack = []; var classLexicalEnvironmentMap = new ts.Map(); var currentClassLexicalEnvironment; + var currentClassContainer; var currentComputedPropertyNameClassLexicalEnvironment; var currentStaticPropertyDeclarationOrStaticBlock; return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { - var options = context.getCompilerOptions(); - if (node.isDeclarationFile - || useDefineForClassFields && ts.getEmitScriptTarget(options) >= 9 /* ScriptTarget.ES2022 */) { + if (node.isDeclarationFile || !shouldTransformAnything) { return node; } var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); return visited; } - function visitorWorker(node, valueIsDiscarded) { - if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */) { - switch (node.kind) { - case 226 /* SyntaxKind.ClassExpression */: - case 257 /* SyntaxKind.ClassDeclaration */: - return visitClassLike(node); - case 167 /* SyntaxKind.PropertyDeclaration */: - return visitPropertyDeclaration(node); - case 237 /* SyntaxKind.VariableStatement */: - return visitVariableStatement(node); - case 80 /* SyntaxKind.PrivateIdentifier */: - return visitPrivateIdentifier(node); - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - return visitClassStaticBlockDeclaration(node); - } + function visitor(node) { + if (!(node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */) && + !(node.transformFlags & 134234112 /* TransformFlags.ContainsLexicalThisOrSuper */)) { + return node; } - if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */ || - node.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */ && - shouldTransformSuperInStaticInitializers && - currentStaticPropertyDeclarationOrStaticBlock && - currentClassLexicalEnvironment) { - switch (node.kind) { - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 220 /* SyntaxKind.PostfixUnaryExpression */: - return visitPreOrPostfixUnaryExpression(node, valueIsDiscarded); - case 221 /* SyntaxKind.BinaryExpression */: - return visitBinaryExpression(node, valueIsDiscarded); - case 208 /* SyntaxKind.CallExpression */: - return visitCallExpression(node); - case 210 /* SyntaxKind.TaggedTemplateExpression */: - return visitTaggedTemplateExpression(node); - case 206 /* SyntaxKind.PropertyAccessExpression */: - return visitPropertyAccessExpression(node); - case 207 /* SyntaxKind.ElementAccessExpression */: - return visitElementAccessExpression(node); - case 238 /* SyntaxKind.ExpressionStatement */: - return visitExpressionStatement(node); - case 242 /* SyntaxKind.ForStatement */: - return visitForStatement(node); - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 171 /* SyntaxKind.Constructor */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: { - var savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock; - currentStaticPropertyDeclarationOrStaticBlock = undefined; - var result = ts.visitEachChild(node, visitor, context); - currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock; - return result; - } + switch (node.kind) { + case 127 /* SyntaxKind.AccessorKeyword */: + return shouldTransformAutoAccessors ? undefined : node; + case 260 /* SyntaxKind.ClassDeclaration */: + return visitClassDeclaration(node); + case 228 /* SyntaxKind.ClassExpression */: + return visitClassExpression(node); + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: + return visitClassStaticBlockDeclaration(node); + case 169 /* SyntaxKind.PropertyDeclaration */: + return visitPropertyDeclaration(node); + case 240 /* SyntaxKind.VariableStatement */: + return visitVariableStatement(node); + case 80 /* SyntaxKind.PrivateIdentifier */: + return visitPrivateIdentifier(node); + case 208 /* SyntaxKind.PropertyAccessExpression */: + return visitPropertyAccessExpression(node); + case 209 /* SyntaxKind.ElementAccessExpression */: + return visitElementAccessExpression(node); + case 221 /* SyntaxKind.PrefixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: + return visitPreOrPostfixUnaryExpression(node, /*valueIsDiscarded*/ false); + case 223 /* SyntaxKind.BinaryExpression */: + return visitBinaryExpression(node, /*valueIsDiscarded*/ false); + case 210 /* SyntaxKind.CallExpression */: + return visitCallExpression(node); + case 241 /* SyntaxKind.ExpressionStatement */: + return visitExpressionStatement(node); + case 212 /* SyntaxKind.TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 245 /* SyntaxKind.ForStatement */: + return visitForStatement(node); + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 173 /* SyntaxKind.Constructor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: { + // If we are descending into a new scope, clear the current static property or block + return setCurrentStaticPropertyDeclarationOrStaticBlockAnd( + /*current*/ undefined, fallbackVisitor, node); } + default: + return fallbackVisitor(node); } + } + function fallbackVisitor(node) { return ts.visitEachChild(node, visitor, context); } + /** + * Visits a node in an expression whose result is discarded. + */ function discardedValueVisitor(node) { - return visitorWorker(node, /*valueIsDiscarded*/ true); - } - function visitor(node) { - return visitorWorker(node, /*valueIsDiscarded*/ false); + switch (node.kind) { + case 221 /* SyntaxKind.PrefixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: + return visitPreOrPostfixUnaryExpression(node, /*valueIsDiscarded*/ true); + case 223 /* SyntaxKind.BinaryExpression */: + return visitBinaryExpression(node, /*valueIsDiscarded*/ true); + default: + return visitor(node); + } } + /** + * Visits a node in a {@link HeritageClause}. + */ function heritageClauseVisitor(node) { switch (node.kind) { - case 291 /* SyntaxKind.HeritageClause */: + case 294 /* SyntaxKind.HeritageClause */: return ts.visitEachChild(node, heritageClauseVisitor, context); - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: - return visitExpressionWithTypeArguments(node); + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: + return visitExpressionWithTypeArgumentsInHeritageClause(node); + default: + return visitor(node); } - return visitor(node); } - function visitorDestructuringTarget(node) { + /** + * Visits the assignment target of a destructuring assignment. + */ + function assignmentTargetVisitor(node) { switch (node.kind) { - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return visitAssignmentPattern(node); default: return visitor(node); } } + /** + * Visits a member of a class. + */ + function classElementVisitor(node) { + switch (node.kind) { + case 173 /* SyntaxKind.Constructor */: + return visitConstructorDeclaration(node); + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + return setCurrentStaticPropertyDeclarationOrStaticBlockAnd( + /*current*/ undefined, visitMethodOrAccessorDeclaration, node); + case 169 /* SyntaxKind.PropertyDeclaration */: + return setCurrentStaticPropertyDeclarationOrStaticBlockAnd( + /*current*/ undefined, visitPropertyDeclaration, node); + case 164 /* SyntaxKind.ComputedPropertyName */: + return visitComputedPropertyName(node); + case 237 /* SyntaxKind.SemicolonClassElement */: + return node; + default: + return visitor(node); + } + } + /** + * Visits the results of an auto-accessor field transformation in a second pass. + */ + function accessorFieldResultVisitor(node) { + switch (node.kind) { + case 169 /* SyntaxKind.PropertyDeclaration */: + return transformFieldInitializer(node); + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + return classElementVisitor(node); + default: + ts.Debug.assertMissingNode(node, "Expected node to either be a PropertyDeclaration, GetAccessorDeclaration, or SetAccessorDeclaration"); + break; + } + } /** * If we visit a private name, this means it is an undeclared private name. * Replace it with an empty identifier to indicate a problem with the code, @@ -95331,17 +96127,15 @@ var ts; } return ts.setOriginalNode(factory.createIdentifier(""), node); } + function isPrivateIdentifierInExpression(node) { + return ts.isPrivateIdentifier(node.left) + && node.operatorToken.kind === 101 /* SyntaxKind.InKeyword */; + } /** * Visits `#id in expr` */ - function visitPrivateIdentifierInInExpression(node) { - if (!shouldTransformPrivateElementsOrClassStaticBlocks) { - return node; - } - var privId = node.left; - ts.Debug.assertNode(privId, ts.isPrivateIdentifier); - ts.Debug.assert(node.operatorToken.kind === 101 /* SyntaxKind.InKeyword */); - var info = accessPrivateIdentifier(privId); + function transformPrivateIdentifierInInExpression(node) { + var info = accessPrivateIdentifier(node.left); if (info) { var receiver = ts.visitNode(node.right, visitor, ts.isExpression); return ts.setOriginalNode(context.getEmitHelperFactory().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver), node); @@ -95349,31 +96143,6 @@ var ts; // Private name has not been declared. Subsequent transformers will handle this error return ts.visitEachChild(node, visitor, context); } - /** - * Visits the members of a class that has fields. - * - * @param node The node to visit. - */ - function classElementVisitor(node) { - switch (node.kind) { - case 171 /* SyntaxKind.Constructor */: - // Constructors for classes using class fields are transformed in - // `visitClassDeclaration` or `visitClassExpression`. - return undefined; - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 169 /* SyntaxKind.MethodDeclaration */: - return visitMethodOrAccessorDeclaration(node); - case 167 /* SyntaxKind.PropertyDeclaration */: - return visitPropertyDeclaration(node); - case 162 /* SyntaxKind.ComputedPropertyName */: - return visitComputedPropertyName(node); - case 234 /* SyntaxKind.SemicolonClassElement */: - return node; - default: - return visitor(node); - } - } function visitVariableStatement(node) { var savedPendingStatements = pendingStatements; pendingStatements = []; @@ -95383,15 +96152,24 @@ var ts; pendingStatements = savedPendingStatements; return statement; } - function visitComputedPropertyName(name) { - var node = ts.visitEachChild(name, visitor, context); + function visitComputedPropertyName(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); if (ts.some(pendingExpressions)) { - var expressions = pendingExpressions; - expressions.push(node.expression); - pendingExpressions = []; - node = factory.updateComputedPropertyName(node, factory.inlineExpressions(expressions)); + if (ts.isParenthesizedExpression(expression)) { + expression = factory.updateParenthesizedExpression(expression, factory.inlineExpressions(__spreadArray(__spreadArray([], pendingExpressions, true), [expression.expression], false))); + } + else { + expression = factory.inlineExpressions(__spreadArray(__spreadArray([], pendingExpressions, true), [expression], false)); + } + pendingExpressions = undefined; } - return node; + return factory.updateComputedPropertyName(node, expression); + } + function visitConstructorDeclaration(node) { + if (currentClassContainer) { + return transformConstructor(node, currentClassContainer); + } + return fallbackVisitor(node); } function visitMethodOrAccessorDeclaration(node) { ts.Debug.assert(!ts.hasDecorators(node)); @@ -95406,13 +96184,20 @@ var ts; } var functionName = getHoistedFunctionName(node); if (functionName) { - getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return ts.isModifier(m) && !ts.isStaticModifier(m); }), node.asteriskToken, functionName, - /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), - /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return ts.isModifier(m) && !ts.isStaticModifier(m) && !ts.isAccessorModifier(m); }), node.asteriskToken, functionName, + /* typeParameters */ undefined, ts.visitParameterList(node.parameters, visitor, context), + /* type */ undefined, ts.visitFunctionBody(node.body, visitor, context)))); } // remove method declaration from class return undefined; } + function setCurrentStaticPropertyDeclarationOrStaticBlockAnd(current, visitor, arg) { + var savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock; + currentStaticPropertyDeclarationOrStaticBlock = current; + var result = visitor(arg); + currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock; + return result; + } function getHoistedFunctionName(node) { ts.Debug.assert(ts.isPrivateIdentifier(node.name)); var info = accessPrivateIdentifier(node.name); @@ -95429,49 +96214,104 @@ var ts; } } } - function visitPropertyDeclaration(node) { - ts.Debug.assert(!ts.hasDecorators(node)); - if (ts.isPrivateIdentifier(node.name)) { - if (!shouldTransformPrivateElementsOrClassStaticBlocks) { - if (ts.isStatic(node)) { - // static fields are left as is - return ts.visitEachChild(node, visitor, context); - } - // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, - /*questionOrExclamationToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined); - } - // leave invalid code untransformed + function transformAutoAccessor(node) { + // transforms: + // accessor x = 1; + // into: + // #x = 1; + // get x() { return this.#x; } + // set x(value) { this.#x = value; } + ts.Debug.assertEachNode(node.modifiers, ts.isModifier); + var commentRange = ts.getCommentRange(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Since we're creating two declarations where there was previously one, cache + // the expression for any computed property names. + var name = node.name; + var getterName = name; + var setterName = name; + if (ts.isComputedPropertyName(name) && !ts.isSimpleInlineableExpression(name.expression)) { + var temp = factory.createTempVariable(hoistVariableDeclaration); + ts.setSourceMapRange(temp, name.expression); + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + var assignment = factory.createAssignment(temp, expression); + ts.setSourceMapRange(assignment, name.expression); + getterName = factory.updateComputedPropertyName(name, factory.inlineExpressions([assignment, temp])); + setterName = factory.updateComputedPropertyName(name, temp); + } + var backingField = ts.createAccessorPropertyBackingField(factory, node, node.modifiers, node.initializer); + ts.setOriginalNode(backingField, node); + ts.setEmitFlags(backingField, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(backingField, sourceMapRange); + var getter = ts.createAccessorPropertyGetRedirector(factory, node, node.modifiers, getterName); + ts.setOriginalNode(getter, node); + ts.setCommentRange(getter, commentRange); + ts.setSourceMapRange(getter, sourceMapRange); + var setter = ts.createAccessorPropertySetRedirector(factory, node, node.modifiers, setterName); + ts.setOriginalNode(setter, node); + ts.setEmitFlags(setter, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(setter, sourceMapRange); + return ts.visitArray([backingField, getter, setter], accessorFieldResultVisitor, ts.isClassElement); + } + function transformPrivateFieldInitializer(node) { + if (shouldTransformPrivateElementsOrClassStaticBlocks) { + // If we are transforming private elements into WeakMap/WeakSet, we should elide the node. var info = accessPrivateIdentifier(node.name); ts.Debug.assert(info, "Undeclared private name for property declaration."); - if (!info.isValid) { - return node; + // Leave invalid code untransformed; otherwise, elide the node as it is transformed elsewhere. + return info.isValid ? undefined : node; + } + if (shouldTransformInitializersUsingSet && !ts.isStatic(node)) { + // If we are transforming initializers using Set semantics we will elide the initializer as it will + // be moved to the constructor to preserve evaluation order next to public instance fields. We don't + // need to do this transformation for private static fields since public static fields can be + // transformed into `static {}` blocks. + return factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + return ts.visitEachChild(node, visitor, context); + } + function transformPublicFieldInitializer(node) { + if (shouldTransformInitializers) { + // Create a temporary variable to store a computed property name (if necessary). + // If it's not inlineable, then we emit an expression after the class which assigns + // the property name to the temporary variable. + var expr = getPropertyNameExpressionIfNeeded(node.name, /*shouldHoist*/ !!node.initializer || useDefineForClassFields); + if (expr) { + getPendingExpressions().push(expr); } - } - // Create a temporary variable to store a computed property name (if necessary). - // If it's not inlineable, then we emit an expression after the class which assigns - // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); - if (expr && !ts.isSimpleInlineableExpression(expr)) { - getPendingExpressions().push(expr); - } - if (ts.isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { - var initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); - if (initializerStatement) { - var staticBlock = factory.createClassStaticBlockDeclaration(factory.createBlock([initializerStatement])); - ts.setOriginalNode(staticBlock, node); - ts.setCommentRange(staticBlock, node); - // Set the comment range for the statement to an empty synthetic range - // and drop synthetic comments from the statement to avoid printing them twice. - ts.setCommentRange(initializerStatement, { pos: -1, end: -1 }); - ts.setSyntheticLeadingComments(initializerStatement, undefined); - ts.setSyntheticTrailingComments(initializerStatement, undefined); - return staticBlock; + if (ts.isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks) { + var initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); + if (initializerStatement) { + var staticBlock = factory.createClassStaticBlockDeclaration(factory.createBlock([initializerStatement])); + ts.setOriginalNode(staticBlock, node); + ts.setCommentRange(staticBlock, node); + // Set the comment range for the statement to an empty synthetic range + // and drop synthetic comments from the statement to avoid printing them twice. + ts.setCommentRange(initializerStatement, { pos: -1, end: -1 }); + ts.setSyntheticLeadingComments(initializerStatement, undefined); + ts.setSyntheticTrailingComments(initializerStatement, undefined); + return staticBlock; + } } + return undefined; } - return undefined; + return ts.visitEachChild(node, classElementVisitor, context); + } + function transformFieldInitializer(node) { + ts.Debug.assert(!ts.hasDecorators(node), "Decorators should already have been transformed and elided."); + return ts.isPrivateIdentifierClassElementDeclaration(node) ? + transformPrivateFieldInitializer(node) : + transformPublicFieldInitializer(node); + } + function visitPropertyDeclaration(node) { + // If this is an auto-accessor, we defer to `transformAutoAccessor`. That function + // will in turn call `transformFieldInitializer` as needed. + if (shouldTransformAutoAccessors && ts.isAutoAccessorPropertyDeclaration(node)) { + return transformAutoAccessor(node); + } + return transformFieldInitializer(node); } function createPrivateIdentifierAccess(info, receiver) { return createPrivateIdentifierAccessHelper(info, ts.visitNode(receiver, visitor, ts.isExpression)); @@ -95535,9 +96375,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) { - if (node.operator === 45 /* SyntaxKind.PlusPlusToken */ || node.operator === 46 /* SyntaxKind.MinusMinusToken */) { + if (node.operator === 45 /* SyntaxKind.PlusPlusToken */ || + node.operator === 46 /* SyntaxKind.MinusMinusToken */) { var operand = ts.skipParentheses(node.operand); - if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(operand)) { + if (shouldTransformPrivateElementsOrClassStaticBlocks && + ts.isPrivateIdentifierPropertyAccessExpression(operand)) { var info = void 0; if (info = accessPrivateIdentifier(operand.name)) { var receiver = ts.visitNode(operand.expression, visitor, ts.isExpression); @@ -95626,7 +96468,9 @@ var ts; return { readExpression: readExpression, initializeExpression: initializeExpression }; } function visitCallExpression(node) { - if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { + if (shouldTransformPrivateElementsOrClassStaticBlocks && + ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { + // obj.#x() // Transform call expressions of private names to properly bind the `this` parameter. var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; if (ts.isCallChain(node)) { @@ -95641,6 +96485,8 @@ var ts; ts.isSuperProperty(node.expression) && currentStaticPropertyDeclarationOrStaticBlock && (currentClassLexicalEnvironment === null || currentClassLexicalEnvironment === void 0 ? void 0 : currentClassLexicalEnvironment.classConstructor)) { + // super.x() + // super[x]() // converts `super.f(...)` into `Reflect.get(_baseTemp, "f", _classTemp).call(_classTemp, ...)` var invocation = factory.createFunctionCallCall(ts.visitNode(node.expression, visitor, ts.isExpression), currentClassLexicalEnvironment.classConstructor, ts.visitNodes(node.arguments, visitor, ts.isExpression)); ts.setOriginalNode(invocation, node); @@ -95650,7 +96496,8 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitTaggedTemplateExpression(node) { - if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { + if (shouldTransformPrivateElementsOrClassStaticBlocks && + ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access. var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"), @@ -95676,11 +96523,8 @@ var ts; classLexicalEnvironmentMap.set(ts.getOriginalNodeId(node), currentClassLexicalEnvironment); } startLexicalEnvironment(); - var savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock; - currentStaticPropertyDeclarationOrStaticBlock = node; - var statements = ts.visitNodes(node.body.statements, visitor, ts.isStatement); + var statements = setCurrentStaticPropertyDeclarationOrStaticBlockAnd(node, function (statements) { return ts.visitNodes(statements, visitor, ts.isStatement); }, node.body.statements); statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); - currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock; var iife = factory.createImmediatelyInvokedArrowFunction(statements); ts.setOriginalNode(iife, node); ts.setTextRange(iife, node); @@ -95690,9 +96534,12 @@ var ts; } function visitBinaryExpression(node, valueIsDiscarded) { if (ts.isDestructuringAssignment(node)) { + // ({ x: obj.#x } = ...) + // ({ x: super.x } = ...) + // ({ x: super[x] } = ...) var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; - node = factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorDestructuringTarget), node.operatorToken, ts.visitNode(node.right, visitor)); + node = factory.updateBinaryExpression(node, ts.visitNode(node.left, assignmentTargetVisitor), node.operatorToken, ts.visitNode(node.right, visitor)); var expr = ts.some(pendingExpressions) ? factory.inlineExpressions(ts.compact(__spreadArray(__spreadArray([], pendingExpressions, true), [node], false))) : node; @@ -95700,7 +96547,9 @@ var ts; return expr; } if (ts.isAssignmentExpression(node)) { - if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) { + if (shouldTransformPrivateElementsOrClassStaticBlocks && + ts.isPrivateIdentifierPropertyAccessExpression(node.left)) { + // obj.#x = ... var info = accessPrivateIdentifier(node.left.name); if (info) { return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node), node); @@ -95710,6 +96559,10 @@ var ts; ts.isSuperProperty(node.left) && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { + // super.x = ... + // super[x] = ... + // super.x += ... + // super.x -= ... var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; if (facts & 1 /* ClassFacts.ClassWasDecorated */) { return factory.updateBinaryExpression(node, visitInvalidSuperProperty(node.left), node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression)); @@ -95753,8 +96606,10 @@ var ts; } } } - if (node.operatorToken.kind === 101 /* SyntaxKind.InKeyword */ && ts.isPrivateIdentifier(node.left)) { - return visitPrivateIdentifierInInExpression(node); + if (shouldTransformPrivateElementsOrClassStaticBlocks && + isPrivateIdentifierInExpression(node)) { + // #x in obj + return transformPrivateIdentifierInInExpression(node); } return ts.visitEachChild(node, visitor, context); } @@ -95779,36 +96634,6 @@ var ts; ts.Debug.assertNever(info, "Unknown private element type"); } } - /** - * Set up the environment for a class. - */ - function visitClassLike(node) { - if (!ts.forEach(node.members, doesClassElementNeedTransform)) { - return ts.visitEachChild(node, visitor, context); - } - var savedPendingExpressions = pendingExpressions; - pendingExpressions = undefined; - startClassLexicalEnvironment(); - if (shouldTransformPrivateElementsOrClassStaticBlocks) { - var name = ts.getNameOfDeclaration(node); - if (name && ts.isIdentifier(name)) { - getPrivateIdentifierEnvironment().className = ts.idText(name); - } - var privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); - if (ts.some(privateInstanceMethodsAndAccessors)) { - getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass("instances", privateInstanceMethodsAndAccessors[0].name); - } - } - var result = ts.isClassDeclaration(node) ? - visitClassDeclaration(node) : - visitClassExpression(node); - endClassLexicalEnvironment(); - pendingExpressions = savedPendingExpressions; - return result; - } - function doesClassElementNeedTransform(node) { - return ts.isPropertyDeclaration(node) || ts.isClassStaticBlockDeclaration(node) || (shouldTransformPrivateElementsOrClassStaticBlocks && node.name && ts.isPrivateIdentifier(node.name)); - } function getPrivateInstanceMethodsAndAccessors(node) { return ts.filter(node.members, ts.isNonStaticMethodOrAccessorWithPrivateName); } @@ -95822,7 +96647,7 @@ var ts; var member = _a[_i]; if (!ts.isStatic(member)) continue; - if (member.name && ts.isPrivateIdentifier(member.name) && shouldTransformPrivateElementsOrClassStaticBlocks) { + if (member.name && (ts.isPrivateIdentifier(member.name) || ts.isAutoAccessorPropertyDeclaration(member)) && shouldTransformPrivateElementsOrClassStaticBlocks) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } if (ts.isPropertyDeclaration(member) || ts.isClassStaticBlockDeclaration(member)) { @@ -95841,7 +96666,7 @@ var ts; } return facts; } - function visitExpressionWithTypeArguments(node) { + function visitExpressionWithTypeArgumentsInHeritageClause(node) { var facts = (currentClassLexicalEnvironment === null || currentClassLexicalEnvironment === void 0 ? void 0 : currentClassLexicalEnvironment.facts) || 0 /* ClassFacts.None */; if (facts & 4 /* ClassFacts.NeedsClassSuperReference */) { var temp = factory.createTempVariable(hoistVariableDeclaration, /*reserveInNestedScopes*/ true); @@ -95851,7 +96676,22 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function visitClassDeclaration(node) { + function visitInNewClassLexicalEnvironment(node, visitor) { + var savedCurrentClassContainer = currentClassContainer; + var savedPendingExpressions = pendingExpressions; + currentClassContainer = node; + pendingExpressions = undefined; + startClassLexicalEnvironment(); + if (shouldTransformPrivateElementsOrClassStaticBlocks) { + var name = ts.getNameOfDeclaration(node); + if (name && ts.isIdentifier(name)) { + getPrivateIdentifierEnvironment().className = name; + } + var privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + if (ts.some(privateInstanceMethodsAndAccessors)) { + getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass("instances", privateInstanceMethodsAndAccessors[0].name); + } + } var facts = getClassFacts(node); if (facts) { getClassLexicalEnvironment().facts = facts; @@ -95859,6 +96699,16 @@ var ts; if (facts & 8 /* ClassFacts.NeedsSubstitutionForThisInClassStaticField */) { enableSubstitutionForClassStaticThisOrSuperReference(); } + var result = visitor(node, facts); + endClassLexicalEnvironment(); + currentClassContainer = savedCurrentClassContainer; + pendingExpressions = savedPendingExpressions; + return result; + } + function visitClassDeclaration(node) { + return visitInNewClassLexicalEnvironment(node, visitClassDeclarationInNewClassLexicalEnvironment); + } + function visitClassDeclarationInNewClassLexicalEnvironment(node, facts) { // If a class has private static fields, or a static field has a `this` or `super` reference, // then we need to allocate a temp variable to hold on to that reference. var pendingClassReferenceAssignment; @@ -95867,12 +96717,16 @@ var ts; getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp); pendingClassReferenceAssignment = factory.createAssignment(temp, factory.getInternalName(node)); } - var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); - var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* SyntaxKind.NullKeyword */); - var statements = [ - factory.updateClassDeclaration(node, node.modifiers, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) - ]; + var modifiers = ts.visitNodes(node.modifiers, visitor, ts.isModifierLike); + var heritageClauses = ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause); + var _a = transformClassMembers(node), members = _a.members, prologue = _a.prologue; + var classDecl = factory.updateClassDeclaration(node, modifiers, node.name, + /*typeParameters*/ undefined, heritageClauses, members); + var statements = []; + if (prologue) { + statements.push(factory.createExpressionStatement(prologue)); + } + statements.push(classDecl); if (pendingClassReferenceAssignment) { getPendingExpressions().unshift(pendingClassReferenceAssignment); } @@ -95880,25 +96734,23 @@ var ts; if (ts.some(pendingExpressions)) { statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))); } - // Emit static property assignment. Because classDeclaration is lexically evaluated, - // it is safe to emit static property assignment after classDeclaration - // From ES6 specification: - // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using - // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - var staticProperties = ts.getStaticPropertiesAndClassStaticBlock(node); - if (ts.some(staticProperties)) { - addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory.getInternalName(node)); + if (shouldTransformInitializersUsingSet || shouldTransformPrivateElementsOrClassStaticBlocks) { + // Emit static property assignment. Because classDeclaration is lexically evaluated, + // it is safe to emit static property assignment after classDeclaration + // From ES6 specification: + // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using + // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + var staticProperties = ts.getStaticPropertiesAndClassStaticBlock(node); + if (ts.some(staticProperties)) { + addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory.getInternalName(node)); + } } return statements; } function visitClassExpression(node) { - var facts = getClassFacts(node); - if (facts) { - getClassLexicalEnvironment().facts = facts; - } - if (facts & 8 /* ClassFacts.NeedsSubstitutionForThisInClassStaticField */) { - enableSubstitutionForClassStaticThisOrSuperReference(); - } + return visitInNewClassLexicalEnvironment(node, visitClassExpressionInNewClassLexicalEnvironment); + } + function visitClassExpressionInNewClassLexicalEnvironment(node, facts) { // If this class expression is a transformation of a decorated class declaration, // then we want to output the pendingExpressions as statements, not as inlined // expressions with the class statement. @@ -95908,8 +96760,6 @@ var ts; // these statements after the class expression variable statement. var isDecoratedClassDeclaration = !!(facts & 1 /* ClassFacts.ClassWasDecorated */); var staticPropertiesOrClassStaticBlocks = ts.getStaticPropertiesAndClassStaticBlock(node); - var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); - var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* SyntaxKind.NullKeyword */); var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */; var temp; function createClassTempVar() { @@ -95922,9 +96772,23 @@ var ts; temp = createClassTempVar(); getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp); } - var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); - var hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || ts.isPrivateIdentifier(p.name); }); + var modifiers = ts.visitNodes(node.modifiers, visitor, ts.isModifierLike); + var heritageClauses = ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause); + var _a = transformClassMembers(node), members = _a.members, prologue = _a.prologue; + var classExpression = factory.updateClassExpression(node, modifiers, node.name, + /*typeParameters*/ undefined, heritageClauses, members); + var expressions = []; + if (prologue) { + expressions.push(prologue); + } + // Static initializers are transformed to `static {}` blocks when `useDefineForClassFields: false` + // and not also transforming static blocks. + var hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && + ts.some(staticPropertiesOrClassStaticBlocks, function (node) { + return ts.isClassStaticBlockDeclaration(node) || + ts.isPrivateIdentifierClassElementDeclaration(node) || + shouldTransformInitializers && ts.isInitializedProperty(node); + }); if (hasTransformableStatics || ts.some(pendingExpressions)) { if (isDecoratedClassDeclaration) { ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); @@ -95936,12 +96800,16 @@ var ts; addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, factory.getInternalName(node)); } if (temp) { - return factory.inlineExpressions([factory.createAssignment(temp, classExpression), temp]); + expressions.push(ts.startOnNewLine(factory.createAssignment(temp, classExpression)), ts.startOnNewLine(temp)); + } + else { + expressions.push(classExpression); + if (prologue) { + ts.startOnNewLine(classExpression); + } } - return classExpression; } else { - var expressions = []; temp || (temp = createClassTempVar()); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -95958,45 +96826,87 @@ var ts; ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); ts.addRange(expressions, generateInitializedPropertyExpressionsOrClassStaticBlock(staticPropertiesOrClassStaticBlocks, temp)); expressions.push(ts.startOnNewLine(temp)); - return factory.inlineExpressions(expressions); } } - return classExpression; + else { + expressions.push(classExpression); + if (prologue) { + ts.startOnNewLine(classExpression); + } + } + return factory.inlineExpressions(expressions); } function visitClassStaticBlockDeclaration(node) { if (!shouldTransformPrivateElementsOrClassStaticBlocks) { - return ts.visitEachChild(node, classElementVisitor, context); + return ts.visitEachChild(node, visitor, context); } // ClassStaticBlockDeclaration for classes are transformed in `visitClassDeclaration` or `visitClassExpression`. return undefined; } - function transformClassMembers(node, isDerivedClass) { - var members = []; + function transformClassMembers(node) { + // Declare private names if (shouldTransformPrivateElementsOrClassStaticBlocks) { - // Declare private names. for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (ts.isPrivateIdentifierClassElementDeclaration(member)) { - addPrivateIdentifierToEnvironment(member); + addPrivateIdentifierToEnvironment(member, member.name, addPrivateIdentifierClassElementToEnvironment); } } if (ts.some(getPrivateInstanceMethodsAndAccessors(node))) { createBrandCheckWeakSetForPrivateMethods(); } + if (shouldTransformAutoAccessors) { + for (var _b = 0, _c = node.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (ts.isAutoAccessorPropertyDeclaration(member)) { + var storageName = factory.getGeneratedPrivateNameForNode(member.name, /*prefix*/ undefined, "_accessor_storage"); + addPrivateIdentifierToEnvironment(member, storageName, addPrivateIdentifierPropertyDeclarationToEnvironment); + } + } + } } - var constructor = transformConstructor(node, isDerivedClass); - var visitedMembers = ts.visitNodes(node.members, classElementVisitor, ts.isClassElement); - if (constructor) { - members.push(constructor); + var members = ts.visitNodes(node.members, classElementVisitor, ts.isClassElement); + // Create a synthetic constructor if necessary + var syntheticConstructor; + if (!ts.some(members, ts.isConstructorDeclaration)) { + syntheticConstructor = transformConstructor(/*constructor*/ undefined, node); } + var prologue; + // If there are pending expressions create a class static block in which to evaluate them, but only if + // class static blocks are not also being transformed. This block will be injected at the top of the class + // to ensure that expressions from computed property names are evaluated before any other static + // initializers. + var syntheticStaticBlock; if (!shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(pendingExpressions)) { - members.push(factory.createClassStaticBlockDeclaration(factory.createBlock([ - factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)) - ]))); + var statement = factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)); + if (statement.transformFlags & 134234112 /* TransformFlags.ContainsLexicalThisOrSuper */) { + // If there are `this` or `super` references from computed property names, shift the expression + // into an arrow function to be evaluated in the outer scope so that `this` and `super` are + // properly captured. + var temp = factory.createTempVariable(hoistVariableDeclaration); + var arrow = factory.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, factory.createBlock([statement])); + prologue = factory.createAssignment(temp, arrow); + statement = factory.createExpressionStatement(factory.createCallExpression(temp, /*typeArguments*/ undefined, [])); + } + var block = factory.createBlock([statement]); + syntheticStaticBlock = factory.createClassStaticBlockDeclaration(block); pendingExpressions = undefined; } - ts.addRange(members, visitedMembers); - return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); + // If we created a synthetic constructor or class static block, add them to the visited members + // and return a new array. + if (syntheticConstructor || syntheticStaticBlock) { + var membersArray = void 0; + membersArray = ts.append(membersArray, syntheticConstructor); + membersArray = ts.append(membersArray, syntheticStaticBlock); + membersArray = ts.addRange(membersArray, members); + members = ts.setTextRange(factory.createNodeArray(membersArray), /*location*/ node.members); + } + return { members: members, prologue: prologue }; } function createBrandCheckWeakSetForPrivateMethods() { var weakSetName = getPrivateIdentifierEnvironment().weakSetName; @@ -96005,35 +96915,38 @@ var ts; /*typeArguments*/ undefined, []))); } function isClassElementThatRequiresConstructorStatement(member) { - if (ts.isStatic(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* ModifierFlags.Abstract */)) { + if (ts.isStatic(member) || ts.hasAbstractModifier(ts.getOriginalNode(member))) { return false; } - if (useDefineForClassFields) { - // If we are using define semantics and targeting ESNext or higher, - // then we don't need to transform any class properties. - return languageVersion < 9 /* ScriptTarget.ES2022 */; - } - return ts.isInitializedProperty(member) || shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierClassElementDeclaration(member); + return shouldTransformInitializersUsingDefine && ts.isPropertyDeclaration(member) || + shouldTransformInitializersUsingSet && ts.isInitializedProperty(member) || + shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierClassElementDeclaration(member) || + shouldTransformPrivateElementsOrClassStaticBlocks && shouldTransformAutoAccessors && ts.isAutoAccessorPropertyDeclaration(member); } - function transformConstructor(node, isDerivedClass) { - var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration); - var elements = node.members.filter(isClassElementThatRequiresConstructorStatement); - if (!ts.some(elements)) { + function transformConstructor(constructor, container) { + constructor = ts.visitNode(constructor, visitor, ts.isConstructorDeclaration); + if (!ts.some(container.members, isClassElementThatRequiresConstructorStatement)) { return constructor; } + var extendsClauseElement = ts.getEffectiveBaseTypeNode(container); + var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* SyntaxKind.NullKeyword */); var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context); - var body = transformConstructorBody(node, constructor, isDerivedClass); + var body = transformConstructorBody(container, constructor, isDerivedClass); if (!body) { - return undefined; + return constructor; + } + if (constructor) { + ts.Debug.assert(parameters); + return factory.updateConstructorDeclaration(constructor, /*modifiers*/ undefined, parameters, body); } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration( - /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); + /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || container), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var _a; + var _a, _b; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { - properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); + properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name) || ts.hasAccessorModifier(property); }); } var privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); var needsConstructorBody = ts.some(properties) || ts.some(privateMethodsAndAccessors); @@ -96085,8 +96998,8 @@ var ts; statements = statements.filter(function (statement) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(statement), constructor); }); } else { - for (var _i = 0, _b = constructor.body.statements; _i < _b.length; _i++) { - var statement = _b[_i]; + for (var _i = 0, _c = constructor.body.statements; _i < _c.length; _i++) { + var statement = _c[_i]; if (ts.isParameterPropertyDeclaration(ts.getOriginalNode(statement), constructor)) { parameterPropertyDeclarationCount++; } @@ -96118,9 +97031,14 @@ var ts; ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitBodyStatement, ts.isStatement, indexOfFirstStatementAfterSuperAndPrologue)); } statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + if (statements.length === 0 && !constructor) { + return undefined; + } + var multiLine = (constructor === null || constructor === void 0 ? void 0 : constructor.body) && constructor.body.statements.length >= statements.length ? + (_b = constructor.body.multiLine) !== null && _b !== void 0 ? _b : statements.length > 0 : + statements.length > 0; return ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), - /*location*/ constructor ? constructor.body.statements : node.members), - /*multiLine*/ true), + /*location*/ constructor ? constructor.body.statements : node.members), multiLine), /*location*/ constructor ? constructor.body : undefined); function visitBodyStatement(statement) { if (useDefineForClassFields && ts.isParameterPropertyDeclaration(ts.getOriginalNode(statement), constructor)) { @@ -96156,9 +97074,10 @@ var ts; return undefined; } var statement = factory.createExpressionStatement(expression); + ts.setOriginalNode(statement, property); + ts.addEmitFlags(statement, ts.getEmitFlags(property) & 1536 /* EmitFlags.NoComments */); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); - ts.setOriginalNode(statement, property); // `setOriginalNode` *copies* the `emitNode` from `property`, so now both // `statement` and `expression` have a copy of the synthesized comments. // Drop the comments from expression to avoid printing them twice. @@ -96181,9 +97100,10 @@ var ts; continue; } ts.startOnNewLine(expression); + ts.setOriginalNode(expression, property); + ts.addEmitFlags(expression, ts.getEmitFlags(property) & 1536 /* EmitFlags.NoComments */); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); - ts.setOriginalNode(expression, property); expressions.push(expression); } return expressions; @@ -96210,9 +97130,11 @@ var ts; var _a; // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) var emitAssignment = !useDefineForClassFields; - var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) - ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) - : property.name; + var propertyName = ts.hasAccessorModifier(property) ? + factory.getGeneratedPrivateNameForNode(property.name) : + ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? + factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : + property.name; if (ts.hasStaticModifier(property)) { currentStaticPropertyDeclarationOrStaticBlock = property; } @@ -96239,7 +97161,7 @@ var ts; return undefined; } var propertyOriginalNode = ts.getOriginalNode(property); - if (ts.hasSyntacticModifier(propertyOriginalNode, 128 /* ModifierFlags.Abstract */)) { + if (ts.hasSyntacticModifier(propertyOriginalNode, 256 /* ModifierFlags.Abstract */)) { return undefined; } var initializer = property.initializer || emitAssignment ? (_a = ts.visitNode(property.initializer, visitor, ts.isExpression)) !== null && _a !== void 0 ? _a : factory.createVoidZero() @@ -96273,17 +97195,17 @@ var ts; // substitute `this` in a static field initializer context.enableSubstitution(108 /* SyntaxKind.ThisKeyword */); // these push a new lexical environment that is not the class lexical environment - context.enableEmitNotification(256 /* SyntaxKind.FunctionDeclaration */); - context.enableEmitNotification(213 /* SyntaxKind.FunctionExpression */); - context.enableEmitNotification(171 /* SyntaxKind.Constructor */); + context.enableEmitNotification(259 /* SyntaxKind.FunctionDeclaration */); + context.enableEmitNotification(215 /* SyntaxKind.FunctionExpression */); + context.enableEmitNotification(173 /* SyntaxKind.Constructor */); // these push a new lexical environment that is not the class lexical environment, except // when they have a computed property name - context.enableEmitNotification(172 /* SyntaxKind.GetAccessor */); - context.enableEmitNotification(173 /* SyntaxKind.SetAccessor */); - context.enableEmitNotification(169 /* SyntaxKind.MethodDeclaration */); - context.enableEmitNotification(167 /* SyntaxKind.PropertyDeclaration */); + context.enableEmitNotification(174 /* SyntaxKind.GetAccessor */); + context.enableEmitNotification(175 /* SyntaxKind.SetAccessor */); + context.enableEmitNotification(171 /* SyntaxKind.MethodDeclaration */); + context.enableEmitNotification(169 /* SyntaxKind.PropertyDeclaration */); // class lexical environments are restored when entering a computed property name - context.enableEmitNotification(162 /* SyntaxKind.ComputedPropertyName */); + context.enableEmitNotification(164 /* SyntaxKind.ComputedPropertyName */); } } /** @@ -96322,13 +97244,13 @@ var ts; } } switch (node.kind) { - case 213 /* SyntaxKind.FunctionExpression */: + case 215 /* SyntaxKind.FunctionExpression */: if (ts.isArrowFunction(original) || ts.getEmitFlags(node) & 262144 /* EmitFlags.AsyncFunctionBody */) { break; } // falls through - case 256 /* SyntaxKind.FunctionDeclaration */: - case 171 /* SyntaxKind.Constructor */: { + case 259 /* SyntaxKind.FunctionDeclaration */: + case 173 /* SyntaxKind.Constructor */: { var savedClassLexicalEnvironment = currentClassLexicalEnvironment; var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; currentClassLexicalEnvironment = undefined; @@ -96338,10 +97260,10 @@ var ts; currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment; return; } - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 167 /* SyntaxKind.PropertyDeclaration */: { + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: { var savedClassLexicalEnvironment = currentClassLexicalEnvironment; var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; currentComputedPropertyNameClassLexicalEnvironment = currentClassLexicalEnvironment; @@ -96351,7 +97273,7 @@ var ts; currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment; return; } - case 162 /* SyntaxKind.ComputedPropertyName */: { + case 164 /* SyntaxKind.ComputedPropertyName */: { var savedClassLexicalEnvironment = currentClassLexicalEnvironment; var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; currentClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; @@ -96465,149 +97387,138 @@ var ts; function getPrivateIdentifierEnvironment() { var lex = getClassLexicalEnvironment(); lex.privateIdentifierEnvironment || (lex.privateIdentifierEnvironment = { - className: "", - identifiers: new ts.Map() + className: undefined, + weakSetName: undefined, + identifiers: undefined, + generatedIdentifiers: undefined, }); return lex.privateIdentifierEnvironment; } function getPendingExpressions() { - return pendingExpressions || (pendingExpressions = []); + return pendingExpressions !== null && pendingExpressions !== void 0 ? pendingExpressions : (pendingExpressions = []); } - function addPrivateIdentifierToEnvironment(node) { - var _a; - var text = ts.getTextOfPropertyName(node.name); - var lex = getClassLexicalEnvironment(); - var classConstructor = lex.classConstructor; - var privateEnv = getPrivateIdentifierEnvironment(); - var weakSetName = privateEnv.weakSetName; - var assignmentExpressions = []; - var privateName = node.name.escapedText; - var previousInfo = privateEnv.identifiers.get(privateName); - var isValid = !isReservedPrivateName(node.name) && previousInfo === undefined; - if (ts.hasStaticModifier(node)) { - ts.Debug.assert(classConstructor, "weakSetName should be set in private identifier environment"); - if (ts.isPropertyDeclaration(node)) { - var variableName = createHoistedVariableForPrivateName(text, node); - privateEnv.identifiers.set(privateName, { - kind: "f" /* PrivateIdentifierKind.Field */, - variableName: variableName, - brandCheckIdentifier: classConstructor, - isStatic: true, - isValid: isValid, - }); - } - else if (ts.isMethodDeclaration(node)) { - var functionName = createHoistedVariableForPrivateName(text, node); - privateEnv.identifiers.set(privateName, { - kind: "m" /* PrivateIdentifierKind.Method */, - methodName: functionName, - brandCheckIdentifier: classConstructor, - isStatic: true, - isValid: isValid, - }); - } - else if (ts.isGetAccessorDeclaration(node)) { - var getterName = createHoistedVariableForPrivateName(text + "_get", node); - if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && previousInfo.isStatic && !previousInfo.getterName) { - previousInfo.getterName = getterName; - } - else { - privateEnv.identifiers.set(privateName, { - kind: "a" /* PrivateIdentifierKind.Accessor */, - getterName: getterName, - setterName: undefined, - brandCheckIdentifier: classConstructor, - isStatic: true, - isValid: isValid, - }); - } - } - else if (ts.isSetAccessorDeclaration(node)) { - var setterName = createHoistedVariableForPrivateName(text + "_set", node); - if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && previousInfo.isStatic && !previousInfo.setterName) { - previousInfo.setterName = setterName; - } - else { - privateEnv.identifiers.set(privateName, { - kind: "a" /* PrivateIdentifierKind.Accessor */, - getterName: undefined, - setterName: setterName, - brandCheckIdentifier: classConstructor, - isStatic: true, - isValid: isValid, - }); - } - } - else { - ts.Debug.assertNever(node, "Unknown class element type."); - } + function addPrivateIdentifierClassElementToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo) { + if (ts.isAutoAccessorPropertyDeclaration(node)) { + addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo); } else if (ts.isPropertyDeclaration(node)) { - var weakMapName = createHoistedVariableForPrivateName(text, node); - privateEnv.identifiers.set(privateName, { - kind: "f" /* PrivateIdentifierKind.Field */, - brandCheckIdentifier: weakMapName, - isStatic: false, - variableName: undefined, - isValid: isValid, - }); - assignmentExpressions.push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), - /*typeArguments*/ undefined, []))); + addPrivateIdentifierPropertyDeclarationToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo); } else if (ts.isMethodDeclaration(node)) { - ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); - privateEnv.identifiers.set(privateName, { - kind: "m" /* PrivateIdentifierKind.Method */, - methodName: createHoistedVariableForPrivateName(text, node), - brandCheckIdentifier: weakSetName, - isStatic: false, + addPrivateIdentifierMethodDeclarationToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo); + } + else if (ts.isGetAccessorDeclaration(node)) { + addPrivateIdentifierGetAccessorDeclarationToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo); + } + else if (ts.isSetAccessorDeclaration(node)) { + addPrivateIdentifierSetAccessorDeclarationToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo); + } + } + function addPrivateIdentifierPropertyDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic, isValid, _previousInfo) { + if (isStatic) { + ts.Debug.assert(lex.classConstructor, "classConstructor should be set in private identifier environment"); + var variableName = createHoistedVariableForPrivateName(name); + setPrivateIdentifier(privateEnv, name, { + kind: "f" /* PrivateIdentifierKind.Field */, + brandCheckIdentifier: lex.classConstructor, + variableName: variableName, + isStatic: true, isValid: isValid, }); } - else if (ts.isAccessor(node)) { - ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); - if (ts.isGetAccessor(node)) { - var getterName = createHoistedVariableForPrivateName(text + "_get", node); - if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && !previousInfo.isStatic && !previousInfo.getterName) { - previousInfo.getterName = getterName; - } - else { - privateEnv.identifiers.set(privateName, { - kind: "a" /* PrivateIdentifierKind.Accessor */, - getterName: getterName, - setterName: undefined, - brandCheckIdentifier: weakSetName, - isStatic: false, - isValid: isValid, - }); - } - } - else { - var setterName = createHoistedVariableForPrivateName(text + "_set", node); - if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && !previousInfo.isStatic && !previousInfo.setterName) { - previousInfo.setterName = setterName; - } - else { - privateEnv.identifiers.set(privateName, { - kind: "a" /* PrivateIdentifierKind.Accessor */, - getterName: undefined, - setterName: setterName, - brandCheckIdentifier: weakSetName, - isStatic: false, - isValid: isValid, - }); - } - } + else { + var weakMapName = createHoistedVariableForPrivateName(name); + setPrivateIdentifier(privateEnv, name, { + kind: "f" /* PrivateIdentifierKind.Field */, + brandCheckIdentifier: weakMapName, + variableName: undefined, + isStatic: false, + isValid: isValid, + }); + getPendingExpressions().push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), + /*typeArguments*/ undefined, []))); + } + } + function addPrivateIdentifierMethodDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic, isValid, _previousInfo) { + var methodName = createHoistedVariableForPrivateName(name); + var brandCheckIdentifier = isStatic ? + ts.Debug.checkDefined(lex.classConstructor, "classConstructor should be set in private identifier environment") : + ts.Debug.checkDefined(privateEnv.weakSetName, "weakSetName should be set in private identifier environment"); + setPrivateIdentifier(privateEnv, name, { + kind: "m" /* PrivateIdentifierKind.Method */, + methodName: methodName, + brandCheckIdentifier: brandCheckIdentifier, + isStatic: isStatic, + isValid: isValid, + }); + } + function addPrivateIdentifierGetAccessorDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic, isValid, previousInfo) { + var getterName = createHoistedVariableForPrivateName(name, "_get"); + var brandCheckIdentifier = isStatic ? + ts.Debug.checkDefined(lex.classConstructor, "classConstructor should be set in private identifier environment") : + ts.Debug.checkDefined(privateEnv.weakSetName, "weakSetName should be set in private identifier environment"); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && previousInfo.isStatic === isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; } else { - ts.Debug.assertNever(node, "Unknown class element type."); + setPrivateIdentifier(privateEnv, name, { + kind: "a" /* PrivateIdentifierKind.Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: brandCheckIdentifier, + isStatic: isStatic, + isValid: isValid, + }); } - (_a = getPendingExpressions()).push.apply(_a, assignmentExpressions); } - function createHoistedVariableForClass(name, node) { + function addPrivateIdentifierSetAccessorDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic, isValid, previousInfo) { + var setterName = createHoistedVariableForPrivateName(name, "_set"); + var brandCheckIdentifier = isStatic ? + ts.Debug.checkDefined(lex.classConstructor, "classConstructor should be set in private identifier environment") : + ts.Debug.checkDefined(privateEnv.weakSetName, "weakSetName should be set in private identifier environment"); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && previousInfo.isStatic === isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + setPrivateIdentifier(privateEnv, name, { + kind: "a" /* PrivateIdentifierKind.Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: brandCheckIdentifier, + isStatic: isStatic, + isValid: isValid, + }); + } + } + function addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic, isValid, _previousInfo) { + var getterName = createHoistedVariableForPrivateName(name, "_get"); + var setterName = createHoistedVariableForPrivateName(name, "_set"); + var brandCheckIdentifier = isStatic ? + ts.Debug.checkDefined(lex.classConstructor, "classConstructor should be set in private identifier environment") : + ts.Debug.checkDefined(privateEnv.weakSetName, "weakSetName should be set in private identifier environment"); + setPrivateIdentifier(privateEnv, name, { + kind: "a" /* PrivateIdentifierKind.Accessor */, + getterName: getterName, + setterName: setterName, + brandCheckIdentifier: brandCheckIdentifier, + isStatic: isStatic, + isValid: isValid, + }); + } + function addPrivateIdentifierToEnvironment(node, name, addDeclaration) { + var lex = getClassLexicalEnvironment(); + var privateEnv = getPrivateIdentifierEnvironment(); + var previousInfo = getPrivateIdentifier(privateEnv, name); + var isStatic = ts.hasStaticModifier(node); + var isValid = !isReservedPrivateName(name) && previousInfo === undefined; + addDeclaration(node, name, lex, privateEnv, isStatic, isValid, previousInfo); + } + function createHoistedVariableForClass(name, node, suffix) { var className = getPrivateIdentifierEnvironment().className; - var prefix = className ? "_".concat(className) : ""; - var identifier = factory.createUniqueName("".concat(prefix, "_").concat(name), 16 /* GeneratedIdentifierFlags.Optimistic */); + var prefix = className ? { prefix: "_", node: className, suffix: "_" } : "_"; + var identifier = typeof name === "object" ? factory.getGeneratedNameForNode(name, 16 /* GeneratedIdentifierFlags.Optimistic */ | 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */, prefix, suffix) : + typeof name === "string" ? factory.createUniqueName(name, 16 /* GeneratedIdentifierFlags.Optimistic */, prefix, suffix) : + factory.createTempVariable(/*recordTempVariable*/ undefined, /*reserveInNestedScopes*/ true, prefix, suffix); if (resolver.getNodeCheckFlags(node) & 524288 /* NodeCheckFlags.BlockScopedBindingInLoop */) { addBlockScopedVariable(identifier); } @@ -96616,13 +97527,33 @@ var ts; } return identifier; } - function createHoistedVariableForPrivateName(privateName, node) { - return createHoistedVariableForClass(privateName.substring(1), node.name); - } - function accessPrivateIdentifier(name) { + function createHoistedVariableForPrivateName(name, suffix) { var _a; + var text = ts.tryGetTextOfPropertyName(name); + return createHoistedVariableForClass((_a = text === null || text === void 0 ? void 0 : text.substring(1)) !== null && _a !== void 0 ? _a : name, name, suffix); + } + /** + * Access an already defined {@link PrivateIdentifier} in the current {@link PrivateIdentifierEnvironment}. + * + * @seealso {@link addPrivateIdentifierToEnvironment} + */ + function accessPrivateIdentifier(name) { + if (ts.isGeneratedPrivateIdentifier(name)) { + return accessGeneratedPrivateIdentifier(name); + } + else { + return accessPrivateIdentifierByText(name.escapedText); + } + } + function accessPrivateIdentifierByText(text) { + return accessPrivateIdentifierWorker(getPrivateIdentifierInfo, text); + } + function accessGeneratedPrivateIdentifier(name) { + return accessPrivateIdentifierWorker(getGeneratedPrivateIdentifierInfo, ts.getNodeForGeneratedName(name)); + } + function accessPrivateIdentifierWorker(getPrivateIdentifierInfo, privateIdentifierKey) { if (currentClassLexicalEnvironment === null || currentClassLexicalEnvironment === void 0 ? void 0 : currentClassLexicalEnvironment.privateIdentifierEnvironment) { - var info = currentClassLexicalEnvironment.privateIdentifierEnvironment.identifiers.get(name.escapedText); + var info = getPrivateIdentifierInfo(currentClassLexicalEnvironment.privateIdentifierEnvironment, privateIdentifierKey); if (info) { return info; } @@ -96632,9 +97563,11 @@ var ts; if (!env) { continue; } - var info = (_a = env.privateIdentifierEnvironment) === null || _a === void 0 ? void 0 : _a.identifiers.get(name.escapedText); - if (info) { - return info; + if (env.privateIdentifierEnvironment) { + var info = getPrivateIdentifierInfo(env.privateIdentifierEnvironment, privateIdentifierKey); + if (info) { + return info; + } } } return undefined; @@ -96691,7 +97624,7 @@ var ts; } } } - return ts.visitNode(node, visitorDestructuringTarget); + return ts.visitNode(node, assignmentTargetVisitor); } function visitObjectAssignmentTarget(node) { if (ts.isObjectBindingOrAssignmentElement(node) && !ts.isShorthandPropertyAssignment(node)) { @@ -96724,10 +97657,10 @@ var ts; var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor, ts.isPropertyName), wrapped ? initializer ? factory.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped : - ts.visitNode(node.initializer, visitorDestructuringTarget, ts.isExpression)); + ts.visitNode(node.initializer, assignmentTargetVisitor, ts.isExpression)); } if (ts.isSpreadAssignment(node)) { - return factory.updateSpreadAssignment(node, wrapped || ts.visitNode(node.expression, visitorDestructuringTarget, ts.isExpression)); + return factory.updateSpreadAssignment(node, wrapped || ts.visitNode(node.expression, assignmentTargetVisitor, ts.isExpression)); } ts.Debug.assert(wrapped === undefined, "Should not have generated a wrapped target"); } @@ -96773,7 +97706,31 @@ var ts; /*typeArguments*/ undefined, [receiver]); } function isReservedPrivateName(node) { - return node.escapedText === "#constructor"; + return !ts.isGeneratedPrivateIdentifier(node) && node.escapedText === "#constructor"; + } + function getPrivateIdentifier(privateEnv, name) { + return ts.isGeneratedPrivateIdentifier(name) ? + getGeneratedPrivateIdentifierInfo(privateEnv, ts.getNodeForGeneratedName(name)) : + getPrivateIdentifierInfo(privateEnv, name.escapedText); + } + function setPrivateIdentifier(privateEnv, name, info) { + var _a, _b; + if (ts.isGeneratedPrivateIdentifier(name)) { + (_a = privateEnv.generatedIdentifiers) !== null && _a !== void 0 ? _a : (privateEnv.generatedIdentifiers = new ts.Map()); + privateEnv.generatedIdentifiers.set(ts.getNodeForGeneratedName(name), info); + } + else { + (_b = privateEnv.identifiers) !== null && _b !== void 0 ? _b : (privateEnv.identifiers = new ts.Map()); + privateEnv.identifiers.set(name.escapedText, info); + } + } + function getPrivateIdentifierInfo(privateEnv, key) { + var _a; + return (_a = privateEnv.identifiers) === null || _a === void 0 ? void 0 : _a.get(key); + } + function getGeneratedPrivateIdentifierInfo(privateEnv, key) { + var _a; + return (_a = privateEnv.generatedIdentifiers) === null || _a === void 0 ? void 0 : _a.get(key); } })(ts || (ts = {})); /*@internal*/ @@ -96814,15 +97771,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 164 /* SyntaxKind.Parameter */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 166 /* SyntaxKind.Parameter */: return serializeTypeNode(node.type); - case 173 /* SyntaxKind.SetAccessor */: - case 172 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: return serializeTypeNode(getAccessorTypeNode(node)); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: return ts.factory.createIdentifier("Function"); default: return ts.factory.createVoidZero(); @@ -96858,7 +97815,7 @@ var ts; return ts.factory.createArrayLiteralExpression(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { + if (container && node.kind === 174 /* SyntaxKind.GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -96904,66 +97861,66 @@ var ts; node = ts.skipTypeParentheses(node); switch (node.kind) { case 114 /* SyntaxKind.VoidKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: + case 155 /* SyntaxKind.UndefinedKeyword */: + case 144 /* SyntaxKind.NeverKeyword */: return ts.factory.createVoidZero(); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: return ts.factory.createIdentifier("Function"); - case 183 /* SyntaxKind.ArrayType */: - case 184 /* SyntaxKind.TupleType */: + case 185 /* SyntaxKind.ArrayType */: + case 186 /* SyntaxKind.TupleType */: return ts.factory.createIdentifier("Array"); - case 177 /* SyntaxKind.TypePredicate */: + case 179 /* SyntaxKind.TypePredicate */: return node.assertsModifier ? ts.factory.createVoidZero() : ts.factory.createIdentifier("Boolean"); - case 133 /* SyntaxKind.BooleanKeyword */: + case 134 /* SyntaxKind.BooleanKeyword */: return ts.factory.createIdentifier("Boolean"); - case 198 /* SyntaxKind.TemplateLiteralType */: - case 150 /* SyntaxKind.StringKeyword */: + case 200 /* SyntaxKind.TemplateLiteralType */: + case 152 /* SyntaxKind.StringKeyword */: return ts.factory.createIdentifier("String"); - case 148 /* SyntaxKind.ObjectKeyword */: + case 149 /* SyntaxKind.ObjectKeyword */: return ts.factory.createIdentifier("Object"); - case 196 /* SyntaxKind.LiteralType */: + case 198 /* SyntaxKind.LiteralType */: return serializeLiteralOfLiteralTypeNode(node.literal); - case 147 /* SyntaxKind.NumberKeyword */: + case 148 /* SyntaxKind.NumberKeyword */: return ts.factory.createIdentifier("Number"); - case 158 /* SyntaxKind.BigIntKeyword */: + case 160 /* SyntaxKind.BigIntKeyword */: return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); - case 151 /* SyntaxKind.SymbolKeyword */: + case 153 /* SyntaxKind.SymbolKeyword */: return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return serializeTypeReferenceNode(node); - case 188 /* SyntaxKind.IntersectionType */: + case 190 /* SyntaxKind.IntersectionType */: return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ true); - case 187 /* SyntaxKind.UnionType */: + case 189 /* SyntaxKind.UnionType */: return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ false); - case 189 /* SyntaxKind.ConditionalType */: + case 191 /* SyntaxKind.ConditionalType */: return serializeUnionOrIntersectionConstituents([node.trueType, node.falseType], /*isIntersection*/ false); - case 193 /* SyntaxKind.TypeOperator */: - if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { + case 195 /* SyntaxKind.TypeOperator */: + if (node.operator === 146 /* SyntaxKind.ReadonlyKeyword */) { return serializeTypeNode(node.type); } break; - case 181 /* SyntaxKind.TypeQuery */: - case 194 /* SyntaxKind.IndexedAccessType */: - case 195 /* SyntaxKind.MappedType */: - case 182 /* SyntaxKind.TypeLiteral */: - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 192 /* SyntaxKind.ThisType */: - case 200 /* SyntaxKind.ImportType */: + case 183 /* SyntaxKind.TypeQuery */: + case 196 /* SyntaxKind.IndexedAccessType */: + case 197 /* SyntaxKind.MappedType */: + case 184 /* SyntaxKind.TypeLiteral */: + case 131 /* SyntaxKind.AnyKeyword */: + case 157 /* SyntaxKind.UnknownKeyword */: + case 194 /* SyntaxKind.ThisType */: + case 202 /* SyntaxKind.ImportType */: break; // handle JSDoc types from an invalid parse - case 312 /* SyntaxKind.JSDocAllType */: - case 313 /* SyntaxKind.JSDocUnknownType */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 318 /* SyntaxKind.JSDocVariadicType */: - case 319 /* SyntaxKind.JSDocNamepathType */: + case 315 /* SyntaxKind.JSDocAllType */: + case 316 /* SyntaxKind.JSDocUnknownType */: + case 320 /* SyntaxKind.JSDocFunctionType */: + case 321 /* SyntaxKind.JSDocVariadicType */: + case 322 /* SyntaxKind.JSDocNamepathType */: break; - case 314 /* SyntaxKind.JSDocNullableType */: - case 315 /* SyntaxKind.JSDocNonNullableType */: - case 316 /* SyntaxKind.JSDocOptionalType */: + case 317 /* SyntaxKind.JSDocNullableType */: + case 318 /* SyntaxKind.JSDocNonNullableType */: + case 319 /* SyntaxKind.JSDocOptionalType */: return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); @@ -96975,7 +97932,7 @@ var ts; case 10 /* SyntaxKind.StringLiteral */: case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: return ts.factory.createIdentifier("String"); - case 219 /* SyntaxKind.PrefixUnaryExpression */: { + case 221 /* SyntaxKind.PrefixUnaryExpression */: { var operand = node.operand; switch (operand.kind) { case 8 /* SyntaxKind.NumericLiteral */: @@ -97004,20 +97961,20 @@ var ts; for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { var typeNode = types_22[_i]; typeNode = ts.skipTypeParentheses(typeNode); - if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { + if (typeNode.kind === 144 /* SyntaxKind.NeverKeyword */) { if (isIntersection) return ts.factory.createVoidZero(); // Reduce to `never` in an intersection continue; // Elide `never` in a union } - if (typeNode.kind === 155 /* SyntaxKind.UnknownKeyword */) { + if (typeNode.kind === 157 /* SyntaxKind.UnknownKeyword */) { if (!isIntersection) return ts.factory.createIdentifier("Object"); // Reduce to `unknown` in a union continue; // Elide `unknown` in an intersection } - if (typeNode.kind === 130 /* SyntaxKind.AnyKeyword */) { + if (typeNode.kind === 131 /* SyntaxKind.AnyKeyword */) { return ts.factory.createIdentifier("Object"); // Reduce to `any` in a union or intersection } - if (!strictNullChecks && ((ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */) || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { + if (!strictNullChecks && ((ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */) || typeNode.kind === 155 /* SyntaxKind.UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var serializedConstituent = serializeTypeNode(typeNode); @@ -97165,7 +98122,7 @@ var ts; name.original = undefined; ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. return name; - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: return serializeQualifiedNameAsExpression(node); } } @@ -97220,24 +98177,24 @@ var ts; return node; } switch (node.kind) { - case 165 /* SyntaxKind.Decorator */: + case 167 /* SyntaxKind.Decorator */: // Decorators are elided. They will be emitted as part of `visitClassDeclaration`. return undefined; - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: return visitClassDeclaration(node); - case 226 /* SyntaxKind.ClassExpression */: + case 228 /* SyntaxKind.ClassExpression */: return visitClassExpression(node); - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return visitConstructorDeclaration(node); - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: return visitMethodDeclaration(node); - case 173 /* SyntaxKind.SetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return visitSetAccessorDeclaration(node); - case 172 /* SyntaxKind.GetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: return visitGetAccessorDeclaration(node); - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: return visitPropertyDeclaration(node); - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return visitParameterDeclaration(node); default: return ts.visitEachChild(node, visitor, context); @@ -97593,7 +98550,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ - ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ + ? ts.isPropertyDeclaration(member) && !ts.hasAccessorModifier(member) // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? factory.createVoidZero() @@ -97856,34 +98813,37 @@ var ts; return node; } switch (node.kind) { - case 131 /* SyntaxKind.AsyncKeyword */: + case 132 /* SyntaxKind.AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 218 /* SyntaxKind.AwaitExpression */: + case 220 /* SyntaxKind.AwaitExpression */: return visitAwaitExpression(node); - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitMethodDeclaration, node); - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitFunctionDeclaration, node); - case 213 /* SyntaxKind.FunctionExpression */: + case 215 /* SyntaxKind.FunctionExpression */: return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitFunctionExpression, node); - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return doWithContext(1 /* ContextFlags.NonTopLevel */, visitArrowFunction, node); - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 106 /* SyntaxKind.SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 106 /* SyntaxKind.SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 171 /* SyntaxKind.Constructor */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 174 /* SyntaxKind.GetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitGetAccessorDeclaration, node); + case 175 /* SyntaxKind.SetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitSetAccessorDeclaration, node); + case 173 /* SyntaxKind.Constructor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitConstructorDeclaration, node); + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitDefault, node); default: return ts.visitEachChild(node, visitor, context); @@ -97892,27 +98852,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return visitForStatementInAsyncBody(node); - case 243 /* SyntaxKind.ForInStatement */: + case 246 /* SyntaxKind.ForInStatement */: return visitForInStatementInAsyncBody(node); - case 244 /* SyntaxKind.ForOfStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return visitCatchClauseInAsyncBody(node); - case 235 /* SyntaxKind.Block */: - case 249 /* SyntaxKind.SwitchStatement */: - case 263 /* SyntaxKind.CaseBlock */: - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: - case 252 /* SyntaxKind.TryStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 239 /* SyntaxKind.IfStatement */: - case 248 /* SyntaxKind.WithStatement */: - case 250 /* SyntaxKind.LabeledStatement */: + case 238 /* SyntaxKind.Block */: + case 252 /* SyntaxKind.SwitchStatement */: + case 266 /* SyntaxKind.CaseBlock */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: + case 255 /* SyntaxKind.TryStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 242 /* SyntaxKind.IfStatement */: + case 251 /* SyntaxKind.WithStatement */: + case 253 /* SyntaxKind.LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -97982,6 +98942,9 @@ var ts; return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression( /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); + } /** * Visits a MethodDeclaration node. * @@ -97996,7 +98959,14 @@ var ts; /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) - : ts.visitFunctionBody(node.body, visitor, context)); + : transformMethodBody(node)); + } + function visitGetAccessorDeclaration(node) { + return factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformMethodBody(node)); + } + function visitSetAccessorDeclaration(node) { + return factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); } /** * Visits a FunctionDeclaration node. @@ -98110,12 +99080,48 @@ var ts; } return false; } + function transformMethodBody(node) { + ts.Debug.assertIsDefined(node.body); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = new ts.Set(); + hasSuperElementAccess = false; + var updated = ts.visitFunctionBody(node.body, visitor, context); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var originalMethod = ts.getOriginalNode(node, ts.isFunctionLikeDeclaration); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && + resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) && + (ts.getFunctionFlags(originalMethod) & 3 /* FunctionFlags.AsyncGenerator */) !== 3 /* FunctionFlags.AsyncGenerator */; + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + if (capturedSuperProperties.size) { + var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + var statements = updated.statements.slice(); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + updated = factory.updateBlock(updated, statements); + } + if (hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { + ts.addEmitHelper(updated, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { + ts.addEmitHelper(updated, ts.asyncSuperHelper); + } + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return updated; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ScriptTarget.ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 214 /* SyntaxKind.ArrowFunction */; + var isArrowFunction = node.kind === 216 /* SyntaxKind.ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* NodeCheckFlags.CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -98142,7 +99148,7 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { @@ -98155,10 +99161,10 @@ var ts; ts.setTextRange(block, node.body); if (emitSuperHelpers && hasSuperElementAccess) { // Emit helpers for super element access expressions (`super[x]`). - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -98206,17 +99212,17 @@ var ts; enabledSubstitutions |= 1 /* ES2017SubstitutionFlags.AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(208 /* SyntaxKind.CallExpression */); - context.enableSubstitution(206 /* SyntaxKind.PropertyAccessExpression */); - context.enableSubstitution(207 /* SyntaxKind.ElementAccessExpression */); + context.enableSubstitution(210 /* SyntaxKind.CallExpression */); + context.enableSubstitution(208 /* SyntaxKind.PropertyAccessExpression */); + context.enableSubstitution(209 /* SyntaxKind.ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(257 /* SyntaxKind.ClassDeclaration */); - context.enableEmitNotification(169 /* SyntaxKind.MethodDeclaration */); - context.enableEmitNotification(172 /* SyntaxKind.GetAccessor */); - context.enableEmitNotification(173 /* SyntaxKind.SetAccessor */); - context.enableEmitNotification(171 /* SyntaxKind.Constructor */); + context.enableEmitNotification(260 /* SyntaxKind.ClassDeclaration */); + context.enableEmitNotification(171 /* SyntaxKind.MethodDeclaration */); + context.enableEmitNotification(174 /* SyntaxKind.GetAccessor */); + context.enableEmitNotification(175 /* SyntaxKind.SetAccessor */); + context.enableEmitNotification(173 /* SyntaxKind.Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(237 /* SyntaxKind.VariableStatement */); + context.enableEmitNotification(240 /* SyntaxKind.VariableStatement */); } } /** @@ -98230,7 +99236,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ES2017SubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -98264,11 +99270,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return substituteElementAccessExpression(node); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return substituteCallExpression(node); } return node; @@ -98300,14 +99306,14 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 257 /* SyntaxKind.ClassDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */; + return kind === 260 /* SyntaxKind.ClassDeclaration */ + || kind === 173 /* SyntaxKind.Constructor */ + || kind === 171 /* SyntaxKind.MethodDeclaration */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -98322,7 +99328,7 @@ var ts; function createSuperAccessVariableStatement(factory, resolver, node, names) { // Create a variable declaration with a getter/setter (if binding) definition for each name: // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); - var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) !== 0; + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) !== 0; var accessors = []; names.forEach(function (_, key) { var name = ts.unescapeLeadingUnderscores(key); @@ -98461,7 +99467,7 @@ var ts; return visitorWorker(node, /*expressionResultIsUnused*/ true); } function visitorNoAsyncModifier(node) { - if (node.kind === 131 /* SyntaxKind.AsyncKeyword */) { + if (node.kind === 132 /* SyntaxKind.AsyncKeyword */) { return undefined; } return node; @@ -98487,70 +99493,70 @@ var ts; return node; } switch (node.kind) { - case 218 /* SyntaxKind.AwaitExpression */: + case 220 /* SyntaxKind.AwaitExpression */: return visitAwaitExpression(node); - case 224 /* SyntaxKind.YieldExpression */: + case 226 /* SyntaxKind.YieldExpression */: return visitYieldExpression(node); - case 247 /* SyntaxKind.ReturnStatement */: + case 250 /* SyntaxKind.ReturnStatement */: return visitReturnStatement(node); - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: return visitLabeledStatement(node); - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 351 /* SyntaxKind.CommaListExpression */: + case 354 /* SyntaxKind.CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return visitCatchClause(node); - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return visitVariableStatement(node); - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return visitVariableDeclaration(node); - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 243 /* SyntaxKind.ForInStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 246 /* SyntaxKind.ForInStatement */: return doWithHierarchyFacts(visitDefault, node, 0 /* HierarchyFacts.IterationStatementExcludes */, 2 /* HierarchyFacts.IterationStatementIncludes */); - case 244 /* SyntaxKind.ForOfStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return doWithHierarchyFacts(visitForStatement, node, 0 /* HierarchyFacts.IterationStatementExcludes */, 2 /* HierarchyFacts.IterationStatementIncludes */); - case 217 /* SyntaxKind.VoidExpression */: + case 219 /* SyntaxKind.VoidExpression */: return visitVoidExpression(node); - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* HierarchyFacts.ClassOrFunctionExcludes */, 1 /* HierarchyFacts.ClassOrFunctionIncludes */); - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* HierarchyFacts.ClassOrFunctionExcludes */, 1 /* HierarchyFacts.ClassOrFunctionIncludes */); - case 172 /* SyntaxKind.GetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* HierarchyFacts.ClassOrFunctionExcludes */, 1 /* HierarchyFacts.ClassOrFunctionIncludes */); - case 173 /* SyntaxKind.SetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* HierarchyFacts.ClassOrFunctionExcludes */, 1 /* HierarchyFacts.ClassOrFunctionIncludes */); - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* HierarchyFacts.ClassOrFunctionExcludes */, 1 /* HierarchyFacts.ClassOrFunctionIncludes */); - case 213 /* SyntaxKind.FunctionExpression */: + case 215 /* SyntaxKind.FunctionExpression */: return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* HierarchyFacts.ClassOrFunctionExcludes */, 1 /* HierarchyFacts.ClassOrFunctionIncludes */); - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return doWithHierarchyFacts(visitArrowFunction, node, 2 /* HierarchyFacts.ArrowFunctionExcludes */, 0 /* HierarchyFacts.ArrowFunctionIncludes */); - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return visitParameter(node); - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: return visitExpressionStatement(node); - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 106 /* SyntaxKind.SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 106 /* SyntaxKind.SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: return doWithHierarchyFacts(visitDefault, node, 2 /* HierarchyFacts.ClassOrFunctionExcludes */, 1 /* HierarchyFacts.ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); @@ -98586,7 +99592,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* FunctionFlags.Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 244 /* SyntaxKind.ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 247 /* SyntaxKind.ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node); @@ -98598,7 +99604,7 @@ var ts; var objects = []; for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { var e = elements_5[_i]; - if (e.kind === 298 /* SyntaxKind.SpreadAssignment */) { + if (e.kind === 301 /* SyntaxKind.SpreadAssignment */) { if (chunkObject) { objects.push(factory.createObjectLiteralExpression(chunkObject)); chunkObject = undefined; @@ -98607,7 +99613,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 296 /* SyntaxKind.PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 299 /* SyntaxKind.PropertyAssignment */ ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -98641,7 +99647,7 @@ var ts; // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we // end up with `{ a: 1, b: 2, c: 3 }` var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 205 /* SyntaxKind.ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 207 /* SyntaxKind.ObjectLiteralExpression */) { objects.unshift(factory.createObjectLiteralExpression()); } var expression = objects[0]; @@ -98815,11 +99821,22 @@ var ts; } return node; } - function convertForOfStatementHead(node, boundValue) { - var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue); + function convertForOfStatementHead(node, boundValue, nonUserCode) { + var value = factory.createTempVariable(hoistVariableDeclaration); + var iteratorValueExpression = factory.createAssignment(value, boundValue); + var iteratorValueStatement = factory.createExpressionStatement(iteratorValueExpression); + ts.setSourceMapRange(iteratorValueStatement, node.expression); + var exitNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createFalse()); + var exitNonUserCodeStatement = factory.createExpressionStatement(exitNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var enterNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createTrue()); + var enterNonUserCodeStatement = factory.createExpressionStatement(enterNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var statements = []; + var binding = ts.createForOfBindingStatement(factory, node.initializer, value); + statements.push(ts.visitNode(binding, visitor, ts.isStatement)); var bodyLocation; var statementsLocation; - var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); @@ -98829,8 +99846,16 @@ var ts; else { statements.push(statement); } - return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), + var body = ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* EmitFlags.NoSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */); + return factory.createBlock([ + iteratorValueStatement, + exitNonUserCodeStatement, + factory.createTryStatement(body, + /*catchClause*/ undefined, factory.createBlock([ + enterNonUserCodeStatement + ])) + ]); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ @@ -98841,6 +99866,8 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined); + var nonUserCode = factory.createTempVariable(/*recordTempVariable*/ undefined); + var done = factory.createTempVariable(hoistVariableDeclaration); var errorRecord = factory.createUniqueName("e"); var catchVariable = factory.getGeneratedNameForNode(errorRecord); var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined); @@ -98857,12 +99884,17 @@ var ts; callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement( /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([ + factory.createVariableDeclaration(nonUserCode, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createTrue()), ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression), factory.createVariableDeclaration(result) ]), node.expression), 2097152 /* EmitFlags.NoHoisting */), - /*condition*/ factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)), + /*condition*/ factory.inlineExpressions([ + factory.createAssignment(result, createDownlevelAwait(callNext)), + factory.createAssignment(done, getDone), + factory.createLogicalNot(done) + ]), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, getValue)), + /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode)), /*location*/ node), 256 /* EmitFlags.NoTokenTrailingSourceMaps */); ts.setOriginalNode(forStatement, node); return factory.createTryStatement(factory.createBlock([ @@ -98874,7 +99906,7 @@ var ts; ]), 1 /* EmitFlags.SingleLine */)), factory.createBlock([ factory.createTryStatement( /*tryBlock*/ factory.createBlock([ - ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(result, factory.createLogicalNot(getDone)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) + ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(factory.createLogicalNot(nonUserCode), factory.createLogicalNot(done)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([ @@ -99030,7 +100062,7 @@ var ts; /*type*/ undefined, factory.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HierarchyFacts.HasLexicalThis */))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); @@ -99041,10 +100073,10 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = factory.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -99149,17 +100181,17 @@ var ts; enabledSubstitutions |= 1 /* ESNextSubstitutionFlags.AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(208 /* SyntaxKind.CallExpression */); - context.enableSubstitution(206 /* SyntaxKind.PropertyAccessExpression */); - context.enableSubstitution(207 /* SyntaxKind.ElementAccessExpression */); + context.enableSubstitution(210 /* SyntaxKind.CallExpression */); + context.enableSubstitution(208 /* SyntaxKind.PropertyAccessExpression */); + context.enableSubstitution(209 /* SyntaxKind.ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(257 /* SyntaxKind.ClassDeclaration */); - context.enableEmitNotification(169 /* SyntaxKind.MethodDeclaration */); - context.enableEmitNotification(172 /* SyntaxKind.GetAccessor */); - context.enableEmitNotification(173 /* SyntaxKind.SetAccessor */); - context.enableEmitNotification(171 /* SyntaxKind.Constructor */); + context.enableEmitNotification(260 /* SyntaxKind.ClassDeclaration */); + context.enableEmitNotification(171 /* SyntaxKind.MethodDeclaration */); + context.enableEmitNotification(174 /* SyntaxKind.GetAccessor */); + context.enableEmitNotification(175 /* SyntaxKind.SetAccessor */); + context.enableEmitNotification(173 /* SyntaxKind.Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(237 /* SyntaxKind.VariableStatement */); + context.enableEmitNotification(240 /* SyntaxKind.VariableStatement */); } } /** @@ -99173,7 +100205,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ESNextSubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -99207,11 +100239,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return substituteElementAccessExpression(node); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return substituteCallExpression(node); } return node; @@ -99243,14 +100275,14 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 257 /* SyntaxKind.ClassDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */; + return kind === 260 /* SyntaxKind.ClassDeclaration */ + || kind === 173 /* SyntaxKind.Constructor */ + || kind === 171 /* SyntaxKind.MethodDeclaration */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -99279,7 +100311,7 @@ var ts; return node; } switch (node.kind) { - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -99311,25 +100343,25 @@ var ts; return node; } switch (node.kind) { - case 208 /* SyntaxKind.CallExpression */: { + case 210 /* SyntaxKind.CallExpression */: { var updated = visitNonOptionalCallExpression(node, /*captureThisArg*/ false); ts.Debug.assertNotNode(updated, ts.isSyntheticReference); return updated; } - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: if (ts.isOptionalChain(node)) { var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false); ts.Debug.assertNotNode(updated, ts.isSyntheticReference); return updated; } return ts.visitEachChild(node, visitor, context); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: if (node.operatorToken.kind === 60 /* SyntaxKind.QuestionQuestionToken */) { return transformNullishCoalescingExpression(node); } return ts.visitEachChild(node, visitor, context); - case 215 /* SyntaxKind.DeleteExpression */: + case 217 /* SyntaxKind.DeleteExpression */: return visitDeleteExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -99371,7 +100403,7 @@ var ts; thisArg = expression; } } - expression = node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ + expression = node.kind === 208 /* SyntaxKind.PropertyAccessExpression */ ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression; @@ -99394,10 +100426,10 @@ var ts; } function visitNonOptionalExpression(node, captureThisArg, isDelete) { switch (node.kind) { - case 212 /* SyntaxKind.ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); - case 208 /* SyntaxKind.CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); + case 214 /* SyntaxKind.ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); + case 210 /* SyntaxKind.CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } } @@ -99416,8 +100448,8 @@ var ts; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: if (i === chain.length - 1 && captureThisArg) { if (!ts.isSimpleCopiableExpression(rightExpression)) { thisArg = factory.createTempVariable(hoistVariableDeclaration); @@ -99427,11 +100459,11 @@ var ts; thisArg = rightExpression; } } - rightExpression = segment.kind === 206 /* SyntaxKind.PropertyAccessExpression */ + rightExpression = segment.kind === 208 /* SyntaxKind.PropertyAccessExpression */ ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: if (i === 0 && leftThisArg) { if (!ts.isGeneratedIdentifier(leftThisArg)) { leftThisArg = factory.cloneNode(leftThisArg); @@ -99492,7 +100524,7 @@ var ts; return node; } switch (node.kind) { - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: var binaryExpression = node; if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) { return transformLogicalAssignment(binaryExpression); @@ -99661,13 +100693,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 278 /* SyntaxKind.JsxElement */: + case 281 /* SyntaxKind.JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 282 /* SyntaxKind.JsxFragment */: + case 285 /* SyntaxKind.JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 288 /* SyntaxKind.JsxExpression */: + case 291 /* SyntaxKind.JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -99677,13 +100709,13 @@ var ts; switch (node.kind) { case 11 /* SyntaxKind.JsxText */: return visitJsxText(node); - case 288 /* SyntaxKind.JsxExpression */: + case 291 /* SyntaxKind.JsxExpression */: return visitJsxExpression(node); - case 278 /* SyntaxKind.JsxElement */: + case 281 /* SyntaxKind.JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 282 /* SyntaxKind.JsxFragment */: + case 285 /* SyntaxKind.JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -99864,7 +100896,7 @@ var ts; var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - if (node.kind === 288 /* SyntaxKind.JsxExpression */) { + if (node.kind === 291 /* SyntaxKind.JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } @@ -99965,7 +100997,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 278 /* SyntaxKind.JsxElement */) { + if (node.kind === 281 /* SyntaxKind.JsxElement */) { return getTagName(node.openingElement); } else { @@ -100272,7 +101304,7 @@ var ts; return node; } switch (node.kind) { - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -100497,7 +101529,7 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 8192 /* HierarchyFacts.ConstructorWithCapturedSuper */) !== 0 - && node.kind === 247 /* SyntaxKind.ReturnStatement */ + && node.kind === 250 /* SyntaxKind.ReturnStatement */ && !node.expression; } function isOrMayContainReturnCompletion(node) { @@ -100551,65 +101583,65 @@ var ts; switch (node.kind) { case 124 /* SyntaxKind.StaticKeyword */: return undefined; // elide static keyword - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: return visitClassDeclaration(node); - case 226 /* SyntaxKind.ClassExpression */: + case 228 /* SyntaxKind.ClassExpression */: return visitClassExpression(node); - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return visitParameter(node); - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return visitFunctionDeclaration(node); - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return visitArrowFunction(node); - case 213 /* SyntaxKind.FunctionExpression */: + case 215 /* SyntaxKind.FunctionExpression */: return visitFunctionExpression(node); - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return visitVariableDeclaration(node); case 79 /* SyntaxKind.Identifier */: return visitIdentifier(node); - case 255 /* SyntaxKind.VariableDeclarationList */: + case 258 /* SyntaxKind.VariableDeclarationList */: return visitVariableDeclarationList(node); - case 249 /* SyntaxKind.SwitchStatement */: + case 252 /* SyntaxKind.SwitchStatement */: return visitSwitchStatement(node); - case 263 /* SyntaxKind.CaseBlock */: + case 266 /* SyntaxKind.CaseBlock */: return visitCaseBlock(node); - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 246 /* SyntaxKind.BreakStatement */: - case 245 /* SyntaxKind.ContinueStatement */: + case 249 /* SyntaxKind.BreakStatement */: + case 248 /* SyntaxKind.ContinueStatement */: return visitBreakOrContinueStatement(node); - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: return visitLabeledStatement(node); - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 243 /* SyntaxKind.ForInStatement */: + case 246 /* SyntaxKind.ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 244 /* SyntaxKind.ForOfStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: return visitExpressionStatement(node); - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return visitCatchClause(node); - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: return visitComputedPropertyName(node); - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return visitCallExpression(node); - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: return visitNewExpression(node); - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 351 /* SyntaxKind.CommaListExpression */: + case 354 /* SyntaxKind.CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: case 15 /* SyntaxKind.TemplateHead */: @@ -100620,30 +101652,30 @@ var ts; return visitStringLiteral(node); case 8 /* SyntaxKind.NumericLiteral */: return visitNumericLiteral(node); - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 223 /* SyntaxKind.TemplateExpression */: + case 225 /* SyntaxKind.TemplateExpression */: return visitTemplateExpression(node); - case 224 /* SyntaxKind.YieldExpression */: + case 226 /* SyntaxKind.YieldExpression */: return visitYieldExpression(node); - case 225 /* SyntaxKind.SpreadElement */: + case 227 /* SyntaxKind.SpreadElement */: return visitSpreadElement(node); case 106 /* SyntaxKind.SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); case 108 /* SyntaxKind.ThisKeyword */: return visitThisKeyword(node); - case 231 /* SyntaxKind.MetaProperty */: + case 233 /* SyntaxKind.MetaProperty */: return visitMetaProperty(node); - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: return visitMethodDeclaration(node); - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return visitAccessorDeclaration(node); - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return visitVariableStatement(node); - case 247 /* SyntaxKind.ReturnStatement */: + case 250 /* SyntaxKind.ReturnStatement */: return visitReturnStatement(node); - case 217 /* SyntaxKind.VoidExpression */: + case 219 /* SyntaxKind.VoidExpression */: return visitVoidExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -100719,11 +101751,13 @@ var ts; return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); } function visitIdentifier(node) { - if (!convertedLoopState) { - return node; + if (convertedLoopState) { + if (resolver.isArgumentsLocalBinding(node)) { + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + } } - if (resolver.isArgumentsLocalBinding(node)) { - return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + if (node.hasExtendedUnicodeEscape) { + return ts.setOriginalNode(ts.setTextRange(factory.createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText)), node), node); } return node; } @@ -100733,14 +101767,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 246 /* SyntaxKind.BreakStatement */ ? 2 /* Jump.Break */ : 4 /* Jump.Continue */; + var jump = node.kind === 249 /* SyntaxKind.BreakStatement */ ? 2 /* Jump.Break */ : 4 /* Jump.Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 246 /* SyntaxKind.BreakStatement */) { + if (node.kind === 249 /* SyntaxKind.BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Jump.Break */; labelMarker = "break"; } @@ -100751,7 +101785,7 @@ var ts; } } else { - if (node.kind === 246 /* SyntaxKind.BreakStatement */) { + if (node.kind === 249 /* SyntaxKind.BreakStatement */) { labelMarker = "break-".concat(label.escapedText); setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -100807,7 +101841,7 @@ var ts; statements.push(statement); // Add an `export default` statement for default exports (for `--target es5 --module es6`) if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - var exportStatement = ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */) + var exportStatement = ts.hasSyntacticModifier(node, 1024 /* ModifierFlags.Default */) ? factory.createExportDefault(factory.getLocalName(node)) : factory.createExternalModuleExport(factory.getLocalName(node)); ts.setOriginalNode(exportStatement, statement); @@ -101176,11 +102210,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 247 /* SyntaxKind.ReturnStatement */) { + if (statement.kind === 250 /* SyntaxKind.ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 239 /* SyntaxKind.IfStatement */) { + else if (statement.kind === 242 /* SyntaxKind.IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -101188,7 +102222,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 235 /* SyntaxKind.Block */) { + else if (statement.kind === 238 /* SyntaxKind.Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -101388,7 +102422,7 @@ var ts; * @param node A node. */ function insertCaptureThisForNodeIfNeeded(statements, node) { - if (hierarchyFacts & 65536 /* HierarchyFacts.CapturedLexicalThis */ && node.kind !== 214 /* SyntaxKind.ArrowFunction */) { + if (hierarchyFacts & 65536 /* HierarchyFacts.CapturedLexicalThis */ && node.kind !== 216 /* SyntaxKind.ArrowFunction */) { insertCaptureThisForNode(statements, node, factory.createThis()); return true; } @@ -101422,22 +102456,22 @@ var ts; if (hierarchyFacts & 32768 /* HierarchyFacts.NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return statements; - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = factory.createVoidZero(); break; - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* EmitFlags.NoSubstitution */), "constructor"); break; - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4 /* EmitFlags.NoSubstitution */), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4 /* EmitFlags.NoSubstitution */), 102 /* SyntaxKind.InstanceOfKeyword */, factory.getLocalName(node))), @@ -101472,21 +102506,21 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 234 /* SyntaxKind.SemicolonClassElement */: + case 237 /* SyntaxKind.SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 171 /* SyntaxKind.Constructor */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -101685,7 +102719,7 @@ var ts; : enterSubtree(32670 /* HierarchyFacts.FunctionExcludes */, 65 /* HierarchyFacts.FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 32768 /* HierarchyFacts.NewTarget */ && !name && (node.kind === 256 /* SyntaxKind.FunctionDeclaration */ || node.kind === 213 /* SyntaxKind.FunctionExpression */)) { + if (hierarchyFacts & 32768 /* HierarchyFacts.NewTarget */ && !name && (node.kind === 259 /* SyntaxKind.FunctionDeclaration */ || node.kind === 215 /* SyntaxKind.FunctionExpression */)) { name = factory.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); @@ -101731,7 +102765,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 214 /* SyntaxKind.ArrowFunction */); + ts.Debug.assert(node.kind === 216 /* SyntaxKind.ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -102038,14 +103072,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 243 /* SyntaxKind.ForInStatement */: + case 246 /* SyntaxKind.ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 244 /* SyntaxKind.ForOfStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -102231,7 +103265,7 @@ var ts; var property = properties[i]; if ((property.transformFlags & 1048576 /* TransformFlags.ContainsYield */ && hierarchyFacts & 4 /* HierarchyFacts.AsyncFunctionBody */) - || (hasComputed = ts.Debug.checkDefined(property.name).kind === 162 /* SyntaxKind.ComputedPropertyName */)) { + || (hasComputed = ts.Debug.checkDefined(property.name).kind === 164 /* SyntaxKind.ComputedPropertyName */)) { numInitialProperties = i; break; } @@ -102347,11 +103381,11 @@ var ts; } function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { switch (node.kind) { - case 242 /* SyntaxKind.ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); - case 243 /* SyntaxKind.ForInStatement */: return convertForInStatement(node, convertedLoopBody); - case 244 /* SyntaxKind.ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); - case 240 /* SyntaxKind.DoStatement */: return convertDoStatement(node, convertedLoopBody); - case 241 /* SyntaxKind.WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + case 245 /* SyntaxKind.ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 246 /* SyntaxKind.ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 247 /* SyntaxKind.ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 243 /* SyntaxKind.DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 244 /* SyntaxKind.WhileStatement */: return convertWhileStatement(node, convertedLoopBody); default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); } } @@ -102376,11 +103410,11 @@ var ts; function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (initializer && initializer.kind === 258 /* SyntaxKind.VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -102796,20 +103830,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -102916,7 +103950,7 @@ var ts; var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 172 /* SyntaxKind.GetAccessor */) { + if (node.kind === 174 /* SyntaxKind.GetAccessor */) { updated = factory.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body); } else { @@ -103376,13 +104410,13 @@ var ts; if ((enabledSubstitutions & 1 /* ES2015SubstitutionFlags.CapturedThis */) === 0) { enabledSubstitutions |= 1 /* ES2015SubstitutionFlags.CapturedThis */; context.enableSubstitution(108 /* SyntaxKind.ThisKeyword */); - context.enableEmitNotification(171 /* SyntaxKind.Constructor */); - context.enableEmitNotification(169 /* SyntaxKind.MethodDeclaration */); - context.enableEmitNotification(172 /* SyntaxKind.GetAccessor */); - context.enableEmitNotification(173 /* SyntaxKind.SetAccessor */); - context.enableEmitNotification(214 /* SyntaxKind.ArrowFunction */); - context.enableEmitNotification(213 /* SyntaxKind.FunctionExpression */); - context.enableEmitNotification(256 /* SyntaxKind.FunctionDeclaration */); + context.enableEmitNotification(173 /* SyntaxKind.Constructor */); + context.enableEmitNotification(171 /* SyntaxKind.MethodDeclaration */); + context.enableEmitNotification(174 /* SyntaxKind.GetAccessor */); + context.enableEmitNotification(175 /* SyntaxKind.SetAccessor */); + context.enableEmitNotification(216 /* SyntaxKind.ArrowFunction */); + context.enableEmitNotification(215 /* SyntaxKind.FunctionExpression */); + context.enableEmitNotification(259 /* SyntaxKind.FunctionDeclaration */); } } /** @@ -103423,10 +104457,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 203 /* SyntaxKind.BindingElement */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 254 /* SyntaxKind.VariableDeclaration */: + case 205 /* SyntaxKind.BindingElement */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -103508,11 +104542,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 238 /* SyntaxKind.ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 241 /* SyntaxKind.ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 208 /* SyntaxKind.CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 210 /* SyntaxKind.CallExpression */) { return false; } var callTarget = statementExpression.expression; @@ -103520,7 +104554,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 225 /* SyntaxKind.SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 227 /* SyntaxKind.SpreadElement */) { return false; } var expression = callArgument.expression; @@ -103546,15 +104580,15 @@ var ts; if (compilerOptions.jsx === 1 /* JsxEmit.Preserve */ || compilerOptions.jsx === 3 /* JsxEmit.ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(280 /* SyntaxKind.JsxOpeningElement */); - context.enableEmitNotification(281 /* SyntaxKind.JsxClosingElement */); - context.enableEmitNotification(279 /* SyntaxKind.JsxSelfClosingElement */); + context.enableEmitNotification(283 /* SyntaxKind.JsxOpeningElement */); + context.enableEmitNotification(284 /* SyntaxKind.JsxClosingElement */); + context.enableEmitNotification(282 /* SyntaxKind.JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(206 /* SyntaxKind.PropertyAccessExpression */); - context.enableSubstitution(296 /* SyntaxKind.PropertyAssignment */); + context.enableSubstitution(208 /* SyntaxKind.PropertyAccessExpression */); + context.enableSubstitution(299 /* SyntaxKind.PropertyAssignment */); return ts.chainBundle(context, transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -103573,9 +104607,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 280 /* SyntaxKind.JsxOpeningElement */: - case 281 /* SyntaxKind.JsxClosingElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 284 /* SyntaxKind.JsxClosingElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -103910,13 +104944,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 240 /* SyntaxKind.DoStatement */: + case 243 /* SyntaxKind.DoStatement */: return visitDoStatement(node); - case 241 /* SyntaxKind.WhileStatement */: + case 244 /* SyntaxKind.WhileStatement */: return visitWhileStatement(node); - case 249 /* SyntaxKind.SwitchStatement */: + case 252 /* SyntaxKind.SwitchStatement */: return visitSwitchStatement(node); - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -103929,24 +104963,24 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return visitFunctionDeclaration(node); - case 213 /* SyntaxKind.FunctionExpression */: + case 215 /* SyntaxKind.FunctionExpression */: return visitFunctionExpression(node); - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return visitAccessorDeclaration(node); - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return visitVariableStatement(node); - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return visitForStatement(node); - case 243 /* SyntaxKind.ForInStatement */: + case 246 /* SyntaxKind.ForInStatement */: return visitForInStatement(node); - case 246 /* SyntaxKind.BreakStatement */: + case 249 /* SyntaxKind.BreakStatement */: return visitBreakStatement(node); - case 245 /* SyntaxKind.ContinueStatement */: + case 248 /* SyntaxKind.ContinueStatement */: return visitContinueStatement(node); - case 247 /* SyntaxKind.ReturnStatement */: + case 250 /* SyntaxKind.ReturnStatement */: return visitReturnStatement(node); default: if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { @@ -103967,23 +105001,23 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return visitBinaryExpression(node); - case 351 /* SyntaxKind.CommaListExpression */: + case 354 /* SyntaxKind.CommaListExpression */: return visitCommaListExpression(node); - case 222 /* SyntaxKind.ConditionalExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: return visitConditionalExpression(node); - case 224 /* SyntaxKind.YieldExpression */: + case 226 /* SyntaxKind.YieldExpression */: return visitYieldExpression(node); - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return visitElementAccessExpression(node); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return visitCallExpression(node); - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -103996,9 +105030,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return visitFunctionDeclaration(node); - case 213 /* SyntaxKind.FunctionExpression */: + case 215 /* SyntaxKind.FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -104205,7 +105239,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: // [source] // a.b = yield; // @@ -104217,7 +105251,7 @@ var ts; // _a.b = %sent%; target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: // [source] // a[b] = yield; // @@ -104611,35 +105645,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: return transformAndEmitBlock(node); - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 239 /* SyntaxKind.IfStatement */: + case 242 /* SyntaxKind.IfStatement */: return transformAndEmitIfStatement(node); - case 240 /* SyntaxKind.DoStatement */: + case 243 /* SyntaxKind.DoStatement */: return transformAndEmitDoStatement(node); - case 241 /* SyntaxKind.WhileStatement */: + case 244 /* SyntaxKind.WhileStatement */: return transformAndEmitWhileStatement(node); - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return transformAndEmitForStatement(node); - case 243 /* SyntaxKind.ForInStatement */: + case 246 /* SyntaxKind.ForInStatement */: return transformAndEmitForInStatement(node); - case 245 /* SyntaxKind.ContinueStatement */: + case 248 /* SyntaxKind.ContinueStatement */: return transformAndEmitContinueStatement(node); - case 246 /* SyntaxKind.BreakStatement */: + case 249 /* SyntaxKind.BreakStatement */: return transformAndEmitBreakStatement(node); - case 247 /* SyntaxKind.ReturnStatement */: + case 250 /* SyntaxKind.ReturnStatement */: return transformAndEmitReturnStatement(node); - case 248 /* SyntaxKind.WithStatement */: + case 251 /* SyntaxKind.WithStatement */: return transformAndEmitWithStatement(node); - case 249 /* SyntaxKind.SwitchStatement */: + case 252 /* SyntaxKind.SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 251 /* SyntaxKind.ThrowStatement */: + case 254 /* SyntaxKind.ThrowStatement */: return transformAndEmitThrowStatement(node); - case 252 /* SyntaxKind.TryStatement */: + case 255 /* SyntaxKind.TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -104870,7 +105904,6 @@ var ts; return node; } function transformAndEmitForInStatement(node) { - // TODO(rbuckton): Source map locations if (containsYield(node)) { // [source] // for (var p in o) { @@ -104878,34 +105911,41 @@ var ts; // } // // [intermediate] - // .local _a, _b, _i - // _a = []; - // for (_b in o) _a.push(_b); + // .local _b, _a, _c, _i + // _b = []; + // _a = o; + // for (_c in _a) _b.push(_c); // _i = 0; // .loop incrementLabel, endLoopLabel // .mark conditionLabel - // .brfalse endLoopLabel, (_i < _a.length) - // p = _a[_i]; + // .brfalse endLoopLabel, (_i < _b.length) + // _c = _b[_i]; + // .brfalse incrementLabel, (_c in _a) + // p = _c; // /*body*/ // .mark incrementLabel - // _b++; + // _c++; // .br conditionLabel // .endloop // .mark endLoopLabel - var keysArray = declareLocal(); // _a - var key = declareLocal(); // _b + var obj = declareLocal(); // _a + var keysArray = declareLocal(); // _b + var key = declareLocal(); // _c var keysIndex = factory.createLoopVariable(); // _i var initializer = node.initializer; hoistVariableDeclaration(keysIndex); + emitAssignment(obj, ts.visitNode(node.expression, visitor, ts.isExpression)); emitAssignment(keysArray, factory.createArrayLiteralExpression()); - emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), + emitStatement(factory.createForInStatement(key, obj, factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), /*typeArguments*/ undefined, [key])))); emitAssignment(keysIndex, factory.createNumericLiteral(0)); var conditionLabel = defineLabel(); var incrementLabel = defineLabel(); - var endLabel = beginLoopBlock(incrementLabel); + var endLoopLabel = beginLoopBlock(incrementLabel); markLabel(conditionLabel); - emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitBreakWhenFalse(endLoopLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitAssignment(key, factory.createElementAccessExpression(keysArray, keysIndex)); + emitBreakWhenFalse(incrementLabel, factory.createBinaryExpression(key, 101 /* SyntaxKind.InKeyword */, obj)); var variable = void 0; if (ts.isVariableDeclarationList(initializer)) { for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { @@ -104918,7 +105958,7 @@ var ts; variable = ts.visitNode(initializer, visitor, ts.isExpression); ts.Debug.assert(ts.isLeftHandSideExpression(variable)); } - emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex)); + emitAssignment(variable, key); transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex))); @@ -105069,7 +106109,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 290 /* SyntaxKind.DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 293 /* SyntaxKind.DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -105082,7 +106122,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 289 /* SyntaxKind.CaseClause */) { + if (clause.kind === 292 /* SyntaxKind.CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -106242,12 +107282,12 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(208 /* SyntaxKind.CallExpression */); // Substitute calls to imported/exported symbols to avoid incorrect `this`. - context.enableSubstitution(210 /* SyntaxKind.TaggedTemplateExpression */); // Substitute calls to imported/exported symbols to avoid incorrect `this`. + context.enableSubstitution(210 /* SyntaxKind.CallExpression */); // Substitute calls to imported/exported symbols to avoid incorrect `this`. + context.enableSubstitution(212 /* SyntaxKind.TaggedTemplateExpression */); // Substitute calls to imported/exported symbols to avoid incorrect `this`. context.enableSubstitution(79 /* SyntaxKind.Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(221 /* SyntaxKind.BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(297 /* SyntaxKind.ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(305 /* SyntaxKind.SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(223 /* SyntaxKind.BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(300 /* SyntaxKind.ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(308 /* SyntaxKind.SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -106575,23 +107615,23 @@ var ts; */ function topLevelVisitor(node) { switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return visitImportDeclaration(node); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: return visitExportDeclaration(node); - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: return visitExportAssignment(node); - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return visitVariableStatement(node); - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return visitFunctionDeclaration(node); - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: return visitClassDeclaration(node); - case 352 /* SyntaxKind.MergeDeclarationMarker */: + case 355 /* SyntaxKind.MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 353 /* SyntaxKind.EndOfDeclarationMarker */: + case 356 /* SyntaxKind.EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return visitor(node); @@ -106604,26 +107644,26 @@ var ts; return node; } switch (node.kind) { - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return visitForStatement(node); - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: return visitExpressionStatement(node); - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return visitParenthesizedExpression(node, valueIsDiscarded); - case 350 /* SyntaxKind.PartiallyEmittedExpression */: + case 353 /* SyntaxKind.PartiallyEmittedExpression */: return visitPartiallyEmittedExpression(node, valueIsDiscarded); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: if (ts.isImportCall(node) && currentSourceFile.impliedNodeFormat === undefined) { return visitImportCallExpression(node); } break; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node, valueIsDiscarded); } break; - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: return visitPreOrPostfixUnaryExpression(node, valueIsDiscarded); } return ts.visitEachChild(node, visitor, context); @@ -106639,24 +107679,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 298 /* SyntaxKind.SpreadAssignment */: + case 301 /* SyntaxKind.SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -106759,7 +107799,7 @@ var ts; return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return createImportCallExpressionCommonJS(argument, containsLexicalThis); + return createImportCallExpressionCommonJS(argument); } } function createImportCallExpressionUMD(arg, containsLexicalThis) { @@ -106782,7 +107822,7 @@ var ts; return factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(arg), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); } @@ -106791,7 +107831,7 @@ var ts; return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, /* isInlineable */ true), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); } @@ -106841,14 +107881,20 @@ var ts; } return promise; } - function createImportCallExpressionCommonJS(arg, containsLexicalThis) { - // import("./blah") + function createImportCallExpressionCommonJS(arg, isInlineable) { + // import(x) // emit as - // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // var _a; + // (_a = x, Promise.resolve().then(() => require(_a)) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately - var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); - var requireCall = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + // If the arg is not inlineable, we have to evaluate it in the current scope with a temp var + var temp = arg && !ts.isSimpleInlineableExpression(arg) && !isInlineable ? factory.createTempVariable(hoistVariableDeclaration) : undefined; + var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), + /*typeArguments*/ undefined, + /*argumentsArray*/ []); + var requireCall = factory.createCallExpression(factory.createIdentifier("require"), + /*typeArguments*/ undefined, temp ? [temp] : arg ? [arg] : []); if (ts.getESModuleInterop(compilerOptions)) { requireCall = emitHelpers().createImportStarHelper(requireCall); } @@ -106869,14 +107915,9 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)])); - // if there is a lexical 'this' in the import call arguments, ensure we indicate - // that this new function expression indicates it captures 'this' so that the - // es2015 transformer will properly substitute 'this' with '_this'. - if (containsLexicalThis) { - ts.setEmitFlags(func, 8 /* EmitFlags.CapturesThis */); - } } - return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + var downleveledImport = factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + return temp === undefined ? downleveledImport : factory.createCommaListExpression([factory.createAssignment(temp, arg), downleveledImport]); } function getHelperExpressionForExport(node, innerExpr) { if (!ts.getESModuleInterop(compilerOptions) || ts.getEmitFlags(node) & 67108864 /* EmitFlags.NeverApplyImportHelper */) { @@ -107242,7 +108283,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 237 /* SyntaxKind.VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 240 /* SyntaxKind.VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -107297,10 +108338,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 268 /* SyntaxKind.NamespaceImport */: + case 271 /* SyntaxKind.NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 269 /* SyntaxKind.NamedImports */: + case 272 /* SyntaxKind.NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true); @@ -107384,7 +108425,7 @@ var ts; return statements; } if (ts.hasSyntacticModifier(decl, 1 /* ModifierFlags.Export */)) { - var exportName = ts.hasSyntacticModifier(decl, 512 /* ModifierFlags.Default */) ? factory.createIdentifier("default") : factory.getDeclarationName(decl); + var exportName = ts.hasSyntacticModifier(decl, 1024 /* ModifierFlags.Default */) ? factory.createIdentifier("default") : factory.getDeclarationName(decl); statements = appendExportStatement(statements, exportName, factory.getLocalName(decl), /*location*/ decl); } if (decl.name) { @@ -107513,7 +108554,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 305 /* SyntaxKind.SourceFile */) { + if (node.kind === 308 /* SyntaxKind.SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; previousOnEmitNode(hint, node, emitCallback); @@ -107575,11 +108616,11 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: return substituteExpressionIdentifier(node); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return substituteCallExpression(node); - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: return substituteTaggedTemplateExpression(node); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return substituteBinaryExpression(node); } return node; @@ -107623,7 +108664,7 @@ var ts; } else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* GeneratedIdentifierFlags.AllowNameSubstitution */)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 305 /* SyntaxKind.SourceFile */) { + if (exportContainer && exportContainer.kind === 308 /* SyntaxKind.SourceFile */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), /*location*/ node); } @@ -107713,10 +108754,10 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(79 /* SyntaxKind.Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(297 /* SyntaxKind.ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(221 /* SyntaxKind.BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(231 /* SyntaxKind.MetaProperty */); // Substitutes 'import.meta' - context.enableEmitNotification(305 /* SyntaxKind.SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(300 /* SyntaxKind.ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(223 /* SyntaxKind.BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(233 /* SyntaxKind.MetaProperty */); // Substitutes 'import.meta' + context.enableEmitNotification(308 /* SyntaxKind.SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -107906,7 +108947,7 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var modifiers = node.transformFlags & 2097152 /* TransformFlags.ContainsAwait */ ? - factory.createModifiersFromModifierFlags(256 /* ModifierFlags.Async */) : + factory.createModifiersFromModifierFlags(512 /* ModifierFlags.Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ factory.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -107940,7 +108981,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 272 /* SyntaxKind.ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 275 /* SyntaxKind.ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -108029,19 +109070,26 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName))); + if (ts.hasSyntacticModifier(entry, 1 /* ModifierFlags.Export */)) { + statements.push(factory.createExpressionStatement(factory.createCallExpression(exportFunction, + /*typeArguments*/ undefined, [ + factory.createStringLiteral(ts.idText(importVariableName)), + parameterName, + ]))); + } break; - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { if (ts.isNamedExports(entry.exportClause)) { @@ -108100,13 +109148,13 @@ var ts; */ function topLevelVisitor(node) { switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return visitImportDeclaration(node); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: return visitExportDeclaration(node); - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: return visitExportAssignment(node); default: return topLevelNestedVisitor(node); @@ -108285,7 +109333,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* EmitFlags.NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 305 /* SyntaxKind.SourceFile */ + && (enclosingBlockScopedContainer.kind === 308 /* SyntaxKind.SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* NodeFlags.BlockScoped */) === 0); } /** @@ -108349,7 +109397,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 237 /* SyntaxKind.VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 240 /* SyntaxKind.VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1 /* ModifierFlags.Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -108411,10 +109459,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 268 /* SyntaxKind.NamespaceImport */: + case 271 /* SyntaxKind.NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 269 /* SyntaxKind.NamedImports */: + case 272 /* SyntaxKind.NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -108509,7 +109557,7 @@ var ts; } var excludeName; if (ts.hasSyntacticModifier(decl, 1 /* ModifierFlags.Export */)) { - var exportName = ts.hasSyntacticModifier(decl, 512 /* ModifierFlags.Default */) ? factory.createStringLiteral("default") : decl.name; + var exportName = ts.hasSyntacticModifier(decl, 1024 /* ModifierFlags.Default */) ? factory.createStringLiteral("default") : decl.name; statements = appendExportStatement(statements, exportName, factory.getLocalName(decl)); excludeName = ts.getTextOfIdentifierOrLiteral(exportName); } @@ -108594,43 +109642,43 @@ var ts; */ function topLevelNestedVisitor(node) { switch (node.kind) { - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return visitVariableStatement(node); - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return visitFunctionDeclaration(node); - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: return visitClassDeclaration(node); - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return visitForStatement(node, /*isTopLevel*/ true); - case 243 /* SyntaxKind.ForInStatement */: + case 246 /* SyntaxKind.ForInStatement */: return visitForInStatement(node); - case 244 /* SyntaxKind.ForOfStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return visitForOfStatement(node); - case 240 /* SyntaxKind.DoStatement */: + case 243 /* SyntaxKind.DoStatement */: return visitDoStatement(node); - case 241 /* SyntaxKind.WhileStatement */: + case 244 /* SyntaxKind.WhileStatement */: return visitWhileStatement(node); - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: return visitLabeledStatement(node); - case 248 /* SyntaxKind.WithStatement */: + case 251 /* SyntaxKind.WithStatement */: return visitWithStatement(node); - case 249 /* SyntaxKind.SwitchStatement */: + case 252 /* SyntaxKind.SwitchStatement */: return visitSwitchStatement(node); - case 263 /* SyntaxKind.CaseBlock */: + case 266 /* SyntaxKind.CaseBlock */: return visitCaseBlock(node); - case 289 /* SyntaxKind.CaseClause */: + case 292 /* SyntaxKind.CaseClause */: return visitCaseClause(node); - case 290 /* SyntaxKind.DefaultClause */: + case 293 /* SyntaxKind.DefaultClause */: return visitDefaultClause(node); - case 252 /* SyntaxKind.TryStatement */: + case 255 /* SyntaxKind.TryStatement */: return visitTryStatement(node); - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return visitCatchClause(node); - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: return visitBlock(node); - case 352 /* SyntaxKind.MergeDeclarationMarker */: + case 355 /* SyntaxKind.MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 353 /* SyntaxKind.EndOfDeclarationMarker */: + case 356 /* SyntaxKind.EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return visitor(node); @@ -108816,26 +109864,26 @@ var ts; return node; } switch (node.kind) { - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return visitForStatement(node, /*isTopLevel*/ false); - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: return visitExpressionStatement(node); - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return visitParenthesizedExpression(node, valueIsDiscarded); - case 350 /* SyntaxKind.PartiallyEmittedExpression */: + case 353 /* SyntaxKind.PartiallyEmittedExpression */: return visitPartiallyEmittedExpression(node, valueIsDiscarded); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node, valueIsDiscarded); } break; - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: if (ts.isImportCall(node)) { return visitImportCallExpression(node); } break; - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: return visitPrefixOrPostfixUnaryExpression(node, valueIsDiscarded); } return ts.visitEachChild(node, visitor, context); @@ -108915,7 +109963,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 305 /* SyntaxKind.SourceFile */; + return container !== undefined && container.kind === 308 /* SyntaxKind.SourceFile */; } else { return false; @@ -108993,7 +110041,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 305 /* SyntaxKind.SourceFile */) { + if (node.kind === 308 /* SyntaxKind.SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -109043,7 +110091,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -109080,9 +110128,9 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: return substituteExpressionIdentifier(node); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return substituteBinaryExpression(node); - case 231 /* SyntaxKind.MetaProperty */: + case 233 /* SyntaxKind.MetaProperty */: return substituteMetaProperty(node); } return node; @@ -109172,7 +110220,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 305 /* SyntaxKind.SourceFile */) { + if (exportContainer && exportContainer.kind === 308 /* SyntaxKind.SourceFile */) { exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -109215,7 +110263,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(305 /* SyntaxKind.SourceFile */); + context.enableEmitNotification(308 /* SyntaxKind.SourceFile */); context.enableSubstitution(79 /* SyntaxKind.Identifier */); var helperNameSubstitutions; var currentSourceFile; @@ -109255,14 +110303,14 @@ var ts; } function visitor(node) { switch (node.kind) { - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: // Though an error in es2020 modules, in node-flavor es2020 modules, we can helpfully transform this to a synthetic `require` call // To give easy access to a synchronous `require` in node-flavor esm. We do the transform even in scenarios where we error, but `import.meta.url` // is available, just because the output is reasonable for a node-like runtime. return ts.getEmitModuleKind(compilerOptions) >= ts.ModuleKind.Node16 ? visitImportEqualsDeclaration(node) : undefined; - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: return visitExportAssignment(node); - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: var exportDecl = node; return visitExportDeclaration(exportDecl); } @@ -109419,8 +110467,8 @@ var ts; var cjsOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(305 /* SyntaxKind.SourceFile */); - context.enableEmitNotification(305 /* SyntaxKind.SourceFile */); + context.enableSubstitution(308 /* SyntaxKind.SourceFile */); + context.enableEmitNotification(308 /* SyntaxKind.SourceFile */); var currentSourceFile; return transformSourceFileOrBundle; function onSubstituteNode(hint, node) { @@ -109467,7 +110515,7 @@ var ts; return result; } function transformSourceFileOrBundle(node) { - return node.kind === 305 /* SyntaxKind.SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 308 /* SyntaxKind.SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -109527,7 +110575,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 257 /* SyntaxKind.ClassDeclaration */) { + else if (node.parent.kind === 260 /* SyntaxKind.ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -109556,7 +110604,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 257 /* SyntaxKind.ClassDeclaration */) { + else if (node.parent.kind === 260 /* SyntaxKind.ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -109603,7 +110651,7 @@ var ts; return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(node.kind))); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 254 /* SyntaxKind.VariableDeclaration */ || node.kind === 203 /* SyntaxKind.BindingElement */) { + if (node.kind === 257 /* SyntaxKind.VariableDeclaration */ || node.kind === 205 /* SyntaxKind.BindingElement */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -109612,8 +110660,8 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 167 /* SyntaxKind.PropertyDeclaration */ || node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ || node.kind === 166 /* SyntaxKind.PropertySignature */ || - (node.kind === 164 /* SyntaxKind.Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* ModifierFlags.Private */))) { + else if (node.kind === 169 /* SyntaxKind.PropertyDeclaration */ || node.kind === 208 /* SyntaxKind.PropertyAccessExpression */ || node.kind === 168 /* SyntaxKind.PropertySignature */ || + (node.kind === 166 /* SyntaxKind.Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* ModifierFlags.Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.isStatic(node)) { return symbolAccessibilityResult.errorModuleName ? @@ -109622,7 +110670,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 257 /* SyntaxKind.ClassDeclaration */ || node.kind === 164 /* SyntaxKind.Parameter */) { + else if (node.parent.kind === 260 /* SyntaxKind.ClassDeclaration */ || node.kind === 166 /* SyntaxKind.Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -109647,7 +110695,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 173 /* SyntaxKind.SetAccessor */) { + if (node.kind === 175 /* SyntaxKind.SetAccessor */) { // Getters can infer the return type from the returned expression, but setters cannot, so the // "_from_external_module_1_but_cannot_be_named" case cannot occur. if (ts.isStatic(node)) { @@ -109686,26 +110734,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 175 /* SyntaxKind.ConstructSignature */: + case 177 /* SyntaxKind.ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 174 /* SyntaxKind.CallSignature */: + case 176 /* SyntaxKind.CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 176 /* SyntaxKind.IndexSignature */: + case 178 /* SyntaxKind.IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: if (ts.isStatic(node)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? @@ -109713,7 +110761,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 257 /* SyntaxKind.ClassDeclaration */) { + else if (node.parent.kind === 260 /* SyntaxKind.ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -109727,7 +110775,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -109752,30 +110800,30 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 175 /* SyntaxKind.ConstructSignature */: - case 180 /* SyntaxKind.ConstructorType */: + case 177 /* SyntaxKind.ConstructSignature */: + case 182 /* SyntaxKind.ConstructorType */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 174 /* SyntaxKind.CallSignature */: + case 176 /* SyntaxKind.CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 176 /* SyntaxKind.IndexSignature */: + case 178 /* SyntaxKind.IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: if (ts.isStatic(node.parent)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? @@ -109783,7 +110831,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 257 /* SyntaxKind.ClassDeclaration */) { + else if (node.parent.parent.kind === 260 /* SyntaxKind.ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -109796,15 +110844,15 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 256 /* SyntaxKind.FunctionDeclaration */: - case 179 /* SyntaxKind.FunctionType */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 181 /* SyntaxKind.FunctionType */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - case 173 /* SyntaxKind.SetAccessor */: - case 172 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* SymbolAccessibility.CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -109818,39 +110866,39 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 195 /* SyntaxKind.MappedType */: + case 197 /* SyntaxKind.MappedType */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1; break; - case 180 /* SyntaxKind.ConstructorType */: - case 175 /* SyntaxKind.ConstructSignature */: + case 182 /* SyntaxKind.ConstructorType */: + case 177 /* SyntaxKind.ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 174 /* SyntaxKind.CallSignature */: + case 176 /* SyntaxKind.CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: if (ts.isStatic(node.parent)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 257 /* SyntaxKind.ClassDeclaration */) { + else if (node.parent.parent.kind === 260 /* SyntaxKind.ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 179 /* SyntaxKind.FunctionType */: - case 256 /* SyntaxKind.FunctionDeclaration */: + case 181 /* SyntaxKind.FunctionType */: + case 259 /* SyntaxKind.FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -109916,7 +110964,7 @@ var ts; } function isInternalDeclaration(node, currentSourceFile) { var parseTreeNode = ts.getParseTreeNode(node); - if (parseTreeNode && parseTreeNode.kind === 164 /* SyntaxKind.Parameter */) { + if (parseTreeNode && parseTreeNode.kind === 166 /* SyntaxKind.Parameter */) { var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined; var text = currentSourceFile.text; @@ -110092,7 +111140,7 @@ var ts; var _a; var primaryDeclaration = (_a = parentSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); - if (augmentingDeclarations) { + if (primaryDeclaration && augmentingDeclarations) { for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { var augmentations = augmentingDeclarations_1[_i]; context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); @@ -110122,10 +111170,10 @@ var ts; return result; } function transformRoot(node) { - if (node.kind === 305 /* SyntaxKind.SourceFile */ && node.isDeclarationFile) { + if (node.kind === 308 /* SyntaxKind.SourceFile */ && node.isDeclarationFile) { return node; } - if (node.kind === 306 /* SyntaxKind.Bundle */) { + if (node.kind === 309 /* SyntaxKind.Bundle */) { isBundledEmit = true; refs = new ts.Map(); libs = new ts.Map(); @@ -110148,14 +111196,14 @@ var ts; resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([factory.createModifier(136 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 308 /* SyntaxKind.InputFiles */) { + if (prepend.kind === 311 /* SyntaxKind.InputFiles */) { var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal); hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib; collectReferences(sourceFile, refs); @@ -110296,7 +111344,7 @@ var ts; return name; } else { - if (name.kind === 202 /* SyntaxKind.ArrayBindingPattern */) { + if (name.kind === 204 /* SyntaxKind.ArrayBindingPattern */) { return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -110304,7 +111352,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 227 /* SyntaxKind.OmittedExpression */) { + if (elem.kind === 229 /* SyntaxKind.OmittedExpression */) { return elem; } if (elem.propertyName && ts.isIdentifier(elem.propertyName) && ts.isIdentifier(elem.name) && !elem.symbol.isReferenced) { @@ -110346,19 +111394,19 @@ var ts; // Literal const declarations will have an initializer ensured rather than a type return; } - var shouldUseResolverType = node.kind === 164 /* SyntaxKind.Parameter */ && + var shouldUseResolverType = node.kind === 166 /* SyntaxKind.Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { return ts.visitNode(type, visitDeclarationSubtree); } if (!ts.getParseTreeNode(node)) { - return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */); + return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */); } - if (node.kind === 173 /* SyntaxKind.SetAccessor */) { + if (node.kind === 175 /* SyntaxKind.SetAccessor */) { // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) - return factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */); + return factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */); } errorNameNode = node.name; var oldDiag; @@ -110366,12 +111414,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 254 /* SyntaxKind.VariableDeclaration */ || node.kind === 203 /* SyntaxKind.BindingElement */) { + if (node.kind === 257 /* SyntaxKind.VariableDeclaration */ || node.kind === 205 /* SyntaxKind.BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 164 /* SyntaxKind.Parameter */ - || node.kind === 167 /* SyntaxKind.PropertyDeclaration */ - || node.kind === 166 /* SyntaxKind.PropertySignature */) { + if (node.kind === 166 /* SyntaxKind.Parameter */ + || node.kind === 169 /* SyntaxKind.PropertyDeclaration */ + || node.kind === 168 /* SyntaxKind.PropertySignature */) { if (ts.isPropertySignature(node) || !node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -110382,28 +111430,28 @@ var ts; if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; } - return returnValue || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */); + return returnValue || factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */); } } function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return !getBindingNameVisible(node); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 266 /* SyntaxKind.ImportDeclaration */: - case 272 /* SyntaxKind.ExportDeclaration */: - case 271 /* SyntaxKind.ExportAssignment */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: + case 274 /* SyntaxKind.ExportAssignment */: return false; - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: return true; } return false; @@ -110492,7 +111540,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 261 /* SyntaxKind.ModuleDeclaration */ && parent.kind !== 200 /* SyntaxKind.ImportType */); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 264 /* SyntaxKind.ModuleDeclaration */ && parent.kind !== 202 /* SyntaxKind.ImportType */); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -110512,7 +111560,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */) { + if (decl.moduleReference.kind === 280 /* SyntaxKind.ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return factory.updateImportEqualsDeclaration(decl, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); @@ -110537,7 +111585,7 @@ var ts; return visibleDefaultBinding && factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } - if (decl.importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; @@ -110640,7 +111688,7 @@ var ts; // We'd see a TDZ violation at runtime var canProduceDiagnostic = ts.canProduceDiagnostics(input); var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 182 /* SyntaxKind.TypeLiteral */ || input.kind === 195 /* SyntaxKind.MappedType */) && input.parent.kind !== 259 /* SyntaxKind.TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 184 /* SyntaxKind.TypeLiteral */ || input.kind === 197 /* SyntaxKind.MappedType */) && input.parent.kind !== 262 /* SyntaxKind.TypeAliasDeclaration */); // Emit methods which are private as properties with no type information if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { if (ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)) { @@ -110661,28 +111709,28 @@ var ts; } if (isProcessedComponent(input)) { switch (input.kind) { - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: { + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments)); } - case 178 /* SyntaxKind.TypeReference */: { + case 180 /* SyntaxKind.TypeReference */: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments)); } - case 175 /* SyntaxKind.ConstructSignature */: + case 177 /* SyntaxKind.ConstructSignature */: return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 171 /* SyntaxKind.Constructor */: { + case 173 /* SyntaxKind.Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* ModifierFlags.None */), /*body*/ undefined); return cleanup(ctor); } - case 169 /* SyntaxKind.MethodDeclaration */: { + case 171 /* SyntaxKind.MethodDeclaration */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -110691,7 +111739,7 @@ var ts; /*body*/ undefined); return cleanup(sig); } - case 172 /* SyntaxKind.GetAccessor */: { + case 174 /* SyntaxKind.GetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -110699,36 +111747,36 @@ var ts; return cleanup(factory.updateGetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), /*body*/ undefined)); } - case 173 /* SyntaxKind.SetAccessor */: { + case 175 /* SyntaxKind.SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updateSetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), /*body*/ undefined)); } - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertyDeclaration(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); - case 166 /* SyntaxKind.PropertySignature */: + case 168 /* SyntaxKind.PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type))); - case 168 /* SyntaxKind.MethodSignature */: { + case 170 /* SyntaxKind.MethodSignature */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 174 /* SyntaxKind.CallSignature */: { + case 176 /* SyntaxKind.CallSignature */: { return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 176 /* SyntaxKind.IndexSignature */: { - return cleanup(factory.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); + case 178 /* SyntaxKind.IndexSignature */: { + return cleanup(factory.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */))); } - case 254 /* SyntaxKind.VariableDeclaration */: { + case 257 /* SyntaxKind.VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -110736,13 +111784,13 @@ var ts; suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types return cleanup(factory.updateVariableDeclaration(input, input.name, /*exclamationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input))); } - case 163 /* SyntaxKind.TypeParameter */: { + case 165 /* SyntaxKind.TypeParameter */: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(factory.updateTypeParameterDeclaration(input, input.modifiers, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 189 /* SyntaxKind.ConditionalType */: { + case 191 /* SyntaxKind.ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -110754,13 +111802,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 179 /* SyntaxKind.FunctionType */: { + case 181 /* SyntaxKind.FunctionType */: { return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 180 /* SyntaxKind.ConstructorType */: { + case 182 /* SyntaxKind.ConstructorType */: { return cleanup(factory.updateConstructorTypeNode(input, ensureModifiers(input), ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 200 /* SyntaxKind.ImportType */: { + case 202 /* SyntaxKind.ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.assertions, input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -110792,7 +111840,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 169 /* SyntaxKind.MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* ModifierFlags.Private */); + return node.parent.kind === 171 /* SyntaxKind.MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* ModifierFlags.Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -110802,7 +111850,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 272 /* SyntaxKind.ExportDeclaration */: { + case 275 /* SyntaxKind.ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; } @@ -110811,7 +111859,7 @@ var ts; // Rewrite external module names if necessary return factory.updateExportDeclaration(input, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); } - case 271 /* SyntaxKind.ExportAssignment */: { + case 274 /* SyntaxKind.ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; @@ -110829,7 +111877,7 @@ var ts; errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); errorFallbackNode = undefined; - var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* NodeFlags.Const */)); + var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(136 /* SyntaxKind.DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* NodeFlags.Const */)); preserveJsDoc(statement, input); ts.removeAllComments(input); return [statement, factory.updateExportAssignment(input, input.modifiers, newId)]; @@ -110842,12 +111890,12 @@ var ts; return input; } function stripExportModifiers(statement) { - if (ts.isImportEqualsDeclaration(statement) || ts.hasEffectiveModifier(statement, 512 /* ModifierFlags.Default */) || !ts.canHaveModifiers(statement)) { + if (ts.isImportEqualsDeclaration(statement) || ts.hasEffectiveModifier(statement, 1024 /* ModifierFlags.Default */) || !ts.canHaveModifiers(statement)) { // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (257023 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (258047 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { @@ -110858,10 +111906,10 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 265 /* SyntaxKind.ImportEqualsDeclaration */: { + case 268 /* SyntaxKind.ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 266 /* SyntaxKind.ImportDeclaration */: { + case 269 /* SyntaxKind.ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -110882,12 +111930,16 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 259 /* SyntaxKind.TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all - return cleanup(factory.updateTypeAliasDeclaration(input, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 258 /* SyntaxKind.InterfaceDeclaration */: { + case 262 /* SyntaxKind.TypeAliasDeclaration */: { + needsDeclare = false; + var clean = cleanup(factory.updateTypeAliasDeclaration(input, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + needsDeclare = previousNeedsDeclare; + return clean; + } + case 261 /* SyntaxKind.InterfaceDeclaration */: { return cleanup(factory.updateInterfaceDeclaration(input, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 256 /* SyntaxKind.FunctionDeclaration */: { + case 259 /* SyntaxKind.FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type var clean = cleanup(factory.updateFunctionDeclaration(input, ensureModifiers(input), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), @@ -110928,10 +111980,10 @@ var ts; })))); } var namespaceDecl = factory.createModuleDeclaration(ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); - if (!ts.hasEffectiveModifier(clean, 512 /* ModifierFlags.Default */)) { + if (!ts.hasEffectiveModifier(clean, 1024 /* ModifierFlags.Default */)) { return [clean, namespaceDecl]; } - var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ModifierFlags.ExportDefault */) | 2 /* ModifierFlags.Ambient */); + var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~1025 /* ModifierFlags.ExportDefault */) | 2 /* ModifierFlags.Ambient */); var cleanDeclaration = factory.updateFunctionDeclaration(clean, modifiers, /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, /*body*/ undefined); @@ -110949,10 +112001,10 @@ var ts; return clean; } } - case 261 /* SyntaxKind.ModuleDeclaration */: { + case 264 /* SyntaxKind.ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 262 /* SyntaxKind.ModuleBlock */) { + if (inner && inner.kind === 265 /* SyntaxKind.ModuleBlock */) { var oldNeedsScopeFix = needsScopeFixMarker; var oldHasScopeFix = resultHasScopeMarker; resultHasScopeMarker = false; @@ -110993,7 +112045,7 @@ var ts; return cleanup(factory.updateModuleDeclaration(input, mods, input.name, body)); } } - case 257 /* SyntaxKind.ClassDeclaration */: { + case 260 /* SyntaxKind.ClassDeclaration */: { errorNameNode = input.name; errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); @@ -111055,7 +112107,7 @@ var ts; typeName: input.name }); }; var varDecl = factory.createVariableDeclaration(newId_1, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); - var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* NodeFlags.Const */)); + var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(136 /* SyntaxKind.DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* NodeFlags.Const */)); var heritageClauses = factory.createNodeArray(ts.map(input.heritageClauses, function (clause) { if (clause.token === 94 /* SyntaxKind.ExtendsKeyword */) { var oldDiag_2 = getSymbolAccessibilityDiagnostic; @@ -111073,10 +112125,10 @@ var ts; return cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 237 /* SyntaxKind.VariableStatement */: { + case 240 /* SyntaxKind.VariableStatement */: { return cleanup(transformVariableStatement(input)); } - case 260 /* SyntaxKind.EnumDeclaration */: { + case 263 /* SyntaxKind.EnumDeclaration */: { return cleanup(factory.updateEnumDeclaration(input, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -111095,7 +112147,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 261 /* SyntaxKind.ModuleDeclaration */) { + if (input.kind === 264 /* SyntaxKind.ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -111118,7 +112170,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 227 /* SyntaxKind.OmittedExpression */) { + if (e.kind === 229 /* SyntaxKind.OmittedExpression */) { return; } if (e.name) { @@ -111166,9 +112218,9 @@ var ts; return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 257023 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files + var mask = 258047 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 512 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* ModifierFlags.Ambient */ : 0 /* ModifierFlags.None */; - var parentIsFile = node.parent.kind === 305 /* SyntaxKind.SourceFile */; + var parentIsFile = node.parent.kind === 308 /* SyntaxKind.SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= 2 /* ModifierFlags.Ambient */; additions = 0 /* ModifierFlags.None */; @@ -111197,7 +112249,7 @@ var ts; } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 258 /* SyntaxKind.InterfaceDeclaration */) { + if (node.kind === 261 /* SyntaxKind.InterfaceDeclaration */) { return true; } return false; @@ -111207,22 +112259,22 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 257023 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } + if (modifierMask === void 0) { modifierMask = 258047 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* ModifierFlags.None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; - if (flags & 512 /* ModifierFlags.Default */ && !(flags & 1 /* ModifierFlags.Export */)) { + if (flags & 1024 /* ModifierFlags.Default */ && !(flags & 1 /* ModifierFlags.Export */)) { // A non-exported default is a nonsequitor - we usually try to remove all export modifiers // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid flags ^= 1 /* ModifierFlags.Export */; } - if (flags & 512 /* ModifierFlags.Default */ && flags & 2 /* ModifierFlags.Ambient */) { + if (flags & 1024 /* ModifierFlags.Default */ && flags & 2 /* ModifierFlags.Ambient */) { flags ^= 2 /* ModifierFlags.Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) } return flags; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 172 /* SyntaxKind.GetAccessor */ + return accessor.kind === 174 /* SyntaxKind.GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -111231,52 +112283,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: return !ts.hasEffectiveModifier(node, 8 /* ModifierFlags.Private */); - case 164 /* SyntaxKind.Parameter */: - case 254 /* SyntaxKind.VariableDeclaration */: + case 166 /* SyntaxKind.Parameter */: + case 257 /* SyntaxKind.VariableDeclaration */: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 237 /* SyntaxKind.VariableStatement */: - case 266 /* SyntaxKind.ImportDeclaration */: - case 272 /* SyntaxKind.ExportDeclaration */: - case 271 /* SyntaxKind.ExportAssignment */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 240 /* SyntaxKind.VariableStatement */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: + case 274 /* SyntaxKind.ExportAssignment */: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 175 /* SyntaxKind.ConstructSignature */: - case 171 /* SyntaxKind.Constructor */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 168 /* SyntaxKind.MethodSignature */: - case 174 /* SyntaxKind.CallSignature */: - case 176 /* SyntaxKind.IndexSignature */: - case 254 /* SyntaxKind.VariableDeclaration */: - case 163 /* SyntaxKind.TypeParameter */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: - case 178 /* SyntaxKind.TypeReference */: - case 189 /* SyntaxKind.ConditionalType */: - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 200 /* SyntaxKind.ImportType */: + case 177 /* SyntaxKind.ConstructSignature */: + case 173 /* SyntaxKind.Constructor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 170 /* SyntaxKind.MethodSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 178 /* SyntaxKind.IndexSignature */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 165 /* SyntaxKind.TypeParameter */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: + case 180 /* SyntaxKind.TypeReference */: + case 191 /* SyntaxKind.ConditionalType */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: + case 202 /* SyntaxKind.ImportType */: return true; } return false; @@ -111416,7 +112468,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(355 /* SyntaxKind.Count */); + var enabledSyntaxKindFeatures = new Array(358 /* SyntaxKind.Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentStatements; @@ -111498,7 +112550,7 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* tracing.Phase.Emit */, "transformNodes", node.kind === 305 /* SyntaxKind.SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* tracing.Phase.Emit */, "transformNodes", node.kind === 308 /* SyntaxKind.SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -111904,7 +112956,7 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 306 /* SyntaxKind.Bundle */) { + if (sourceFile.kind === 309 /* SyntaxKind.Bundle */) { return getOutputPathsForBundle(options, forceDtsPaths); } else { @@ -112273,8 +113325,8 @@ var ts; } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, mapOptions) { var sourceFileOrBundle = transform.transformed[0]; - var bundle = sourceFileOrBundle.kind === 306 /* SyntaxKind.Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 305 /* SyntaxKind.SourceFile */ ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 309 /* SyntaxKind.Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 308 /* SyntaxKind.SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; var sourceMapGenerator; if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { @@ -112324,7 +113376,7 @@ var ts; } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { return (mapOptions.sourceMap || mapOptions.inlineSourceMap) - && (sourceFileOrBundle.kind !== 305 /* SyntaxKind.SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Extension.Json */)); + && (sourceFileOrBundle.kind !== 308 /* SyntaxKind.SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Extension.Json */)); } function getSourceRoot(mapOptions) { // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the @@ -112387,8 +113439,8 @@ var ts; } ts.getBuildInfoText = getBuildInfoText; /*@internal*/ - function getBuildInfo(buildInfoText) { - return JSON.parse(buildInfoText); + function getBuildInfo(buildInfoFile, buildInfoText) { + return ts.readJsonOrUndefined(buildInfoFile, buildInfoText); } ts.getBuildInfo = getBuildInfo; /*@internal*/ @@ -112466,17 +113518,16 @@ var ts; var buildInfo; if (host.getBuildInfo) { // If host directly provides buildinfo we can get it directly. This allows host to cache the buildinfo - var hostBuildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); - if (!hostBuildInfo) - return buildInfoPath; - buildInfo = hostBuildInfo; + buildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); } else { var buildInfoText = host.readFile(buildInfoPath); if (!buildInfoText) return buildInfoPath; - buildInfo = getBuildInfo(buildInfoText); + buildInfo = getBuildInfo(buildInfoPath, buildInfoText); } + if (!buildInfo) + return buildInfoPath; if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationFilePath && !buildInfo.bundle.dts)) return buildInfoPath; var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath)); @@ -112602,6 +113653,10 @@ var ts; var nodeIdToGeneratedName; // Map of generated names for specific nodes. var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. var generatedNames; // Set of names generated by the NameGenerator. + var formattedNameTempFlagsStack; + var formattedNameTempFlags; + var privateNameTempFlagsStack; // Stack of enclosing name generation scopes. + var privateNameTempFlags; // TempFlags for the current name generation scope. var tempFlagsStack; // Stack of enclosing name generation scopes. var tempFlags; // TempFlags for the current name generation scope. var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. @@ -112667,9 +113722,9 @@ var ts; break; } switch (node.kind) { - case 305 /* SyntaxKind.SourceFile */: return printFile(node); - case 306 /* SyntaxKind.Bundle */: return printBundle(node); - case 307 /* SyntaxKind.UnparsedSource */: return printUnparsedSource(node); + case 308 /* SyntaxKind.SourceFile */: return printFile(node); + case 309 /* SyntaxKind.Bundle */: return printBundle(node); + case 310 /* SyntaxKind.UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -112860,6 +113915,10 @@ var ts; nodeIdToGeneratedName = []; autoGeneratedIdToGeneratedName = []; generatedNames = new ts.Set(); + formattedNameTempFlagsStack = []; + formattedNameTempFlags = new ts.Map(); + privateNameTempFlagsStack = []; + privateNameTempFlags = 0 /* TempFlags.Auto */; tempFlagsStack = []; tempFlags = 0 /* TempFlags.Auto */; reservedNamesStack = []; @@ -113003,315 +114062,315 @@ var ts; return emitPrivateIdentifier(node); // Parse tree nodes // Names - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: return emitQualifiedName(node); - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 163 /* SyntaxKind.TypeParameter */: + case 165 /* SyntaxKind.TypeParameter */: return emitTypeParameter(node); - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return emitParameter(node); - case 165 /* SyntaxKind.Decorator */: + case 167 /* SyntaxKind.Decorator */: return emitDecorator(node); // Type members - case 166 /* SyntaxKind.PropertySignature */: + case 168 /* SyntaxKind.PropertySignature */: return emitPropertySignature(node); - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: return emitPropertyDeclaration(node); - case 168 /* SyntaxKind.MethodSignature */: + case 170 /* SyntaxKind.MethodSignature */: return emitMethodSignature(node); - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: return emitMethodDeclaration(node); - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: return emitClassStaticBlockDeclaration(node); - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return emitConstructor(node); - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return emitAccessorDeclaration(node); - case 174 /* SyntaxKind.CallSignature */: + case 176 /* SyntaxKind.CallSignature */: return emitCallSignature(node); - case 175 /* SyntaxKind.ConstructSignature */: + case 177 /* SyntaxKind.ConstructSignature */: return emitConstructSignature(node); - case 176 /* SyntaxKind.IndexSignature */: + case 178 /* SyntaxKind.IndexSignature */: return emitIndexSignature(node); // Types - case 177 /* SyntaxKind.TypePredicate */: + case 179 /* SyntaxKind.TypePredicate */: return emitTypePredicate(node); - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return emitTypeReference(node); - case 179 /* SyntaxKind.FunctionType */: + case 181 /* SyntaxKind.FunctionType */: return emitFunctionType(node); - case 180 /* SyntaxKind.ConstructorType */: + case 182 /* SyntaxKind.ConstructorType */: return emitConstructorType(node); - case 181 /* SyntaxKind.TypeQuery */: + case 183 /* SyntaxKind.TypeQuery */: return emitTypeQuery(node); - case 182 /* SyntaxKind.TypeLiteral */: + case 184 /* SyntaxKind.TypeLiteral */: return emitTypeLiteral(node); - case 183 /* SyntaxKind.ArrayType */: + case 185 /* SyntaxKind.ArrayType */: return emitArrayType(node); - case 184 /* SyntaxKind.TupleType */: + case 186 /* SyntaxKind.TupleType */: return emitTupleType(node); - case 185 /* SyntaxKind.OptionalType */: + case 187 /* SyntaxKind.OptionalType */: return emitOptionalType(node); // SyntaxKind.RestType is handled below - case 187 /* SyntaxKind.UnionType */: + case 189 /* SyntaxKind.UnionType */: return emitUnionType(node); - case 188 /* SyntaxKind.IntersectionType */: + case 190 /* SyntaxKind.IntersectionType */: return emitIntersectionType(node); - case 189 /* SyntaxKind.ConditionalType */: + case 191 /* SyntaxKind.ConditionalType */: return emitConditionalType(node); - case 190 /* SyntaxKind.InferType */: + case 192 /* SyntaxKind.InferType */: return emitInferType(node); - case 191 /* SyntaxKind.ParenthesizedType */: + case 193 /* SyntaxKind.ParenthesizedType */: return emitParenthesizedType(node); - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 192 /* SyntaxKind.ThisType */: + case 194 /* SyntaxKind.ThisType */: return emitThisType(); - case 193 /* SyntaxKind.TypeOperator */: + case 195 /* SyntaxKind.TypeOperator */: return emitTypeOperator(node); - case 194 /* SyntaxKind.IndexedAccessType */: + case 196 /* SyntaxKind.IndexedAccessType */: return emitIndexedAccessType(node); - case 195 /* SyntaxKind.MappedType */: + case 197 /* SyntaxKind.MappedType */: return emitMappedType(node); - case 196 /* SyntaxKind.LiteralType */: + case 198 /* SyntaxKind.LiteralType */: return emitLiteralType(node); - case 197 /* SyntaxKind.NamedTupleMember */: + case 199 /* SyntaxKind.NamedTupleMember */: return emitNamedTupleMember(node); - case 198 /* SyntaxKind.TemplateLiteralType */: + case 200 /* SyntaxKind.TemplateLiteralType */: return emitTemplateType(node); - case 199 /* SyntaxKind.TemplateLiteralTypeSpan */: + case 201 /* SyntaxKind.TemplateLiteralTypeSpan */: return emitTemplateTypeSpan(node); - case 200 /* SyntaxKind.ImportType */: + case 202 /* SyntaxKind.ImportType */: return emitImportTypeNode(node); // Binding patterns - case 201 /* SyntaxKind.ObjectBindingPattern */: + case 203 /* SyntaxKind.ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 202 /* SyntaxKind.ArrayBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: return emitBindingElement(node); // Misc - case 233 /* SyntaxKind.TemplateSpan */: + case 236 /* SyntaxKind.TemplateSpan */: return emitTemplateSpan(node); - case 234 /* SyntaxKind.SemicolonClassElement */: + case 237 /* SyntaxKind.SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: return emitBlock(node); - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return emitVariableStatement(node); - case 236 /* SyntaxKind.EmptyStatement */: + case 239 /* SyntaxKind.EmptyStatement */: return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: return emitExpressionStatement(node); - case 239 /* SyntaxKind.IfStatement */: + case 242 /* SyntaxKind.IfStatement */: return emitIfStatement(node); - case 240 /* SyntaxKind.DoStatement */: + case 243 /* SyntaxKind.DoStatement */: return emitDoStatement(node); - case 241 /* SyntaxKind.WhileStatement */: + case 244 /* SyntaxKind.WhileStatement */: return emitWhileStatement(node); - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return emitForStatement(node); - case 243 /* SyntaxKind.ForInStatement */: + case 246 /* SyntaxKind.ForInStatement */: return emitForInStatement(node); - case 244 /* SyntaxKind.ForOfStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return emitForOfStatement(node); - case 245 /* SyntaxKind.ContinueStatement */: + case 248 /* SyntaxKind.ContinueStatement */: return emitContinueStatement(node); - case 246 /* SyntaxKind.BreakStatement */: + case 249 /* SyntaxKind.BreakStatement */: return emitBreakStatement(node); - case 247 /* SyntaxKind.ReturnStatement */: + case 250 /* SyntaxKind.ReturnStatement */: return emitReturnStatement(node); - case 248 /* SyntaxKind.WithStatement */: + case 251 /* SyntaxKind.WithStatement */: return emitWithStatement(node); - case 249 /* SyntaxKind.SwitchStatement */: + case 252 /* SyntaxKind.SwitchStatement */: return emitSwitchStatement(node); - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: return emitLabeledStatement(node); - case 251 /* SyntaxKind.ThrowStatement */: + case 254 /* SyntaxKind.ThrowStatement */: return emitThrowStatement(node); - case 252 /* SyntaxKind.TryStatement */: + case 255 /* SyntaxKind.TryStatement */: return emitTryStatement(node); - case 253 /* SyntaxKind.DebuggerStatement */: + case 256 /* SyntaxKind.DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return emitVariableDeclaration(node); - case 255 /* SyntaxKind.VariableDeclarationList */: + case 258 /* SyntaxKind.VariableDeclarationList */: return emitVariableDeclarationList(node); - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return emitFunctionDeclaration(node); - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: return emitClassDeclaration(node); - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return emitEnumDeclaration(node); - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return emitModuleDeclaration(node); - case 262 /* SyntaxKind.ModuleBlock */: + case 265 /* SyntaxKind.ModuleBlock */: return emitModuleBlock(node); - case 263 /* SyntaxKind.CaseBlock */: + case 266 /* SyntaxKind.CaseBlock */: return emitCaseBlock(node); - case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 267 /* SyntaxKind.NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return emitImportDeclaration(node); - case 267 /* SyntaxKind.ImportClause */: + case 270 /* SyntaxKind.ImportClause */: return emitImportClause(node); - case 268 /* SyntaxKind.NamespaceImport */: + case 271 /* SyntaxKind.NamespaceImport */: return emitNamespaceImport(node); - case 274 /* SyntaxKind.NamespaceExport */: + case 277 /* SyntaxKind.NamespaceExport */: return emitNamespaceExport(node); - case 269 /* SyntaxKind.NamedImports */: + case 272 /* SyntaxKind.NamedImports */: return emitNamedImports(node); - case 270 /* SyntaxKind.ImportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: return emitImportSpecifier(node); - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: return emitExportAssignment(node); - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: return emitExportDeclaration(node); - case 273 /* SyntaxKind.NamedExports */: + case 276 /* SyntaxKind.NamedExports */: return emitNamedExports(node); - case 275 /* SyntaxKind.ExportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: return emitExportSpecifier(node); - case 293 /* SyntaxKind.AssertClause */: + case 296 /* SyntaxKind.AssertClause */: return emitAssertClause(node); - case 294 /* SyntaxKind.AssertEntry */: + case 297 /* SyntaxKind.AssertEntry */: return emitAssertEntry(node); - case 276 /* SyntaxKind.MissingDeclaration */: + case 279 /* SyntaxKind.MissingDeclaration */: return; // Module references - case 277 /* SyntaxKind.ExternalModuleReference */: + case 280 /* SyntaxKind.ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) case 11 /* SyntaxKind.JsxText */: return emitJsxText(node); - case 280 /* SyntaxKind.JsxOpeningElement */: - case 283 /* SyntaxKind.JsxOpeningFragment */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 286 /* SyntaxKind.JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 281 /* SyntaxKind.JsxClosingElement */: - case 284 /* SyntaxKind.JsxClosingFragment */: + case 284 /* SyntaxKind.JsxClosingElement */: + case 287 /* SyntaxKind.JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 285 /* SyntaxKind.JsxAttribute */: + case 288 /* SyntaxKind.JsxAttribute */: return emitJsxAttribute(node); - case 286 /* SyntaxKind.JsxAttributes */: + case 289 /* SyntaxKind.JsxAttributes */: return emitJsxAttributes(node); - case 287 /* SyntaxKind.JsxSpreadAttribute */: + case 290 /* SyntaxKind.JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 288 /* SyntaxKind.JsxExpression */: + case 291 /* SyntaxKind.JsxExpression */: return emitJsxExpression(node); // Clauses - case 289 /* SyntaxKind.CaseClause */: + case 292 /* SyntaxKind.CaseClause */: return emitCaseClause(node); - case 290 /* SyntaxKind.DefaultClause */: + case 293 /* SyntaxKind.DefaultClause */: return emitDefaultClause(node); - case 291 /* SyntaxKind.HeritageClause */: + case 294 /* SyntaxKind.HeritageClause */: return emitHeritageClause(node); - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return emitCatchClause(node); // Property assignments - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: return emitPropertyAssignment(node); - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 298 /* SyntaxKind.SpreadAssignment */: + case 301 /* SyntaxKind.SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 299 /* SyntaxKind.EnumMember */: + case 302 /* SyntaxKind.EnumMember */: return emitEnumMember(node); // Unparsed - case 300 /* SyntaxKind.UnparsedPrologue */: + case 303 /* SyntaxKind.UnparsedPrologue */: return writeUnparsedNode(node); - case 307 /* SyntaxKind.UnparsedSource */: - case 301 /* SyntaxKind.UnparsedPrepend */: + case 310 /* SyntaxKind.UnparsedSource */: + case 304 /* SyntaxKind.UnparsedPrepend */: return emitUnparsedSourceOrPrepend(node); - case 302 /* SyntaxKind.UnparsedText */: - case 303 /* SyntaxKind.UnparsedInternalText */: + case 305 /* SyntaxKind.UnparsedText */: + case 306 /* SyntaxKind.UnparsedInternalText */: return emitUnparsedTextLike(node); - case 304 /* SyntaxKind.UnparsedSyntheticReference */: + case 307 /* SyntaxKind.UnparsedSyntheticReference */: return emitUnparsedSyntheticReference(node); // Top-level nodes - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: return emitSourceFile(node); - case 306 /* SyntaxKind.Bundle */: + case 309 /* SyntaxKind.Bundle */: return ts.Debug.fail("Bundles should be printed using printBundle"); // SyntaxKind.UnparsedSource (handled above) - case 308 /* SyntaxKind.InputFiles */: + case 311 /* SyntaxKind.InputFiles */: return ts.Debug.fail("InputFiles should not be printed"); // JSDoc nodes (only used in codefixes currently) - case 309 /* SyntaxKind.JSDocTypeExpression */: + case 312 /* SyntaxKind.JSDocTypeExpression */: return emitJSDocTypeExpression(node); - case 310 /* SyntaxKind.JSDocNameReference */: + case 313 /* SyntaxKind.JSDocNameReference */: return emitJSDocNameReference(node); - case 312 /* SyntaxKind.JSDocAllType */: + case 315 /* SyntaxKind.JSDocAllType */: return writePunctuation("*"); - case 313 /* SyntaxKind.JSDocUnknownType */: + case 316 /* SyntaxKind.JSDocUnknownType */: return writePunctuation("?"); - case 314 /* SyntaxKind.JSDocNullableType */: + case 317 /* SyntaxKind.JSDocNullableType */: return emitJSDocNullableType(node); - case 315 /* SyntaxKind.JSDocNonNullableType */: + case 318 /* SyntaxKind.JSDocNonNullableType */: return emitJSDocNonNullableType(node); - case 316 /* SyntaxKind.JSDocOptionalType */: + case 319 /* SyntaxKind.JSDocOptionalType */: return emitJSDocOptionalType(node); - case 317 /* SyntaxKind.JSDocFunctionType */: + case 320 /* SyntaxKind.JSDocFunctionType */: return emitJSDocFunctionType(node); - case 186 /* SyntaxKind.RestType */: - case 318 /* SyntaxKind.JSDocVariadicType */: + case 188 /* SyntaxKind.RestType */: + case 321 /* SyntaxKind.JSDocVariadicType */: return emitRestOrJSDocVariadicType(node); - case 319 /* SyntaxKind.JSDocNamepathType */: + case 322 /* SyntaxKind.JSDocNamepathType */: return; - case 320 /* SyntaxKind.JSDoc */: + case 323 /* SyntaxKind.JSDoc */: return emitJSDoc(node); - case 322 /* SyntaxKind.JSDocTypeLiteral */: + case 325 /* SyntaxKind.JSDocTypeLiteral */: return emitJSDocTypeLiteral(node); - case 323 /* SyntaxKind.JSDocSignature */: + case 326 /* SyntaxKind.JSDocSignature */: return emitJSDocSignature(node); - case 327 /* SyntaxKind.JSDocTag */: - case 332 /* SyntaxKind.JSDocClassTag */: - case 337 /* SyntaxKind.JSDocOverrideTag */: + case 330 /* SyntaxKind.JSDocTag */: + case 335 /* SyntaxKind.JSDocClassTag */: + case 340 /* SyntaxKind.JSDocOverrideTag */: return emitJSDocSimpleTag(node); - case 328 /* SyntaxKind.JSDocAugmentsTag */: - case 329 /* SyntaxKind.JSDocImplementsTag */: + case 331 /* SyntaxKind.JSDocAugmentsTag */: + case 332 /* SyntaxKind.JSDocImplementsTag */: return emitJSDocHeritageTag(node); - case 330 /* SyntaxKind.JSDocAuthorTag */: - case 331 /* SyntaxKind.JSDocDeprecatedTag */: + case 333 /* SyntaxKind.JSDocAuthorTag */: + case 334 /* SyntaxKind.JSDocDeprecatedTag */: return; // SyntaxKind.JSDocClassTag (see JSDocTag, above) - case 333 /* SyntaxKind.JSDocPublicTag */: - case 334 /* SyntaxKind.JSDocPrivateTag */: - case 335 /* SyntaxKind.JSDocProtectedTag */: - case 336 /* SyntaxKind.JSDocReadonlyTag */: + case 336 /* SyntaxKind.JSDocPublicTag */: + case 337 /* SyntaxKind.JSDocPrivateTag */: + case 338 /* SyntaxKind.JSDocProtectedTag */: + case 339 /* SyntaxKind.JSDocReadonlyTag */: return; - case 338 /* SyntaxKind.JSDocCallbackTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: return emitJSDocCallbackTag(node); // SyntaxKind.JSDocEnumTag (see below) - case 340 /* SyntaxKind.JSDocParameterTag */: - case 347 /* SyntaxKind.JSDocPropertyTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: + case 350 /* SyntaxKind.JSDocPropertyTag */: return emitJSDocPropertyLikeTag(node); - case 339 /* SyntaxKind.JSDocEnumTag */: - case 341 /* SyntaxKind.JSDocReturnTag */: - case 342 /* SyntaxKind.JSDocThisTag */: - case 343 /* SyntaxKind.JSDocTypeTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: + case 344 /* SyntaxKind.JSDocReturnTag */: + case 345 /* SyntaxKind.JSDocThisTag */: + case 346 /* SyntaxKind.JSDocTypeTag */: return emitJSDocSimpleTypedTag(node); - case 344 /* SyntaxKind.JSDocTemplateTag */: + case 347 /* SyntaxKind.JSDocTemplateTag */: return emitJSDocTemplateTag(node); - case 345 /* SyntaxKind.JSDocTypedefTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: return emitJSDocTypedefTag(node); - case 346 /* SyntaxKind.JSDocSeeTag */: + case 349 /* SyntaxKind.JSDocSeeTag */: return emitJSDocSeeTag(node); // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) // Transformation nodes - case 349 /* SyntaxKind.NotEmittedStatement */: - case 353 /* SyntaxKind.EndOfDeclarationMarker */: - case 352 /* SyntaxKind.MergeDeclarationMarker */: + case 352 /* SyntaxKind.NotEmittedStatement */: + case 356 /* SyntaxKind.EndOfDeclarationMarker */: + case 355 /* SyntaxKind.MergeDeclarationMarker */: return; } if (ts.isExpression(node)) { @@ -113343,85 +114402,87 @@ var ts; case 80 /* SyntaxKind.PrivateIdentifier */: return emitPrivateIdentifier(node); // Expressions - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return emitElementAccessExpression(node); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return emitCallExpression(node); - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: return emitNewExpression(node); - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 211 /* SyntaxKind.TypeAssertionExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 213 /* SyntaxKind.FunctionExpression */: + case 215 /* SyntaxKind.FunctionExpression */: return emitFunctionExpression(node); - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return emitArrowFunction(node); - case 215 /* SyntaxKind.DeleteExpression */: + case 217 /* SyntaxKind.DeleteExpression */: return emitDeleteExpression(node); - case 216 /* SyntaxKind.TypeOfExpression */: + case 218 /* SyntaxKind.TypeOfExpression */: return emitTypeOfExpression(node); - case 217 /* SyntaxKind.VoidExpression */: + case 219 /* SyntaxKind.VoidExpression */: return emitVoidExpression(node); - case 218 /* SyntaxKind.AwaitExpression */: + case 220 /* SyntaxKind.AwaitExpression */: return emitAwaitExpression(node); - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return emitBinaryExpression(node); - case 222 /* SyntaxKind.ConditionalExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: return emitConditionalExpression(node); - case 223 /* SyntaxKind.TemplateExpression */: + case 225 /* SyntaxKind.TemplateExpression */: return emitTemplateExpression(node); - case 224 /* SyntaxKind.YieldExpression */: + case 226 /* SyntaxKind.YieldExpression */: return emitYieldExpression(node); - case 225 /* SyntaxKind.SpreadElement */: + case 227 /* SyntaxKind.SpreadElement */: return emitSpreadElement(node); - case 226 /* SyntaxKind.ClassExpression */: + case 228 /* SyntaxKind.ClassExpression */: return emitClassExpression(node); - case 227 /* SyntaxKind.OmittedExpression */: + case 229 /* SyntaxKind.OmittedExpression */: return; - case 229 /* SyntaxKind.AsExpression */: + case 231 /* SyntaxKind.AsExpression */: return emitAsExpression(node); - case 230 /* SyntaxKind.NonNullExpression */: + case 232 /* SyntaxKind.NonNullExpression */: return emitNonNullExpression(node); - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 231 /* SyntaxKind.MetaProperty */: + case 235 /* SyntaxKind.SatisfiesExpression */: + return emitSatisfiesExpression(node); + case 233 /* SyntaxKind.MetaProperty */: return emitMetaProperty(node); - case 232 /* SyntaxKind.SyntheticExpression */: + case 234 /* SyntaxKind.SyntheticExpression */: return ts.Debug.fail("SyntheticExpression should never be printed."); // JSX - case 278 /* SyntaxKind.JsxElement */: + case 281 /* SyntaxKind.JsxElement */: return emitJsxElement(node); - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 282 /* SyntaxKind.JsxFragment */: + case 285 /* SyntaxKind.JsxFragment */: return emitJsxFragment(node); // Synthesized list - case 348 /* SyntaxKind.SyntaxList */: + case 351 /* SyntaxKind.SyntaxList */: return ts.Debug.fail("SyntaxList should not be printed"); // Transformation nodes - case 349 /* SyntaxKind.NotEmittedStatement */: + case 352 /* SyntaxKind.NotEmittedStatement */: return; - case 350 /* SyntaxKind.PartiallyEmittedExpression */: + case 353 /* SyntaxKind.PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 351 /* SyntaxKind.CommaListExpression */: + case 354 /* SyntaxKind.CommaListExpression */: return emitCommaList(node); - case 352 /* SyntaxKind.MergeDeclarationMarker */: - case 353 /* SyntaxKind.EndOfDeclarationMarker */: + case 355 /* SyntaxKind.MergeDeclarationMarker */: + case 356 /* SyntaxKind.EndOfDeclarationMarker */: return; - case 354 /* SyntaxKind.SyntheticReferenceExpression */: + case 357 /* SyntaxKind.SyntheticReferenceExpression */: return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); } } @@ -113469,7 +114530,7 @@ var ts; } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 306 /* SyntaxKind.Bundle */ ? node : undefined; + var bundle = node.kind === 309 /* SyntaxKind.Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -113569,7 +114630,7 @@ var ts; var pos = getTextPosWithWriteLine(); writeUnparsedNode(unparsed); if (bundleFileInfo) { - updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 302 /* SyntaxKind.UnparsedText */ ? + updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 305 /* SyntaxKind.UnparsedText */ ? "text" /* BundleFileSectionKind.Text */ : "internal" /* BundleFileSectionKind.Internal */); } @@ -113606,7 +114667,7 @@ var ts; } function emitTabStop(hint, node, snippet) { // A tab stop should only be attached to an empty node, i.e. a node that doesn't emit any text. - ts.Debug.assert(node.kind === 236 /* SyntaxKind.EmptyStatement */, "A tab stop cannot be attached to a node of kind ".concat(ts.Debug.formatSyntaxKind(node.kind), ".")); + ts.Debug.assert(node.kind === 239 /* SyntaxKind.EmptyStatement */, "A tab stop cannot be attached to a node of kind ".concat(ts.Debug.formatSyntaxKind(node.kind), ".")); ts.Debug.assert(hint !== 5 /* EmitHint.EmbeddedStatement */, "A tab stop cannot be attached to an embedded statement."); nonEscapingWrite("$".concat(snippet.order)); } @@ -113667,7 +114728,7 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 320 /* SyntaxKind.JSDocFunctionType */ && !node.name) { emit(node.type); } else { @@ -113728,7 +114789,7 @@ var ts; } function emitAccessorDeclaration(node) { emitDecoratorsAndModifiers(node, node.modifiers); - writeKeyword(node.kind === 172 /* SyntaxKind.GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 174 /* SyntaxKind.GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -113901,7 +114962,7 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - var parenthesizerRule = node.operator === 145 /* SyntaxKind.ReadonlyKeyword */ ? + var parenthesizerRule = node.operator === 146 /* SyntaxKind.ReadonlyKeyword */ ? parenthesizer.parenthesizeOperandOfReadonlyTypeOperator : parenthesizer.parenthesizeOperandOfTypeOperator; emit(node.type, parenthesizerRule); @@ -113924,7 +114985,7 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - if (node.readonlyToken.kind !== 145 /* SyntaxKind.ReadonlyKeyword */) { + if (node.readonlyToken.kind !== 146 /* SyntaxKind.ReadonlyKeyword */) { writeKeyword("readonly"); } writeSpace(); @@ -114170,7 +115231,7 @@ var ts; emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { - emitTokenWithComment(132 /* SyntaxKind.AwaitKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(133 /* SyntaxKind.AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } @@ -114195,7 +115256,7 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 219 /* SyntaxKind.PrefixUnaryExpression */ + return operand.kind === 221 /* SyntaxKind.PrefixUnaryExpression */ && ((node.operator === 39 /* SyntaxKind.PlusToken */ && (operand.operator === 39 /* SyntaxKind.PlusToken */ || operand.operator === 45 /* SyntaxKind.PlusPlusToken */)) || (node.operator === 40 /* SyntaxKind.MinusToken */ && (operand.operator === 40 /* SyntaxKind.MinusToken */ || operand.operator === 46 /* SyntaxKind.MinusMinusToken */))); } @@ -114343,6 +115404,15 @@ var ts; emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } + function emitSatisfiesExpression(node) { + emitExpression(node.expression, /*parenthesizerRules*/ undefined); + if (node.type) { + writeSpace(); + writeKeyword("satisfies"); + writeSpace(); + emit(node.type); + } + } function emitMetaProperty(node) { writeToken(node.keywordToken, node.pos, writePunctuation); writePunctuation("."); @@ -114400,7 +115470,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node, node.thenStatement, node.elseStatement); emitTokenWithComment(91 /* SyntaxKind.ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 239 /* SyntaxKind.IfStatement */) { + if (node.elseStatement.kind === 242 /* SyntaxKind.IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -114463,7 +115533,7 @@ var ts; emitTokenWithComment(20 /* SyntaxKind.OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(160 /* SyntaxKind.OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(162 /* SyntaxKind.OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTokenWithComment(21 /* SyntaxKind.CloseParenToken */, node.expression.end, writePunctuation, node); @@ -114471,7 +115541,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (node.kind === 258 /* SyntaxKind.VariableDeclarationList */) { emit(node); } else { @@ -114508,7 +115578,7 @@ var ts; } pos = writeTokenText(token, writer, pos); if (isSimilarNode && contextNode.end !== pos) { - var isJsxExprContext = contextNode.kind === 288 /* SyntaxKind.JsxExpression */; + var isJsxExprContext = contextNode.kind === 291 /* SyntaxKind.JsxExpression */; emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ !isJsxExprContext, /*forceNoNewline*/ isJsxExprContext); } return pos; @@ -114818,7 +115888,7 @@ var ts; emitTokenWithComment(100 /* SyntaxKind.ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.isTypeOnly) { - emitTokenWithComment(152 /* SyntaxKind.TypeKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(154 /* SyntaxKind.TypeKeyword */, node.pos, writeKeyword, node); writeSpace(); } emit(node.name); @@ -114843,7 +115913,7 @@ var ts; if (node.importClause) { emit(node.importClause); writeSpace(); - emitTokenWithComment(156 /* SyntaxKind.FromKeyword */, node.importClause.end, writeKeyword, node); + emitTokenWithComment(158 /* SyntaxKind.FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); @@ -114854,7 +115924,7 @@ var ts; } function emitImportClause(node) { if (node.isTypeOnly) { - emitTokenWithComment(152 /* SyntaxKind.TypeKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(154 /* SyntaxKind.TypeKeyword */, node.pos, writeKeyword, node); writeSpace(); } emit(node.name); @@ -114867,7 +115937,7 @@ var ts; function emitNamespaceImport(node) { var asPos = emitTokenWithComment(41 /* SyntaxKind.AsteriskToken */, node.pos, writePunctuation, node); writeSpace(); - emitTokenWithComment(127 /* SyntaxKind.AsKeyword */, asPos, writeKeyword, node); + emitTokenWithComment(128 /* SyntaxKind.AsKeyword */, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -114893,10 +115963,11 @@ var ts; writeTrailingSemicolon(); } function emitExportDeclaration(node) { + emitModifiers(node, node.modifiers); var nextPos = emitTokenWithComment(93 /* SyntaxKind.ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.isTypeOnly) { - nextPos = emitTokenWithComment(152 /* SyntaxKind.TypeKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(154 /* SyntaxKind.TypeKeyword */, nextPos, writeKeyword, node); writeSpace(); } if (node.exportClause) { @@ -114908,7 +115979,7 @@ var ts; if (node.moduleSpecifier) { writeSpace(); var fromPos = node.exportClause ? node.exportClause.end : nextPos; - emitTokenWithComment(156 /* SyntaxKind.FromKeyword */, fromPos, writeKeyword, node); + emitTokenWithComment(158 /* SyntaxKind.FromKeyword */, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } @@ -114918,7 +115989,7 @@ var ts; writeTrailingSemicolon(); } function emitAssertClause(node) { - emitTokenWithComment(129 /* SyntaxKind.AssertKeyword */, node.pos, writeKeyword, node); + emitTokenWithComment(130 /* SyntaxKind.AssertKeyword */, node.pos, writeKeyword, node); writeSpace(); var elements = node.elements; emitList(node, elements, 526226 /* ListFormat.ImportClauseEntries */); @@ -114938,9 +116009,9 @@ var ts; function emitNamespaceExportDeclaration(node) { var nextPos = emitTokenWithComment(93 /* SyntaxKind.ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(127 /* SyntaxKind.AsKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(128 /* SyntaxKind.AsKeyword */, nextPos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(142 /* SyntaxKind.NamespaceKeyword */, nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(143 /* SyntaxKind.NamespaceKeyword */, nextPos, writeKeyword, node); writeSpace(); emit(node.name); writeTrailingSemicolon(); @@ -114948,7 +116019,7 @@ var ts; function emitNamespaceExport(node) { var asPos = emitTokenWithComment(41 /* SyntaxKind.AsteriskToken */, node.pos, writePunctuation, node); writeSpace(); - emitTokenWithComment(127 /* SyntaxKind.AsKeyword */, asPos, writeKeyword, node); + emitTokenWithComment(128 /* SyntaxKind.AsKeyword */, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -114971,7 +116042,7 @@ var ts; if (node.propertyName) { emit(node.propertyName); writeSpace(); - emitTokenWithComment(127 /* SyntaxKind.AsKeyword */, node.propertyName.end, writeKeyword, node); + emitTokenWithComment(128 /* SyntaxKind.AsKeyword */, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -115192,7 +116263,7 @@ var ts; } } if (node.tags) { - if (node.tags.length === 1 && node.tags[0].kind === 343 /* SyntaxKind.JSDocTypeTag */ && !node.comment) { + if (node.tags.length === 1 && node.tags[0].kind === 346 /* SyntaxKind.JSDocTypeTag */ && !node.comment) { writeSpace(); emit(node.tags[0]); } @@ -115237,7 +116308,7 @@ var ts; function emitJSDocTypedefTag(tag) { emitJSDocTagName(tag.tagName); if (tag.typeExpression) { - if (tag.typeExpression.kind === 309 /* SyntaxKind.JSDocTypeExpression */) { + if (tag.typeExpression.kind === 312 /* SyntaxKind.JSDocTypeExpression */) { emitJSDocTypeExpression(tag.typeExpression); } else { @@ -115256,7 +116327,7 @@ var ts; emit(tag.fullName); } emitJSDocComment(tag.comment); - if (tag.typeExpression && tag.typeExpression.kind === 322 /* SyntaxKind.JSDocTypeLiteral */) { + if (tag.typeExpression && tag.typeExpression.kind === 325 /* SyntaxKind.JSDocTypeLiteral */) { emitJSDocTypeLiteral(tag.typeExpression); } } @@ -116189,13 +117260,13 @@ var ts; && (!currentSourceFile || ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile)); } function skipSynthesizedParentheses(node) { - while (node.kind === 212 /* SyntaxKind.ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 214 /* SyntaxKind.ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; } function getTextOfNode(node, includeTrivia) { - if (ts.isGeneratedIdentifier(node)) { + if (ts.isGeneratedIdentifier(node) || ts.isGeneratedPrivateIdentifier(node)) { return generateName(node); } if (ts.isStringLiteral(node) && node.textSourceNode) { @@ -116219,7 +117290,7 @@ var ts; function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) { if (node.kind === 10 /* SyntaxKind.StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; - if (ts.isIdentifier(textSourceNode) || ts.isNumericLiteral(textSourceNode)) { + if (ts.isIdentifier(textSourceNode) || ts.isPrivateIdentifier(textSourceNode) || ts.isNumericLiteral(textSourceNode)) { var text = ts.isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode); return jsxAttributeEscape ? "\"".concat(ts.escapeJsxAttributeString(text), "\"") : neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* EmitFlags.NoAsciiEscaping */) ? "\"".concat(ts.escapeString(text), "\"") : @@ -116243,7 +117314,11 @@ var ts; return; } tempFlagsStack.push(tempFlags); - tempFlags = 0; + tempFlags = 0 /* TempFlags.Auto */; + privateNameTempFlagsStack.push(privateNameTempFlags); + privateNameTempFlags = 0 /* TempFlags.Auto */; + formattedNameTempFlagsStack.push(formattedNameTempFlags); + formattedNameTempFlags = undefined; reservedNamesStack.push(reservedNames); } /** @@ -116254,6 +117329,8 @@ var ts; return; } tempFlags = tempFlagsStack.pop(); + privateNameTempFlags = privateNameTempFlagsStack.pop(); + formattedNameTempFlags = formattedNameTempFlagsStack.pop(); reservedNames = reservedNamesStack.pop(); } function reserveNameInNestedScopes(name) { @@ -116266,84 +117343,84 @@ var ts; if (!node) return; switch (node.kind) { - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: ts.forEach(node.statements, generateNames); break; - case 250 /* SyntaxKind.LabeledStatement */: - case 248 /* SyntaxKind.WithStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: + case 253 /* SyntaxKind.LabeledStatement */: + case 251 /* SyntaxKind.WithStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: generateNames(node.statement); break; - case 239 /* SyntaxKind.IfStatement */: + case 242 /* SyntaxKind.IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 242 /* SyntaxKind.ForStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 243 /* SyntaxKind.ForInStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 246 /* SyntaxKind.ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 249 /* SyntaxKind.SwitchStatement */: + case 252 /* SyntaxKind.SwitchStatement */: generateNames(node.caseBlock); break; - case 263 /* SyntaxKind.CaseBlock */: + case 266 /* SyntaxKind.CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 252 /* SyntaxKind.TryStatement */: + case 255 /* SyntaxKind.TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: generateNames(node.declarationList); break; - case 255 /* SyntaxKind.VariableDeclarationList */: + case 258 /* SyntaxKind.VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 254 /* SyntaxKind.VariableDeclaration */: - case 164 /* SyntaxKind.Parameter */: - case 203 /* SyntaxKind.BindingElement */: - case 257 /* SyntaxKind.ClassDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 166 /* SyntaxKind.Parameter */: + case 205 /* SyntaxKind.BindingElement */: + case 260 /* SyntaxKind.ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* EmitFlags.ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 202 /* SyntaxKind.ArrayBindingPattern */: + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: generateNames(node.importClause); break; - case 267 /* SyntaxKind.ImportClause */: + case 270 /* SyntaxKind.ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 268 /* SyntaxKind.NamespaceImport */: + case 271 /* SyntaxKind.NamespaceImport */: generateNameIfNeeded(node.name); break; - case 274 /* SyntaxKind.NamespaceExport */: + case 277 /* SyntaxKind.NamespaceExport */: generateNameIfNeeded(node.name); break; - case 269 /* SyntaxKind.NamedImports */: + case 272 /* SyntaxKind.NamedImports */: ts.forEach(node.elements, generateNames); break; - case 270 /* SyntaxKind.ImportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -116352,19 +117429,19 @@ var ts; if (!node) return; switch (node.kind) { - case 296 /* SyntaxKind.PropertyAssignment */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: generateNameIfNeeded(node.name); break; } } function generateNameIfNeeded(name) { if (name) { - if (ts.isGeneratedIdentifier(name)) { + if (ts.isGeneratedIdentifier(name) || ts.isGeneratedPrivateIdentifier(name)) { generateName(name); } else if (ts.isBindingPattern(name)) { @@ -116379,7 +117456,7 @@ var ts; if ((name.autoGenerateFlags & 7 /* GeneratedIdentifierFlags.KindMask */) === 4 /* GeneratedIdentifierFlags.Node */) { // Node names generate unique names based on their original node // and are cached based on that node's id. - return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); + return generateNameCached(ts.getNodeForGeneratedName(name), ts.isPrivateIdentifier(name), name.autoGenerateFlags, name.autoGeneratePrefix, name.autoGenerateSuffix); } else { // Auto, Loop, and Unique names are cached based on their unique @@ -116388,9 +117465,9 @@ var ts; return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } - function generateNameCached(node, flags) { + function generateNameCached(node, privateName, flags, prefix, suffix) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, privateName, flags !== null && flags !== void 0 ? flags : 0 /* GeneratedIdentifierFlags.None */, ts.formatGeneratedNamePart(prefix, generateName), ts.formatGeneratedNamePart(suffix))); } /** * Returns a value indicating whether a name is unique globally, within the current file, @@ -116422,20 +117499,53 @@ var ts; } return true; } + function getTempFlags(formattedNameKey) { + var _a; + switch (formattedNameKey) { + case "": + return tempFlags; + case "#": + return privateNameTempFlags; + default: + return (_a = formattedNameTempFlags === null || formattedNameTempFlags === void 0 ? void 0 : formattedNameTempFlags.get(formattedNameKey)) !== null && _a !== void 0 ? _a : 0 /* TempFlags.Auto */; + } + } + function setTempFlags(formattedNameKey, flags) { + switch (formattedNameKey) { + case "": + tempFlags = flags; + break; + case "#": + privateNameTempFlags = flags; + break; + default: + formattedNameTempFlags !== null && formattedNameTempFlags !== void 0 ? formattedNameTempFlags : (formattedNameTempFlags = new ts.Map()); + formattedNameTempFlags.set(formattedNameKey, flags); + break; + } + } /** * Return the next available name in the pattern _a ... _z, _0, _1, ... * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. */ - function makeTempVariableName(flags, reservedInNestedScopes) { + function makeTempVariableName(flags, reservedInNestedScopes, privateName, prefix, suffix) { + if (prefix.length > 0 && prefix.charCodeAt(0) === 35 /* CharacterCodes.hash */) { + prefix = prefix.slice(1); + } + // Generate a key to use to acquire a TempFlags counter based on the fixed portions of the generated name. + var key = ts.formatGeneratedName(privateName, prefix, "", suffix); + var tempFlags = getTempFlags(key); if (flags && !(tempFlags & flags)) { var name = flags === 268435456 /* TempFlags._i */ ? "_i" : "_n"; - if (isUniqueName(name)) { + var fullName = ts.formatGeneratedName(privateName, prefix, name, suffix); + if (isUniqueName(fullName)) { tempFlags |= flags; if (reservedInNestedScopes) { - reserveNameInNestedScopes(name); + reserveNameInNestedScopes(fullName); } - return name; + setTempFlags(key, tempFlags); + return fullName; } } while (true) { @@ -116446,11 +117556,13 @@ var ts; var name = count < 26 ? "_" + String.fromCharCode(97 /* CharacterCodes.a */ + count) : "_" + (count - 26); - if (isUniqueName(name)) { + var fullName = ts.formatGeneratedName(privateName, prefix, name, suffix); + if (isUniqueName(fullName)) { if (reservedInNestedScopes) { - reserveNameInNestedScopes(name); + reserveNameInNestedScopes(fullName); } - return name; + setTempFlags(key, tempFlags); + return fullName; } } } @@ -116462,17 +117574,24 @@ var ts; * makeUniqueName are guaranteed to never conflict. * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' */ - function makeUniqueName(baseName, checkFn, optimistic, scoped) { + function makeUniqueName(baseName, checkFn, optimistic, scoped, privateName, prefix, suffix) { if (checkFn === void 0) { checkFn = isUniqueName; } + if (baseName.length > 0 && baseName.charCodeAt(0) === 35 /* CharacterCodes.hash */) { + baseName = baseName.slice(1); + } + if (prefix.length > 0 && prefix.charCodeAt(0) === 35 /* CharacterCodes.hash */) { + prefix = prefix.slice(1); + } if (optimistic) { - if (checkFn(baseName)) { + var fullName = ts.formatGeneratedName(privateName, prefix, baseName, suffix); + if (checkFn(fullName)) { if (scoped) { - reserveNameInNestedScopes(baseName); + reserveNameInNestedScopes(fullName); } else { - generatedNames.add(baseName); + generatedNames.add(fullName); } - return baseName; + return fullName; } } // Find the first unique 'name_n', where n is a positive number @@ -116481,21 +117600,21 @@ var ts; } var i = 1; while (true) { - var generatedName = baseName + i; - if (checkFn(generatedName)) { + var fullName = ts.formatGeneratedName(privateName, prefix, baseName + i, suffix); + if (checkFn(fullName)) { if (scoped) { - reserveNameInNestedScopes(generatedName); + reserveNameInNestedScopes(fullName); } else { - generatedNames.add(generatedName); + generatedNames.add(fullName); } - return generatedName; + return fullName; } i++; } } function makeFileLevelOptimisticUniqueName(name) { - return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); + return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true, /*scoped*/ false, /*privateName*/ false, /*prefix*/ "", /*suffix*/ ""); } /** * Generates a unique name for a ModuleDeclaration or EnumDeclaration. @@ -116503,7 +117622,7 @@ var ts; function generateNameForModuleOrEnum(node) { var name = getTextOfNode(node.name); // Use module/enum name itself if it is unique, otherwise make a unique variation - return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + return isUniqueLocalName(name, node) ? name : makeUniqueName(name, isUniqueName, /*optimistic*/ false, /*scoped*/ false, /*privateName*/ false, /*prefix*/ "", /*suffix*/ ""); } /** * Generates a unique name for an ImportDeclaration or ExportDeclaration. @@ -116512,89 +117631,76 @@ var ts; var expr = ts.getExternalModuleName(node); // TODO: GH#18217 var baseName = ts.isStringLiteral(expr) ? ts.makeIdentifierFromModuleName(expr.text) : "module"; - return makeUniqueName(baseName); + return makeUniqueName(baseName, isUniqueName, /*optimistic*/ false, /*scoped*/ false, /*privateName*/ false, /*prefix*/ "", /*suffix*/ ""); } /** * Generates a unique name for a default export. */ function generateNameForExportDefault() { - return makeUniqueName("default"); + return makeUniqueName("default", isUniqueName, /*optimistic*/ false, /*scoped*/ false, /*privateName*/ false, /*prefix*/ "", /*suffix*/ ""); } /** * Generates a unique name for a class expression. */ function generateNameForClassExpression() { - return makeUniqueName("class"); + return makeUniqueName("class", isUniqueName, /*optimistic*/ false, /*scoped*/ false, /*privateName*/ false, /*prefix*/ "", /*suffix*/ ""); } - function generateNameForMethodOrAccessor(node) { + function generateNameForMethodOrAccessor(node, privateName, prefix, suffix) { if (ts.isIdentifier(node.name)) { - return generateNameCached(node.name); + return generateNameCached(node.name, privateName); } - return makeTempVariableName(0 /* TempFlags.Auto */); + return makeTempVariableName(0 /* TempFlags.Auto */, /*reservedInNestedScopes*/ false, privateName, prefix, suffix); } /** * Generates a unique name from a node. */ - function generateNameForNode(node, flags) { + function generateNameForNode(node, privateName, flags, prefix, suffix) { switch (node.kind) { case 79 /* SyntaxKind.Identifier */: - return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* GeneratedIdentifierFlags.Optimistic */), !!(flags & 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */)); - case 261 /* SyntaxKind.ModuleDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: + case 80 /* SyntaxKind.PrivateIdentifier */: + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* GeneratedIdentifierFlags.Optimistic */), !!(flags & 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */), privateName, prefix, suffix); + case 264 /* SyntaxKind.ModuleDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + ts.Debug.assert(!prefix && !suffix && !privateName); return generateNameForModuleOrEnum(node); - case 266 /* SyntaxKind.ImportDeclaration */: - case 272 /* SyntaxKind.ExportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: + ts.Debug.assert(!prefix && !suffix && !privateName); return generateNameForImportOrExportDeclaration(node); - case 256 /* SyntaxKind.FunctionDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 271 /* SyntaxKind.ExportAssignment */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 274 /* SyntaxKind.ExportAssignment */: + ts.Debug.assert(!prefix && !suffix && !privateName); return generateNameForExportDefault(); - case 226 /* SyntaxKind.ClassExpression */: + case 228 /* SyntaxKind.ClassExpression */: + ts.Debug.assert(!prefix && !suffix && !privateName); return generateNameForClassExpression(); - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - return generateNameForMethodOrAccessor(node); - case 162 /* SyntaxKind.ComputedPropertyName */: - return makeTempVariableName(0 /* TempFlags.Auto */, /*reserveInNestedScopes*/ true); + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + return generateNameForMethodOrAccessor(node, privateName, prefix, suffix); + case 164 /* SyntaxKind.ComputedPropertyName */: + return makeTempVariableName(0 /* TempFlags.Auto */, /*reserveInNestedScopes*/ true, privateName, prefix, suffix); default: - return makeTempVariableName(0 /* TempFlags.Auto */); + return makeTempVariableName(0 /* TempFlags.Auto */, /*reserveInNestedScopes*/ false, privateName, prefix, suffix); } } /** * Generates a unique identifier for a node. */ function makeName(name) { + var prefix = ts.formatGeneratedNamePart(name.autoGeneratePrefix, generateName); + var suffix = ts.formatGeneratedNamePart(name.autoGenerateSuffix); switch (name.autoGenerateFlags & 7 /* GeneratedIdentifierFlags.KindMask */) { case 1 /* GeneratedIdentifierFlags.Auto */: - return makeTempVariableName(0 /* TempFlags.Auto */, !!(name.autoGenerateFlags & 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */)); + return makeTempVariableName(0 /* TempFlags.Auto */, !!(name.autoGenerateFlags & 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */), ts.isPrivateIdentifier(name), prefix, suffix); case 2 /* GeneratedIdentifierFlags.Loop */: - return makeTempVariableName(268435456 /* TempFlags._i */, !!(name.autoGenerateFlags & 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */)); + ts.Debug.assertNode(name, ts.isIdentifier); + return makeTempVariableName(268435456 /* TempFlags._i */, !!(name.autoGenerateFlags & 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */), /*privateName*/ false, prefix, suffix); case 3 /* GeneratedIdentifierFlags.Unique */: - return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* GeneratedIdentifierFlags.FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* GeneratedIdentifierFlags.Optimistic */), !!(name.autoGenerateFlags & 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */)); + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* GeneratedIdentifierFlags.FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* GeneratedIdentifierFlags.Optimistic */), !!(name.autoGenerateFlags & 8 /* GeneratedIdentifierFlags.ReservedInNestedScopes */), ts.isPrivateIdentifier(name), prefix, suffix); } - return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); - } - /** - * Gets the node from which a name should be generated. - */ - function getNodeForGeneratedName(name) { - var autoGenerateId = name.autoGenerateId; - var node = name; - var original = node.original; - while (original) { - node = original; - // if "node" is a different generated name (having a different - // "autoGenerateId"), use it and stop traversing. - if (ts.isIdentifier(node) - && !!(node.autoGenerateFlags & 4 /* GeneratedIdentifierFlags.Node */) - && node.autoGenerateId !== autoGenerateId) { - break; - } - original = node.original; - } - // otherwise, return the original node for the source; - return node; + return ts.Debug.fail("Unsupported GeneratedIdentifierKind: ".concat(ts.Debug.formatEnum(name.autoGenerateFlags & 7 /* GeneratedIdentifierFlags.KindMask */, ts.GeneratedIdentifierFlags, /*isFlags*/ true), ".")); } // Comments function pipelineEmitWithComments(hint, node) { @@ -116640,7 +117746,7 @@ var ts; // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. if (!skipLeadingComments) { - emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== 349 /* SyntaxKind.NotEmittedStatement */); + emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== 352 /* SyntaxKind.NotEmittedStatement */); } if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* EmitFlags.NoLeadingComments */) !== 0)) { // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. @@ -116651,7 +117757,7 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (node.kind === 258 /* SyntaxKind.VariableDeclarationList */) { declarationListContainerEnd = end; } } @@ -116670,7 +117776,7 @@ var ts; declarationListContainerEnd = savedDeclarationListContainerEnd; // Emit trailing comments if the position is not synthesized and the node // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && node.kind !== 349 /* SyntaxKind.NotEmittedStatement */) { + if (!skipTrailingComments && node.kind !== 352 /* SyntaxKind.NotEmittedStatement */) { emitTrailingComments(end); } } @@ -116951,7 +118057,7 @@ var ts; } else { var source = sourceMapRange.source || sourceMapSource; - if (node.kind !== 349 /* SyntaxKind.NotEmittedStatement */ + if (node.kind !== 352 /* SyntaxKind.NotEmittedStatement */ && (emitFlags & 16 /* EmitFlags.NoLeadingSourceMap */) === 0 && sourceMapRange.pos >= 0) { emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); @@ -116969,7 +118075,7 @@ var ts; if (emitFlags & 64 /* EmitFlags.NoNestedSourceMaps */) { sourceMapsDisabled = false; } - if (node.kind !== 349 /* SyntaxKind.NotEmittedStatement */ + if (node.kind !== 352 /* SyntaxKind.NotEmittedStatement */ && (emitFlags & 32 /* EmitFlags.NoTrailingSourceMap */) === 0 && sourceMapRange.end >= 0) { emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); @@ -117134,7 +118240,16 @@ var ts; return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); } function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + var entries = getCachedFileSystemEntries(ts.getDirectoryPath(path)); + if (!entries) { + return entries; + } + // If we're looking for the base directory, we're definitely going to search the entries + if (!entries.sortedAndCanonicalizedFiles) { + entries.sortedAndCanonicalizedFiles = entries.files.map(getCanonicalFileName).sort(); + entries.sortedAndCanonicalizedDirectories = entries.directories.map(getCanonicalFileName).sort(); + } + return entries; } function getBaseNameOfFileName(fileName) { return ts.getBaseFileName(ts.normalizePath(fileName)); @@ -117177,21 +118292,10 @@ var ts; return undefined; } } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } function hasEntry(entries, name) { - return ts.some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } + // Case-sensitive comparison since already canonicalized + var index = ts.binarySearch(entries, name, ts.identity, ts.compareStringsCaseSensitive); + return index >= 0; } function writeFile(fileName, data, writeByteOrderMark) { var path = toPath(fileName); @@ -117204,7 +118308,7 @@ var ts; function fileExists(fileName) { var path = toPath(fileName); var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + return result && hasEntry(result.sortedAndCanonicalizedFiles, getCanonicalFileName(getBaseNameOfFileName(fileName))) || host.fileExists(fileName); } function directoryExists(dirPath) { @@ -117214,9 +118318,14 @@ var ts; function createDirectory(dirPath) { var path = toPath(dirPath); var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); if (result) { - updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + var baseName = getBaseNameOfFileName(dirPath); + var canonicalizedBaseName = getCanonicalFileName(baseName); + var canonicalizedDirectories = result.sortedAndCanonicalizedDirectories; + // Case-sensitive comparison since already canonicalized + if (ts.insertSorted(canonicalizedDirectories, canonicalizedBaseName, ts.compareStringsCaseSensitive)) { + result.directories.push(baseName); + } } host.createDirectory(dirPath); } @@ -117285,7 +118394,7 @@ var ts; fileExists: host.fileExists(fileOrDirectoryPath), directoryExists: host.directoryExists(fileOrDirectoryPath) }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + if (fsQueryResult.directoryExists || hasEntry(parentResult.sortedAndCanonicalizedDirectories, getCanonicalFileName(baseName))) { // Folder added or removed, clear the cache instead of updating the folder and its structure clearCache(); } @@ -117305,7 +118414,23 @@ var ts; } } function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); + var canonicalizedFiles = parentResult.sortedAndCanonicalizedFiles; + var canonicalizedBaseName = getCanonicalFileName(baseName); + if (fileExists) { + // Case-sensitive comparison since already canonicalized + if (ts.insertSorted(canonicalizedFiles, canonicalizedBaseName, ts.compareStringsCaseSensitive)) { + parentResult.files.push(baseName); + } + } + else { + // Case-sensitive comparison since already canonicalized + var sortedIndex = ts.binarySearch(canonicalizedFiles, canonicalizedBaseName, ts.identity, ts.compareStringsCaseSensitive); + if (sortedIndex >= 0) { + canonicalizedFiles.splice(sortedIndex, 1); + var unsortedIndex = parentResult.files.findIndex(function (entry) { return getCanonicalFileName(entry) === canonicalizedBaseName; }); + parentResult.files.splice(unsortedIndex, 1); + } + } } function clearCache() { cachedReadDirectoryResult.clear(); @@ -117785,14 +118910,16 @@ var ts; } return setReadFileCache(key, fileName); }; - var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) { var key = toPath(fileName); - var value = sourceFileCache.get(key); + var impliedNodeFormat = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions.impliedNodeFormat : undefined; + var forImpliedNodeFormat = sourceFileCache.get(impliedNodeFormat); + var value = forImpliedNodeFormat === null || forImpliedNodeFormat === void 0 ? void 0 : forImpliedNodeFormat.get(key); if (value) return value; - var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile); + var sourceFile = getSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile); if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Extension.Json */))) { - sourceFileCache.set(key, sourceFile); + sourceFileCache.set(impliedNodeFormat, (forImpliedNodeFormat || new ts.Map()).set(key, sourceFile)); } return sourceFile; } : undefined; @@ -117817,13 +118944,15 @@ var ts; var value = readFileCache.get(key); if (value !== undefined && value !== data) { readFileCache.delete(key); - sourceFileCache.delete(key); + sourceFileCache.forEach(function (map) { return map.delete(key); }); } else if (getSourceFileWithCache) { - var sourceFile = sourceFileCache.get(key); - if (sourceFile && sourceFile.text !== data) { - sourceFileCache.delete(key); - } + sourceFileCache.forEach(function (map) { + var sourceFile = map.get(key); + if (sourceFile && sourceFile.text !== data) { + map.delete(key); + } + }); } originalWriteFile.call.apply(originalWriteFile, __spreadArray([host, fileName, data], rest, false)); }; @@ -118065,7 +119194,6 @@ var ts; return resolutions; } ts.loadWithTypeDirectiveCache = loadWithTypeDirectiveCache; - ; /** * Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly * provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file. @@ -118265,7 +119393,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; @@ -118293,7 +119421,7 @@ var ts; return true; function sourceFileNotUptoDate(sourceFile) { return !sourceFileVersionUptoDate(sourceFile) || - hasInvalidatedResolution(sourceFile.path); + hasInvalidatedResolutions(sourceFile.path); } function sourceFileVersionUptoDate(sourceFile) { return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName); @@ -118370,7 +119498,7 @@ var ts; state.failedLookupLocations = packageJsonLocations; state.affectingLocations = packageJsonLocations; var packageJsonScope = ts.getPackageScopeForPath(fileName, state); - var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope }; } } @@ -118539,7 +119667,7 @@ var ts; var moduleResolutionCache; var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; - var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var hasInvalidatedResolutions = host.hasInvalidatedResolutions || ts.returnFalse; if (host.resolveModuleNames) { actualResolveModuleNamesWorker = function (moduleNames, containingFile, containingFileName, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFileName, reusedNames, redirectedReference, options, containingFile).map(function (resolved) { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. @@ -118986,7 +120114,7 @@ var ts; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions - if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { + if (file === oldSourceFile && !hasInvalidatedResolutions(oldSourceFile.path)) { var oldResolvedModule = ts.getResolvedModule(oldSourceFile, moduleName, getModeForResolutionAtIndex(oldSourceFile, i)); if (oldResolvedModule) { if (ts.isTraceEnabled(options, host)) { @@ -119222,7 +120350,7 @@ var ts; // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else if (hasInvalidatedResolution(oldSourceFile.path)) { + else if (hasInvalidatedResolutions(oldSourceFile.path)) { // 'module/types' references could have changed structureIsReused = 1 /* StructureIsReused.SafeModules */; // add file to the modified list so that we will resolve it later @@ -119610,22 +120738,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 164 /* SyntaxKind.Parameter */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: + case 166 /* SyntaxKind.Parameter */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); return "skip"; } // falls through - case 168 /* SyntaxKind.MethodSignature */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 213 /* SyntaxKind.FunctionExpression */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 214 /* SyntaxKind.ArrowFunction */: - case 254 /* SyntaxKind.VariableDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 215 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 216 /* SyntaxKind.ArrowFunction */: + case 257 /* SyntaxKind.VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files)); @@ -119633,65 +120761,68 @@ var ts; } } switch (node.kind) { - case 267 /* SyntaxKind.ImportClause */: + case 270 /* SyntaxKind.ImportClause */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type")); return "skip"; } break; - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type")); return "skip"; } break; - case 270 /* SyntaxKind.ImportSpecifier */: - case 275 /* SyntaxKind.ExportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, ts.isImportSpecifier(node) ? "import...type" : "export...type")); return "skip"; } break; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files)); return "skip"; - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 291 /* SyntaxKind.HeritageClause */: + case 294 /* SyntaxKind.HeritageClause */: var heritageClause = node; if (heritageClause.token === 117 /* SyntaxKind.ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: var interfaceKeyword = ts.tokenToString(118 /* SyntaxKind.InterfaceKeyword */); ts.Debug.assertIsDefined(interfaceKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword)); return "skip"; - case 261 /* SyntaxKind.ModuleDeclaration */: - var moduleKeyword = node.flags & 16 /* NodeFlags.Namespace */ ? ts.tokenToString(142 /* SyntaxKind.NamespaceKeyword */) : ts.tokenToString(141 /* SyntaxKind.ModuleKeyword */); + case 264 /* SyntaxKind.ModuleDeclaration */: + var moduleKeyword = node.flags & 16 /* NodeFlags.Namespace */ ? ts.tokenToString(143 /* SyntaxKind.NamespaceKeyword */) : ts.tokenToString(142 /* SyntaxKind.ModuleKeyword */); ts.Debug.assertIsDefined(moduleKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword)); return "skip"; - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(92 /* SyntaxKind.EnumKeyword */)); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); return "skip"; - case 230 /* SyntaxKind.NonNullExpression */: + case 232 /* SyntaxKind.NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 229 /* SyntaxKind.AsExpression */: + case 231 /* SyntaxKind.AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 211 /* SyntaxKind.TypeAssertionExpression */: + case 235 /* SyntaxKind.SatisfiesExpression */: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files)); + return "skip"; + case 213 /* SyntaxKind.TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } } @@ -119700,53 +120831,55 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 213 /* SyntaxKind.FunctionExpression */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 214 /* SyntaxKind.ArrowFunction */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 215 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 216 /* SyntaxKind.ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); return "skip"; } // falls through - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - checkModifiers(parent.modifiers, parent.kind === 237 /* SyntaxKind.VariableStatement */); + checkModifiers(parent.modifiers, parent.kind === 240 /* SyntaxKind.VariableStatement */); return "skip"; } break; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (ts.isModifier(modifier) && modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { + if (ts.isModifier(modifier) + && modifier.kind !== 124 /* SyntaxKind.StaticKeyword */ + && modifier.kind !== 127 /* SyntaxKind.AccessorKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); } } return "skip"; } break; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers && ts.some(nodes, ts.isModifier)) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 280 /* SyntaxKind.JsxOpeningElement */: - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files)); @@ -119768,18 +120901,19 @@ var ts; case 123 /* SyntaxKind.PublicKeyword */: case 121 /* SyntaxKind.PrivateKeyword */: case 122 /* SyntaxKind.ProtectedKeyword */: - case 145 /* SyntaxKind.ReadonlyKeyword */: - case 135 /* SyntaxKind.DeclareKeyword */: + case 146 /* SyntaxKind.ReadonlyKeyword */: + case 136 /* SyntaxKind.DeclareKeyword */: case 126 /* SyntaxKind.AbstractKeyword */: - case 159 /* SyntaxKind.OverrideKeyword */: + case 161 /* SyntaxKind.OverrideKeyword */: case 101 /* SyntaxKind.InKeyword */: - case 144 /* SyntaxKind.OutKeyword */: + case 145 /* SyntaxKind.OutKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); break; // These are all legal modifiers. case 124 /* SyntaxKind.StaticKeyword */: case 93 /* SyntaxKind.ExportKeyword */: case 88 /* SyntaxKind.DefaultKeyword */: + case 127 /* SyntaxKind.AccessorKeyword */: } } } @@ -120101,7 +121235,7 @@ var ts; // It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache // and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way // to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront. - var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); + var result = getImpliedNodeFormatForFileWorker(ts.getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); var languageVersion = ts.getEmitScriptTarget(options); var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options); return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) : @@ -120704,10 +121838,12 @@ var ts; if (options.preserveConstEnums === false) { createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); } - var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* ScriptKind.JSON */; }); - if (firstNonExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics._0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module, ts.getBaseFileName(firstNonExternalModuleSourceFile.fileName))); + for (var _a = 0, files_5 = files; _a < files_5.length; _a++) { + var file = files_5[_a]; + if (!ts.isExternalModule(file) && !ts.isSourceFileJS(file) && !file.isDeclarationFile && file.scriptKind !== 6 /* ScriptKind.JSON */) { + var span = ts.getErrorSpanForNode(file, file); + programDiagnostics.add(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics._0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module, ts.getBaseFileName(file.fileName))); + } } } else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ScriptTarget.ES2015 */ && options.module === ts.ModuleKind.None) { @@ -121958,10 +123094,16 @@ var ts; var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + // We can only reuse emit signatures (i.e. .d.ts signatures) if the .d.ts file is unchanged, + // which will eg be depedent on change in options like declarationDir and outDir options are unchanged. + // We need to look in oldState.compilerOptions, rather than oldCompilerOptions (i.e.we need to disregard useOldState) because + // oldCompilerOptions can be undefined if there was change in say module from None to some other option + // which would make useOldState as false since we can now use reference maps that are needed to track what to emit, what to check etc + // but that option change does not affect d.ts file name so emitSignatures should still be reused. var canCopyEmitSignatures = compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && !outFilePath && - !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions); if (useOldState) { // Copy old state's changed files set (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); @@ -123176,7 +124318,7 @@ var ts; var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* CharacterCodes.slash */; if (isNonDirectorySeparatorRoot && dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths - pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart + pathPartForUserCheck.search(/[a-zA-Z]\$\//) === 0) { // Dos style nextPart nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1); if (nextDirectorySeparator === -1) { // ignore "//vda1cs4850/c$/folderAtRoot" @@ -123260,7 +124402,7 @@ var ts; invalidateResolutionOfFile: invalidateResolutionOfFile, invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, - createHasInvalidatedResolution: createHasInvalidatedResolution, + createHasInvalidatedResolutions: createHasInvalidatedResolutions, isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, @@ -123315,17 +124457,13 @@ var ts; var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); return !!value && !!value.length; } - function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + function createHasInvalidatedResolutions(customHasInvalidatedResolutions) { // Ensure pending resolutions are applied invalidateResolutionsOfFailedLookupLocations(); - if (forceAllFilesAsInvalidated) { - // Any file asked would have invalidated resolution - filesWithInvalidatedResolutions = undefined; - return ts.returnTrue; - } var collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = undefined; - return function (path) { return (!!collected && collected.has(path)) || + return function (path) { return customHasInvalidatedResolutions(path) || + !!(collected === null || collected === void 0 ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function startCachingPerDirectoryResolution() { @@ -124686,15 +125824,21 @@ var ts; return undefined; } function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { + var normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPaths === undefined) { + return undefined; + } + var normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePaths = ts.flatMap(normalizedSourcePaths, function (sourcePath) { + return ts.map(normalizedTargetPaths, function (targetPath) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName)); }); + }); + var shortest = ts.min(relativePaths, ts.compareNumberOfDirectorySeparators); + if (!shortest) { return undefined; } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs - ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions) - : ts.removeFileExtension(relativePath); + ? removeExtensionAndIndexPostFix(shortest, ending, compilerOptions) + : ts.removeFileExtension(shortest); } function tryGetModuleNameAsNodeModule(_a, _b, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { var path = _a.path, isRedirect = _a.isRedirect; @@ -124762,7 +125906,7 @@ var ts; var maybeBlockedByTypesVersions = false; var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) { - var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); + var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.contents.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); var importMode = overrideMode || importingSourceFile.impliedNodeFormat; if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"]; @@ -124831,8 +125975,8 @@ var ts; } } } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { + function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.mapDefined(rootDirs, function (rootDir) { var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); return relativePath !== undefined && isPathRelativeToParent(relativePath) ? undefined : relativePath; }); @@ -125124,7 +126268,7 @@ var ts; case ts.ModuleKind.CommonJS: if (file.packageJsonScope) { (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( - /*details*/ undefined, file.packageJsonScope.packageJsonContent.type ? + /*details*/ undefined, file.packageJsonScope.contents.packageJsonContent.type ? ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); } @@ -125543,18 +126687,14 @@ var ts; if (host.getBuildInfo) { // host provides buildinfo, get it from there. This allows host to cache it buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath); - if (!buildInfo) - return undefined; } else { var content = host.readFile(buildInfoPath); if (!content) return undefined; - buildInfo = ts.getBuildInfo(content); + buildInfo = ts.getBuildInfo(buildInfoPath, content); } - if (buildInfo.version !== ts.version) - return undefined; - if (!buildInfo.program) + if (!buildInfo || buildInfo.version !== ts.version || !buildInfo.program) return undefined; return ts.createBuilderProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); } @@ -125709,6 +126849,10 @@ var ts; ts.maybeBind(host, host.getModuleResolutionCache) : (function () { return resolutionCache.getModuleResolutionCache(); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + // All resolutions are invalid if user provided resolutions and didnt supply hasInvalidatedResolutions + var customHasInvalidatedResolutions = userProvidedResolution ? + ts.maybeBind(host, host.hasInvalidatedResolutions) || ts.returnTrue : + ts.returnFalse; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); // Update the wild card directory watch @@ -125774,9 +126918,9 @@ var ts; resolutionCache.clear(); } } - // All resolutions are invalid if user provided resolutions - var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + var hasInvalidatedResolutions = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions); + var _a = ts.changeCompilerHostLikeToUseCache(compilerHost, toPath), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile; + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, function (fileName) { return compilerHost.fileExists(fileName); }, hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); @@ -125789,15 +126933,20 @@ var ts; if (reportFileChangeDetectedOnCreateProgram) { reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); } - createNewProgram(hasInvalidatedResolution); + createNewProgram(hasInvalidatedResolutions); } reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { host.afterProgramCreate(builderProgram); } + compilerHost.readFile = originalReadFile; + compilerHost.fileExists = originalFileExists; + compilerHost.directoryExists = originalDirectoryExists; + compilerHost.createDirectory = originalCreateDirectory; + compilerHost.writeFile = originalWriteFile; return builderProgram; } - function createNewProgram(hasInvalidatedResolution) { + function createNewProgram(hasInvalidatedResolutions) { // Compile the program writeLog("CreatingProgramWith::"); writeLog(" roots: ".concat(JSON.stringify(rootFileNames))); @@ -125808,7 +126957,7 @@ var ts; hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); - compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasInvalidatedResolutions = hasInvalidatedResolutions; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; var oldProgram = getCurrentProgram(); builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); @@ -126272,19 +127421,20 @@ var ts; */ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend"; UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing"; - UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf"; - UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream"; - UpToDateStatusType[UpToDateStatusType["OutOfDateBuildInfo"] = 7] = "OutOfDateBuildInfo"; - UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 8] = "UpstreamOutOfDate"; - UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 9] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 10] = "ComputingUpstream"; - UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 11] = "TsVersionOutputOfDate"; - UpToDateStatusType[UpToDateStatusType["UpToDateWithInputFileText"] = 12] = "UpToDateWithInputFileText"; + UpToDateStatusType[UpToDateStatusType["ErrorReadingFile"] = 5] = "ErrorReadingFile"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 6] = "OutOfDateWithSelf"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 7] = "OutOfDateWithUpstream"; + UpToDateStatusType[UpToDateStatusType["OutOfDateBuildInfo"] = 8] = "OutOfDateBuildInfo"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 9] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 10] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 11] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 12] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["UpToDateWithInputFileText"] = 13] = "UpToDateWithInputFileText"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 13] = "ContainerOnly"; - UpToDateStatusType[UpToDateStatusType["ForceBuild"] = 14] = "ForceBuild"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 14] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ForceBuild"] = 15] = "ForceBuild"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); function resolveConfigFileProjectName(project) { if (ts.fileExtensionIs(project, ".json" /* Extension.Json */)) { @@ -126502,6 +127652,7 @@ var ts; if (value) { return isParsedCommandLine(value) ? value : undefined; } + ts.performance.mark("SolutionBuilder::beforeConfigFileParsing"); var diagnostic; var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host; var parsed; @@ -126516,6 +127667,8 @@ var ts; parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; } configFileCache.set(configFilePath, parsed || diagnostic); + ts.performance.mark("SolutionBuilder::afterConfigFileParsing"); + ts.performance.measure("SolutionBuilder::Config file parsing", "SolutionBuilder::beforeConfigFileParsing", "SolutionBuilder::afterConfigFileParsing"); return parsed; } function resolveProjectName(state, name) { @@ -126715,6 +127868,7 @@ var ts; if (updateOutputFileStampsPending) { updateOutputTimestamps(state, config, projectPath); } + ts.performance.mark("SolutionBuilder::Timestamps only updates"); return doneInvalidatedProject(state, projectPath); } }; @@ -126808,6 +127962,10 @@ var ts; }; function done(cancellationToken, writeFile, customTransformers) { executeSteps(BuildStep.Done, cancellationToken, writeFile, customTransformers); + if (kind === InvalidatedProjectKind.Build) + ts.performance.mark("SolutionBuilder::Projects built"); + else + ts.performance.mark("SolutionBuilder::Bundles updated"); return doneInvalidatedProject(state, projectPath); } function withProgramOrUndefined(action) { @@ -126986,13 +128144,13 @@ var ts; var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; - var existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo; + var existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo || undefined; outputFiles.forEach(function (_a) { var _b, _c; var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; emittedOutputs.set(toPath(state, name), name); if (buildInfo) { - if (((_b = buildInfo.program) === null || _b === void 0 ? void 0 : _b.outSignature) !== ((_c = existingBuildInfo.program) === null || _c === void 0 ? void 0 : _c.outSignature)) { + if (((_b = buildInfo.program) === null || _b === void 0 ? void 0 : _b.outSignature) !== ((_c = existingBuildInfo === null || existingBuildInfo === void 0 ? void 0 : existingBuildInfo.program) === null || _c === void 0 ? void 0 : _c.outSignature)) { resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; } setBuildInfo(state, buildInfo, projectPath, config.options, resultFlags); @@ -127285,8 +128443,7 @@ var ts; return existing.buildInfo || undefined; } var value = state.readFileWithCache(buildInfoPath); - var buildInfo = value ? ts.getBuildInfo(value) : undefined; - ts.Debug.assert(modifiedTime || !buildInfo); + var buildInfo = value ? ts.getBuildInfo(buildInfoPath, value) : undefined; state.buildInfoCache.set(resolvedConfigPath, { path: path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || ts.missingFileModifiedTime }); return buildInfo; } @@ -127371,7 +128528,14 @@ var ts; missingOutputFileName: buildInfoPath }; } - var buildInfo = ts.Debug.checkDefined(getBuildInfo(state, buildInfoPath, resolvedPath, buildInfoTime)); + var buildInfo = getBuildInfo(state, buildInfoPath, resolvedPath, buildInfoTime); + if (!buildInfo) { + // Error reading buildInfo + return { + type: ts.UpToDateStatusType.ErrorReadingFile, + fileName: buildInfoPath + }; + } if ((buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { return { type: ts.UpToDateStatusType.TsVersionOutputOfDate, @@ -127380,8 +128544,15 @@ var ts; } if (buildInfo.program) { // If there are pending changes that are not emitted, project is out of date + // When there are syntax errors, changeFileSet will have list of files changed (irrespective of noEmit) + // But in case of semantic error we need special treatment. + // Checking presence of affectedFilesPendingEmit list is fast and good way to tell if there were semantic errors and file emit was blocked + // But if noEmit is true, affectedFilesPendingEmit will have file list even if there are no semantic errors to preserve list of files to be emitted when running with noEmit false + // So with noEmit set to true, check on semantic diagnostics needs to be explicit as oppose to when it is false when only files pending emit is sufficient if (((_a = buildInfo.program.changeFileSet) === null || _a === void 0 ? void 0 : _a.length) || - (!project.options.noEmit && ((_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length))) { + (!project.options.noEmit ? + (_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length : + ts.some(buildInfo.program.semanticDiagnosticsPerFile, ts.isArray))) { return { type: ts.UpToDateStatusType.OutOfDateBuildInfo, buildInfoFile: buildInfoPath @@ -127556,7 +128727,10 @@ var ts; if (prior !== undefined) { return prior; } + ts.performance.mark("SolutionBuilder::beforeUpToDateCheck"); var actual = getUpToDateStatusWorker(state, project, resolvedPath); + ts.performance.mark("SolutionBuilder::afterUpToDateCheck"); + ts.performance.measure("SolutionBuilder::Up-to-date check", "SolutionBuilder::beforeUpToDateCheck", "SolutionBuilder::afterUpToDateCheck"); state.projectStatus.set(resolvedPath, actual); return actual; } @@ -127694,6 +128868,13 @@ var ts; } } function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { + ts.performance.mark("SolutionBuilder::beforeBuild"); + var result = buildWorker(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences); + ts.performance.mark("SolutionBuilder::afterBuild"); + ts.performance.measure("SolutionBuilder::Build", "SolutionBuilder::beforeBuild", "SolutionBuilder::afterBuild"); + return result; + } + function buildWorker(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -127721,6 +128902,13 @@ var ts; : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { + ts.performance.mark("SolutionBuilder::beforeClean"); + var result = cleanWorker(state, project, onlyReferences); + ts.performance.mark("SolutionBuilder::afterClean"); + ts.performance.measure("SolutionBuilder::Clean", "SolutionBuilder::beforeClean", "SolutionBuilder::afterClean"); + return result; + } + function cleanWorker(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -127794,6 +128982,14 @@ var ts; state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, state, changeDetected); } function buildNextInvalidatedProject(state, changeDetected) { + ts.performance.mark("SolutionBuilder::beforeBuild"); + var buildOrder = buildNextInvalidatedProjectWorker(state, changeDetected); + ts.performance.mark("SolutionBuilder::afterBuild"); + ts.performance.measure("SolutionBuilder::Build", "SolutionBuilder::beforeBuild", "SolutionBuilder::afterBuild"); + if (buildOrder) + reportErrorSummary(state, buildOrder); + } + function buildNextInvalidatedProjectWorker(state, changeDetected) { state.timerToBuildInvalidatedProject = undefined; if (state.reportFileChangeDetected) { state.reportFileChangeDetected = false; @@ -127826,7 +129022,7 @@ var ts; } } disableCache(state); - reportErrorSummary(state, buildOrder); + return buildOrder; } function watchConfigFile(state, resolved, resolvedPath, parsed) { if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) @@ -127881,6 +129077,7 @@ var ts; function startWatching(state, buildOrder) { if (!state.watchAllProjectsPending) return; + ts.performance.mark("SolutionBuilder::beforeWatcherCreation"); state.watchAllProjectsPending = false; for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) { var resolved = _a[_i]; @@ -127898,6 +129095,8 @@ var ts; watchPackageJsonFiles(state, resolved, resolvedPath, cfg); } } + ts.performance.mark("SolutionBuilder::afterWatcherCreation"); + ts.performance.measure("SolutionBuilder::Watcher creation", "SolutionBuilder::beforeWatcherCreation", "SolutionBuilder::afterWatcherCreation"); } function stopWatching(state) { ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher); @@ -128011,6 +129210,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.OutputMissing: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName)); + case ts.UpToDateStatusType.ErrorReadingFile: + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_there_was_error_reading_file_1, relName(state, configFileName), relName(state, status.fileName)); case ts.UpToDateStatusType.OutOfDateBuildInfo: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, relName(state, configFileName), relName(state, status.buildInfoFile)); case ts.UpToDateStatusType.UpToDate: @@ -128532,6 +129733,12 @@ var ts; SemanticClassificationFormat["Original"] = "original"; SemanticClassificationFormat["TwentyTwenty"] = "2020"; })(SemanticClassificationFormat = ts.SemanticClassificationFormat || (ts.SemanticClassificationFormat = {})); + var OrganizeImportsMode; + (function (OrganizeImportsMode) { + OrganizeImportsMode["All"] = "All"; + OrganizeImportsMode["SortAndCombine"] = "SortAndCombine"; + OrganizeImportsMode["RemoveUnused"] = "RemoveUnused"; + })(OrganizeImportsMode = ts.OrganizeImportsMode || (ts.OrganizeImportsMode = {})); var CompletionTriggerKind; (function (CompletionTriggerKind) { /** Completion was triggered by typing an identifier, manual invocation (e.g Ctrl+Space) or via API. */ @@ -128718,6 +129925,8 @@ var ts; * interface Y { foo:number; } */ ScriptElementKind["memberVariableElement"] = "property"; + /** class X { [public|private]* accessor foo: number; } */ + ScriptElementKind["memberAccessorVariableElement"] = "accessor"; /** * class X { constructor() { } } * class X { static { } } @@ -128850,37 +130059,37 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* SemanticMeaning.All */ : 1 /* SemanticMeaning.Value */; - case 164 /* SyntaxKind.Parameter */: - case 203 /* SyntaxKind.BindingElement */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 292 /* SyntaxKind.CatchClause */: - case 285 /* SyntaxKind.JsxAttribute */: + case 166 /* SyntaxKind.Parameter */: + case 205 /* SyntaxKind.BindingElement */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 295 /* SyntaxKind.CatchClause */: + case 288 /* SyntaxKind.JsxAttribute */: return 1 /* SemanticMeaning.Value */; - case 163 /* SyntaxKind.TypeParameter */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 182 /* SyntaxKind.TypeLiteral */: + case 165 /* SyntaxKind.TypeParameter */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 184 /* SyntaxKind.TypeLiteral */: return 2 /* SemanticMeaning.Type */; - case 345 /* SyntaxKind.JSDocTypedefTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* SemanticMeaning.Value */ | 2 /* SemanticMeaning.Type */ : 2 /* SemanticMeaning.Type */; - case 299 /* SyntaxKind.EnumMember */: - case 257 /* SyntaxKind.ClassDeclaration */: + case 302 /* SyntaxKind.EnumMember */: + case 260 /* SyntaxKind.ClassDeclaration */: return 1 /* SemanticMeaning.Value */ | 2 /* SemanticMeaning.Type */; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* SemanticMeaning.Namespace */ | 1 /* SemanticMeaning.Value */; } @@ -128890,16 +130099,16 @@ var ts; else { return 4 /* SemanticMeaning.Namespace */; } - case 260 /* SyntaxKind.EnumDeclaration */: - case 269 /* SyntaxKind.NamedImports */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 266 /* SyntaxKind.ImportDeclaration */: - case 271 /* SyntaxKind.ExportAssignment */: - case 272 /* SyntaxKind.ExportDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 272 /* SyntaxKind.NamedImports */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 274 /* SyntaxKind.ExportAssignment */: + case 275 /* SyntaxKind.ExportDeclaration */: return 7 /* SemanticMeaning.All */; // An external module can be a Value - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: return 4 /* SemanticMeaning.Namespace */ | 1 /* SemanticMeaning.Value */; } return 7 /* SemanticMeaning.All */; @@ -128908,7 +130117,7 @@ var ts; function getMeaningFromLocation(node) { node = getAdjustedReferenceLocation(node); var parent = node.parent; - if (node.kind === 305 /* SyntaxKind.SourceFile */) { + if (node.kind === 308 /* SyntaxKind.SourceFile */) { return 1 /* SemanticMeaning.Value */; } else if (ts.isExportAssignment(parent) @@ -128951,11 +130160,11 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - var name = node.kind === 161 /* SyntaxKind.QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ ? 7 /* SemanticMeaning.All */ : 4 /* SemanticMeaning.Namespace */; + var name = node.kind === 163 /* SyntaxKind.QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ ? 7 /* SemanticMeaning.All */ : 4 /* SemanticMeaning.Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 161 /* SyntaxKind.QualifiedName */) { + while (node.parent.kind === 163 /* SyntaxKind.QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -128967,27 +130176,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 161 /* SyntaxKind.QualifiedName */) { - while (root.parent && root.parent.kind === 161 /* SyntaxKind.QualifiedName */) { + if (root.parent.kind === 163 /* SyntaxKind.QualifiedName */) { + while (root.parent && root.parent.kind === 163 /* SyntaxKind.QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 178 /* SyntaxKind.TypeReference */ && !isLastClause; + return root.parent.kind === 180 /* SyntaxKind.TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + if (root.parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 228 /* SyntaxKind.ExpressionWithTypeArguments */ && root.parent.parent.kind === 291 /* SyntaxKind.HeritageClause */) { + if (!isLastClause && root.parent.kind === 230 /* SyntaxKind.ExpressionWithTypeArguments */ && root.parent.parent.kind === 294 /* SyntaxKind.HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 257 /* SyntaxKind.ClassDeclaration */ && root.parent.parent.token === 117 /* SyntaxKind.ImplementsKeyword */) || - (decl.kind === 258 /* SyntaxKind.InterfaceDeclaration */ && root.parent.parent.token === 94 /* SyntaxKind.ExtendsKeyword */); + return (decl.kind === 260 /* SyntaxKind.ClassDeclaration */ && root.parent.parent.token === 117 /* SyntaxKind.ImplementsKeyword */) || + (decl.kind === 261 /* SyntaxKind.InterfaceDeclaration */ && root.parent.parent.token === 94 /* SyntaxKind.ExtendsKeyword */); } return false; } @@ -128998,15 +130207,15 @@ var ts; switch (node.kind) { case 108 /* SyntaxKind.ThisKeyword */: return !ts.isExpressionNode(node); - case 192 /* SyntaxKind.ThisType */: + case 194 /* SyntaxKind.ThisType */: return true; } switch (node.parent.kind) { - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return true; - case 200 /* SyntaxKind.ImportType */: + case 202 /* SyntaxKind.ImportType */: return !node.parent.isTypeOf; - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return ts.isPartOfTypeNode(node.parent); } return false; @@ -129073,7 +130282,7 @@ var ts; ts.climbPastPropertyOrElementAccess = climbPastPropertyOrElementAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 250 /* SyntaxKind.LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 253 /* SyntaxKind.LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -129134,22 +130343,22 @@ var ts; ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 299 /* SyntaxKind.EnumMember */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 261 /* SyntaxKind.ModuleDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 302 /* SyntaxKind.EnumMember */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 264 /* SyntaxKind.ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return node.parent.argumentExpression === node; - case 162 /* SyntaxKind.ComputedPropertyName */: + case 164 /* SyntaxKind.ComputedPropertyName */: return true; - case 196 /* SyntaxKind.LiteralType */: - return node.parent.parent.kind === 194 /* SyntaxKind.IndexedAccessType */; + case 198 /* SyntaxKind.LiteralType */: + return node.parent.parent.kind === 196 /* SyntaxKind.IndexedAccessType */; default: return false; } @@ -129173,17 +130382,17 @@ var ts; return undefined; } switch (node.kind) { - case 305 /* SyntaxKind.SourceFile */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: + case 308 /* SyntaxKind.SourceFile */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return node; } } @@ -129191,56 +130400,56 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: return ts.isExternalModule(node) ? "module" /* ScriptElementKind.moduleElement */ : "script" /* ScriptElementKind.scriptElement */; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return "module" /* ScriptElementKind.moduleElement */; - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: return "class" /* ScriptElementKind.classElement */; - case 258 /* SyntaxKind.InterfaceDeclaration */: return "interface" /* ScriptElementKind.interfaceElement */; - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 345 /* SyntaxKind.JSDocTypedefTag */: + case 261 /* SyntaxKind.InterfaceDeclaration */: return "interface" /* ScriptElementKind.interfaceElement */; + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: return "type" /* ScriptElementKind.typeElement */; - case 260 /* SyntaxKind.EnumDeclaration */: return "enum" /* ScriptElementKind.enumElement */; - case 254 /* SyntaxKind.VariableDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return "enum" /* ScriptElementKind.enumElement */; + case 257 /* SyntaxKind.VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 214 /* SyntaxKind.ArrowFunction */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: return "function" /* ScriptElementKind.functionElement */; - case 172 /* SyntaxKind.GetAccessor */: return "getter" /* ScriptElementKind.memberGetAccessorElement */; - case 173 /* SyntaxKind.SetAccessor */: return "setter" /* ScriptElementKind.memberSetAccessorElement */; - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 174 /* SyntaxKind.GetAccessor */: return "getter" /* ScriptElementKind.memberGetAccessorElement */; + case 175 /* SyntaxKind.SetAccessor */: return "setter" /* ScriptElementKind.memberSetAccessorElement */; + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: return "method" /* ScriptElementKind.memberFunctionElement */; - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: var initializer = node.initializer; return ts.isFunctionLike(initializer) ? "method" /* ScriptElementKind.memberFunctionElement */ : "property" /* ScriptElementKind.memberVariableElement */; - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 298 /* SyntaxKind.SpreadAssignment */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 301 /* SyntaxKind.SpreadAssignment */: return "property" /* ScriptElementKind.memberVariableElement */; - case 176 /* SyntaxKind.IndexSignature */: return "index" /* ScriptElementKind.indexSignatureElement */; - case 175 /* SyntaxKind.ConstructSignature */: return "construct" /* ScriptElementKind.constructSignatureElement */; - case 174 /* SyntaxKind.CallSignature */: return "call" /* ScriptElementKind.callSignatureElement */; - case 171 /* SyntaxKind.Constructor */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 178 /* SyntaxKind.IndexSignature */: return "index" /* ScriptElementKind.indexSignatureElement */; + case 177 /* SyntaxKind.ConstructSignature */: return "construct" /* ScriptElementKind.constructSignatureElement */; + case 176 /* SyntaxKind.CallSignature */: return "call" /* ScriptElementKind.callSignatureElement */; + case 173 /* SyntaxKind.Constructor */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: return "constructor" /* ScriptElementKind.constructorImplementationElement */; - case 163 /* SyntaxKind.TypeParameter */: return "type parameter" /* ScriptElementKind.typeParameterElement */; - case 299 /* SyntaxKind.EnumMember */: return "enum member" /* ScriptElementKind.enumMemberElement */; - case 164 /* SyntaxKind.Parameter */: return ts.hasSyntacticModifier(node, 16476 /* ModifierFlags.ParameterPropertyModifier */) ? "property" /* ScriptElementKind.memberVariableElement */ : "parameter" /* ScriptElementKind.parameterElement */; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 275 /* SyntaxKind.ExportSpecifier */: - case 268 /* SyntaxKind.NamespaceImport */: - case 274 /* SyntaxKind.NamespaceExport */: + case 165 /* SyntaxKind.TypeParameter */: return "type parameter" /* ScriptElementKind.typeParameterElement */; + case 302 /* SyntaxKind.EnumMember */: return "enum member" /* ScriptElementKind.enumMemberElement */; + case 166 /* SyntaxKind.Parameter */: return ts.hasSyntacticModifier(node, 16476 /* ModifierFlags.ParameterPropertyModifier */) ? "property" /* ScriptElementKind.memberVariableElement */ : "parameter" /* ScriptElementKind.parameterElement */; + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: + case 271 /* SyntaxKind.NamespaceImport */: + case 277 /* SyntaxKind.NamespaceExport */: return "alias" /* ScriptElementKind.alias */; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { @@ -129269,7 +130478,7 @@ var ts; } case 79 /* SyntaxKind.Identifier */: return ts.isImportClause(node.parent) ? "alias" /* ScriptElementKind.alias */ : "" /* ScriptElementKind.unknown */; - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: var scriptKind = getNodeKind(node.expression); // If the expression didn't come back with something (like it does for an identifiers) return scriptKind === "" /* ScriptElementKind.unknown */ ? "const" /* ScriptElementKind.constElement */ : scriptKind; @@ -129292,7 +130501,7 @@ var ts; return true; case 79 /* SyntaxKind.Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 164 /* SyntaxKind.Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 166 /* SyntaxKind.Parameter */; default: return false; } @@ -129357,42 +130566,42 @@ var ts; return false; } switch (n.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 182 /* SyntaxKind.TypeLiteral */: - case 235 /* SyntaxKind.Block */: - case 262 /* SyntaxKind.ModuleBlock */: - case 263 /* SyntaxKind.CaseBlock */: - case 269 /* SyntaxKind.NamedImports */: - case 273 /* SyntaxKind.NamedExports */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 184 /* SyntaxKind.TypeLiteral */: + case 238 /* SyntaxKind.Block */: + case 265 /* SyntaxKind.ModuleBlock */: + case 266 /* SyntaxKind.CaseBlock */: + case 272 /* SyntaxKind.NamedImports */: + case 276 /* SyntaxKind.NamedExports */: return nodeEndsWith(n, 19 /* SyntaxKind.CloseBraceToken */, sourceFile); - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return isCompletedNode(n.block, sourceFile); - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: if (!n.arguments) { return true; } // falls through - case 208 /* SyntaxKind.CallExpression */: - case 212 /* SyntaxKind.ParenthesizedExpression */: - case 191 /* SyntaxKind.ParenthesizedType */: + case 210 /* SyntaxKind.CallExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: + case 193 /* SyntaxKind.ParenthesizedType */: return nodeEndsWith(n, 21 /* SyntaxKind.CloseParenToken */, sourceFile); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 174 /* SyntaxKind.CallSignature */: - case 214 /* SyntaxKind.ArrowFunction */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 216 /* SyntaxKind.ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -129402,65 +130611,65 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 21 /* SyntaxKind.CloseParenToken */, sourceFile); - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return !!n.body && isCompletedNode(n.body, sourceFile); - case 239 /* SyntaxKind.IfStatement */: + case 242 /* SyntaxKind.IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 26 /* SyntaxKind.SemicolonToken */, sourceFile); - case 204 /* SyntaxKind.ArrayLiteralExpression */: - case 202 /* SyntaxKind.ArrayBindingPattern */: - case 207 /* SyntaxKind.ElementAccessExpression */: - case 162 /* SyntaxKind.ComputedPropertyName */: - case 184 /* SyntaxKind.TupleType */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: + case 204 /* SyntaxKind.ArrayBindingPattern */: + case 209 /* SyntaxKind.ElementAccessExpression */: + case 164 /* SyntaxKind.ComputedPropertyName */: + case 186 /* SyntaxKind.TupleType */: return nodeEndsWith(n, 23 /* SyntaxKind.CloseBracketToken */, sourceFile); - case 176 /* SyntaxKind.IndexSignature */: + case 178 /* SyntaxKind.IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 23 /* SyntaxKind.CloseBracketToken */, sourceFile); - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 241 /* SyntaxKind.WhileStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 244 /* SyntaxKind.WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 240 /* SyntaxKind.DoStatement */: + case 243 /* SyntaxKind.DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; return hasChildOfKind(n, 115 /* SyntaxKind.WhileKeyword */, sourceFile) ? nodeEndsWith(n, 21 /* SyntaxKind.CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); - case 181 /* SyntaxKind.TypeQuery */: + case 183 /* SyntaxKind.TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 216 /* SyntaxKind.TypeOfExpression */: - case 215 /* SyntaxKind.DeleteExpression */: - case 217 /* SyntaxKind.VoidExpression */: - case 224 /* SyntaxKind.YieldExpression */: - case 225 /* SyntaxKind.SpreadElement */: + case 218 /* SyntaxKind.TypeOfExpression */: + case 217 /* SyntaxKind.DeleteExpression */: + case 219 /* SyntaxKind.VoidExpression */: + case 226 /* SyntaxKind.YieldExpression */: + case 227 /* SyntaxKind.SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 223 /* SyntaxKind.TemplateExpression */: + case 225 /* SyntaxKind.TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 233 /* SyntaxKind.TemplateSpan */: + case 236 /* SyntaxKind.TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 272 /* SyntaxKind.ExportDeclaration */: - case 266 /* SyntaxKind.ImportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 222 /* SyntaxKind.ConditionalExpression */: + case 224 /* SyntaxKind.ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -129575,6 +130784,8 @@ var ts; return lastTypeNode; } function getContextualTypeFromParentOrAncestorTypeNode(node, checker) { + if (node.flags & (8388608 /* NodeFlags.JSDoc */ & ~262144 /* NodeFlags.JavaScriptFile */)) + return undefined; var contextualType = getContextualTypeFromParent(node, checker); if (contextualType) return contextualType; @@ -129585,13 +130796,13 @@ var ts; function getAdjustedLocationForDeclaration(node, forRename) { if (!forRename) { switch (node.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: return getAdjustedLocationForClass(node); - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: return getAdjustedLocationForFunction(node); - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return node; } } @@ -129686,11 +130897,11 @@ var ts; node.kind === 98 /* SyntaxKind.FunctionKeyword */ ? ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(node) : node.kind === 118 /* SyntaxKind.InterfaceKeyword */ ? ts.isInterfaceDeclaration(parent) : node.kind === 92 /* SyntaxKind.EnumKeyword */ ? ts.isEnumDeclaration(parent) : - node.kind === 152 /* SyntaxKind.TypeKeyword */ ? ts.isTypeAliasDeclaration(parent) : - node.kind === 142 /* SyntaxKind.NamespaceKeyword */ || node.kind === 141 /* SyntaxKind.ModuleKeyword */ ? ts.isModuleDeclaration(parent) : + node.kind === 154 /* SyntaxKind.TypeKeyword */ ? ts.isTypeAliasDeclaration(parent) : + node.kind === 143 /* SyntaxKind.NamespaceKeyword */ || node.kind === 142 /* SyntaxKind.ModuleKeyword */ ? ts.isModuleDeclaration(parent) : node.kind === 100 /* SyntaxKind.ImportKeyword */ ? ts.isImportEqualsDeclaration(parent) : - node.kind === 136 /* SyntaxKind.GetKeyword */ ? ts.isGetAccessorDeclaration(parent) : - node.kind === 149 /* SyntaxKind.SetKeyword */ && ts.isSetAccessorDeclaration(parent)) { + node.kind === 137 /* SyntaxKind.GetKeyword */ ? ts.isGetAccessorDeclaration(parent) : + node.kind === 151 /* SyntaxKind.SetKeyword */ && ts.isSetAccessorDeclaration(parent)) { var location = getAdjustedLocationForDeclaration(parent, forRename); if (location) { return location; @@ -129704,7 +130915,7 @@ var ts; return decl.name; } } - if (node.kind === 152 /* SyntaxKind.TypeKeyword */) { + if (node.kind === 154 /* SyntaxKind.TypeKeyword */) { // import /**/type [|name|] from ...; // import /**/type { [|name|] } from ...; // import /**/type { propertyName as [|name|] } from ...; @@ -129730,7 +130941,7 @@ var ts; // import * /**/as [|name|] ... // export { propertyName /**/as [|name|] } ... // export * /**/as [|name|] ... - if (node.kind === 127 /* SyntaxKind.AsKeyword */) { + if (node.kind === 128 /* SyntaxKind.AsKeyword */) { if (ts.isImportSpecifier(parent) && parent.propertyName || ts.isExportSpecifier(parent) && parent.propertyName || ts.isNamespaceImport(parent) || @@ -129771,12 +130982,12 @@ var ts; } } // import name = /**/require("[|module|]"); - if (node.kind === 146 /* SyntaxKind.RequireKeyword */ && ts.isExternalModuleReference(parent)) { + if (node.kind === 147 /* SyntaxKind.RequireKeyword */ && ts.isExternalModuleReference(parent)) { return parent.expression; } // import ... /**/from "[|module|]"; // export ... /**/from "[|module|]"; - if (node.kind === 156 /* SyntaxKind.FromKeyword */ && (ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent)) && parent.moduleSpecifier) { + if (node.kind === 158 /* SyntaxKind.FromKeyword */ && (ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent)) && parent.moduleSpecifier) { return parent.moduleSpecifier; } // class ... /**/extends [|name|] ... @@ -129801,7 +131012,7 @@ var ts; } } // ... T extends /**/infer [|U|] ? ... - if (node.kind === 137 /* SyntaxKind.InferKeyword */ && ts.isInferTypeNode(parent)) { + if (node.kind === 138 /* SyntaxKind.InferKeyword */ && ts.isInferTypeNode(parent)) { return parent.typeParameter.name; } // { [ [|K|] /**/in keyof T]: ... } @@ -129809,12 +131020,12 @@ var ts; return parent.name; } // /**/keyof [|T|] - if (node.kind === 140 /* SyntaxKind.KeyOfKeyword */ && ts.isTypeOperatorNode(parent) && parent.operator === 140 /* SyntaxKind.KeyOfKeyword */ && + if (node.kind === 141 /* SyntaxKind.KeyOfKeyword */ && ts.isTypeOperatorNode(parent) && parent.operator === 141 /* SyntaxKind.KeyOfKeyword */ && ts.isTypeReferenceNode(parent.type)) { return parent.type.typeName; } // /**/readonly [|name|][] - if (node.kind === 145 /* SyntaxKind.ReadonlyKeyword */ && ts.isTypeOperatorNode(parent) && parent.operator === 145 /* SyntaxKind.ReadonlyKeyword */ && + if (node.kind === 146 /* SyntaxKind.ReadonlyKeyword */ && ts.isTypeOperatorNode(parent) && parent.operator === 146 /* SyntaxKind.ReadonlyKeyword */ && ts.isArrayTypeNode(parent.type) && ts.isTypeReferenceNode(parent.type.elementType)) { return parent.type.elementType.typeName; } @@ -129832,7 +131043,7 @@ var ts; if (node.kind === 103 /* SyntaxKind.NewKeyword */ && ts.isNewExpression(parent) || node.kind === 114 /* SyntaxKind.VoidKeyword */ && ts.isVoidExpression(parent) || node.kind === 112 /* SyntaxKind.TypeOfKeyword */ && ts.isTypeOfExpression(parent) || - node.kind === 132 /* SyntaxKind.AwaitKeyword */ && ts.isAwaitExpression(parent) || + node.kind === 133 /* SyntaxKind.AwaitKeyword */ && ts.isAwaitExpression(parent) || node.kind === 125 /* SyntaxKind.YieldKeyword */ && ts.isYieldExpression(parent) || node.kind === 89 /* SyntaxKind.DeleteKeyword */ && ts.isDeleteExpression(parent)) { if (parent.expression) { @@ -129845,13 +131056,13 @@ var ts; return ts.skipOuterExpressions(parent.right); } // left /**/as [|name|] - if (node.kind === 127 /* SyntaxKind.AsKeyword */ && ts.isAsExpression(parent) && ts.isTypeReferenceNode(parent.type)) { + if (node.kind === 128 /* SyntaxKind.AsKeyword */ && ts.isAsExpression(parent) && ts.isTypeReferenceNode(parent.type)) { return parent.type.typeName; } // for (... /**/in [|name|]) // for (... /**/of [|name|]) if (node.kind === 101 /* SyntaxKind.InKeyword */ && ts.isForInStatement(parent) || - node.kind === 160 /* SyntaxKind.OfKeyword */ && ts.isForOfStatement(parent)) { + node.kind === 162 /* SyntaxKind.OfKeyword */ && ts.isForOfStatement(parent)) { return ts.skipOuterExpressions(parent.expression); } } @@ -130083,7 +131294,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 305 /* SyntaxKind.SourceFile */ || n.kind === 1 /* SyntaxKind.EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 308 /* SyntaxKind.SourceFile */ || n.kind === 1 /* SyntaxKind.EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. @@ -130114,7 +131325,7 @@ var ts; for (var i = exclusiveStartPosition - 1; i >= 0; i--) { var child = children[i]; if (isWhiteSpaceOnlyJsxText(child)) { - if (i === 0 && (parentKind === 11 /* SyntaxKind.JsxText */ || parentKind === 279 /* SyntaxKind.JsxSelfClosingElement */)) { + if (i === 0 && (parentKind === 11 /* SyntaxKind.JsxText */ || parentKind === 282 /* SyntaxKind.JsxSelfClosingElement */)) { ts.Debug.fail("`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); } } @@ -130158,17 +131369,17 @@ var ts; return true; } //
{ |
or
- if (token.kind === 29 /* SyntaxKind.LessThanToken */ && token.parent.kind === 288 /* SyntaxKind.JsxExpression */) { + if (token.kind === 29 /* SyntaxKind.LessThanToken */ && token.parent.kind === 291 /* SyntaxKind.JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 19 /* SyntaxKind.CloseBraceToken */ && token.parent.kind === 288 /* SyntaxKind.JsxExpression */) { + if (token && token.kind === 19 /* SyntaxKind.CloseBraceToken */ && token.parent.kind === 291 /* SyntaxKind.JsxExpression */) { return true; } //
|
- if (token.kind === 29 /* SyntaxKind.LessThanToken */ && token.parent.kind === 281 /* SyntaxKind.JsxClosingElement */) { + if (token.kind === 29 /* SyntaxKind.LessThanToken */ && token.parent.kind === 284 /* SyntaxKind.JsxClosingElement */) { return true; } return false; @@ -130199,7 +131410,7 @@ var ts; function isInsideJsxElement(sourceFile, position) { function isInsideJsxElementTraversal(node) { while (node) { - if (node.kind >= 279 /* SyntaxKind.JsxSelfClosingElement */ && node.kind <= 288 /* SyntaxKind.JsxExpression */ + if (node.kind >= 282 /* SyntaxKind.JsxSelfClosingElement */ && node.kind <= 291 /* SyntaxKind.JsxExpression */ || node.kind === 11 /* SyntaxKind.JsxText */ || node.kind === 29 /* SyntaxKind.LessThanToken */ || node.kind === 31 /* SyntaxKind.GreaterThanToken */ @@ -130209,7 +131420,7 @@ var ts; || node.kind === 43 /* SyntaxKind.SlashToken */) { node = node.parent; } - else if (node.kind === 278 /* SyntaxKind.JsxElement */) { + else if (node.kind === 281 /* SyntaxKind.JsxElement */) { if (position > node.getStart(sourceFile)) return true; node = node.parent; @@ -130357,7 +131568,7 @@ var ts; // falls through case 112 /* SyntaxKind.TypeOfKeyword */: case 94 /* SyntaxKind.ExtendsKeyword */: - case 140 /* SyntaxKind.KeyOfKeyword */: + case 141 /* SyntaxKind.KeyOfKeyword */: case 24 /* SyntaxKind.DotToken */: case 51 /* SyntaxKind.BarToken */: case 57 /* SyntaxKind.QuestionToken */: @@ -130378,7 +131589,7 @@ var ts; /** * Returns true if the cursor at position in sourceFile is within a comment. * - * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position)` * @param predicate Additional predicate to test on the comment range. */ function isInComment(sourceFile, position, tokenAtPosition) { @@ -130409,7 +131620,7 @@ var ts; result.push("public" /* ScriptElementKindModifier.publicMemberModifier */); if (flags & 32 /* ModifierFlags.Static */ || ts.isClassStaticBlockDeclaration(node)) result.push("static" /* ScriptElementKindModifier.staticModifier */); - if (flags & 128 /* ModifierFlags.Abstract */) + if (flags & 256 /* ModifierFlags.Abstract */) result.push("abstract" /* ScriptElementKindModifier.abstractModifier */); if (flags & 1 /* ModifierFlags.Export */) result.push("export" /* ScriptElementKindModifier.exportedModifier */); @@ -130417,16 +131628,16 @@ var ts; result.push("deprecated" /* ScriptElementKindModifier.deprecatedModifier */); if (node.flags & 16777216 /* NodeFlags.Ambient */) result.push("declare" /* ScriptElementKindModifier.ambientModifier */); - if (node.kind === 271 /* SyntaxKind.ExportAssignment */) + if (node.kind === 274 /* SyntaxKind.ExportAssignment */) result.push("export" /* ScriptElementKindModifier.exportedModifier */); return result.length > 0 ? result.join(",") : "" /* ScriptElementKindModifier.none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 178 /* SyntaxKind.TypeReference */ || node.kind === 208 /* SyntaxKind.CallExpression */) { + if (node.kind === 180 /* SyntaxKind.TypeReference */ || node.kind === 210 /* SyntaxKind.CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 257 /* SyntaxKind.ClassDeclaration */ || node.kind === 258 /* SyntaxKind.InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 260 /* SyntaxKind.ClassDeclaration */ || node.kind === 261 /* SyntaxKind.InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -130471,18 +131682,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 204 /* SyntaxKind.ArrayLiteralExpression */ || - node.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { + if (node.kind === 206 /* SyntaxKind.ArrayLiteralExpression */ || + node.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 221 /* SyntaxKind.BinaryExpression */ && + if (node.parent.kind === 223 /* SyntaxKind.BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 244 /* SyntaxKind.ForOfStatement */ && + if (node.parent.kind === 247 /* SyntaxKind.ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -130490,7 +131701,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 296 /* SyntaxKind.PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 299 /* SyntaxKind.PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -130552,32 +131763,32 @@ var ts; } ts.createTextChange = createTextChange; ts.typeKeywords = [ - 130 /* SyntaxKind.AnyKeyword */, - 128 /* SyntaxKind.AssertsKeyword */, - 158 /* SyntaxKind.BigIntKeyword */, - 133 /* SyntaxKind.BooleanKeyword */, + 131 /* SyntaxKind.AnyKeyword */, + 129 /* SyntaxKind.AssertsKeyword */, + 160 /* SyntaxKind.BigIntKeyword */, + 134 /* SyntaxKind.BooleanKeyword */, 95 /* SyntaxKind.FalseKeyword */, - 137 /* SyntaxKind.InferKeyword */, - 140 /* SyntaxKind.KeyOfKeyword */, - 143 /* SyntaxKind.NeverKeyword */, + 138 /* SyntaxKind.InferKeyword */, + 141 /* SyntaxKind.KeyOfKeyword */, + 144 /* SyntaxKind.NeverKeyword */, 104 /* SyntaxKind.NullKeyword */, - 147 /* SyntaxKind.NumberKeyword */, - 148 /* SyntaxKind.ObjectKeyword */, - 145 /* SyntaxKind.ReadonlyKeyword */, - 150 /* SyntaxKind.StringKeyword */, - 151 /* SyntaxKind.SymbolKeyword */, + 148 /* SyntaxKind.NumberKeyword */, + 149 /* SyntaxKind.ObjectKeyword */, + 146 /* SyntaxKind.ReadonlyKeyword */, + 152 /* SyntaxKind.StringKeyword */, + 153 /* SyntaxKind.SymbolKeyword */, 110 /* SyntaxKind.TrueKeyword */, 114 /* SyntaxKind.VoidKeyword */, - 153 /* SyntaxKind.UndefinedKeyword */, - 154 /* SyntaxKind.UniqueKeyword */, - 155 /* SyntaxKind.UnknownKeyword */, + 155 /* SyntaxKind.UndefinedKeyword */, + 156 /* SyntaxKind.UniqueKeyword */, + 157 /* SyntaxKind.UnknownKeyword */, ]; function isTypeKeyword(kind) { return ts.contains(ts.typeKeywords, kind); } ts.isTypeKeyword = isTypeKeyword; function isTypeKeywordToken(node) { - return node.kind === 152 /* SyntaxKind.TypeKeyword */; + return node.kind === 154 /* SyntaxKind.TypeKeyword */; } ts.isTypeKeywordToken = isTypeKeywordToken; function isTypeKeywordTokenOrIdentifier(node) { @@ -130614,7 +131825,7 @@ var ts; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { - return name.kind === 162 /* SyntaxKind.ComputedPropertyName */ + return name.kind === 164 /* SyntaxKind.ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name); @@ -130764,7 +131975,7 @@ var ts; ts.findModifier = findModifier; function insertImports(changes, sourceFile, imports, blankLineBetween) { var decl = ts.isArray(imports) ? imports[0] : imports; - var importKindPredicate = decl.kind === 237 /* SyntaxKind.VariableStatement */ ? ts.isRequireVariableStatement : ts.isAnyImportSyntax; + var importKindPredicate = decl.kind === 240 /* SyntaxKind.VariableStatement */ ? ts.isRequireVariableStatement : ts.isAnyImportSyntax; var existingImportStatements = ts.filter(sourceFile.statements, importKindPredicate); var sortedNewImports = ts.isArray(imports) ? ts.stableSort(imports, ts.OrganizeImports.compareImportsOrRequireStatements) : [imports]; if (!existingImportStatements.length) { @@ -131438,15 +132649,15 @@ var ts; function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: return checker.getContextualType(parent); - case 221 /* SyntaxKind.BinaryExpression */: { + case 223 /* SyntaxKind.BinaryExpression */: { var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node); } - case 289 /* SyntaxKind.CaseClause */: + case 292 /* SyntaxKind.CaseClause */: return parent.expression === node ? getSwitchedType(parent, checker) : undefined; default: return checker.getContextualType(node); @@ -131476,8 +132687,8 @@ var ts; switch (node.kind) { case 10 /* SyntaxKind.StringLiteral */: case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: - case 223 /* SyntaxKind.TemplateExpression */: - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 225 /* SyntaxKind.TemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: return true; default: return false; @@ -131511,38 +132722,38 @@ var ts; } ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible; function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) { - return kind === 174 /* SyntaxKind.CallSignature */ - || kind === 175 /* SyntaxKind.ConstructSignature */ - || kind === 176 /* SyntaxKind.IndexSignature */ - || kind === 166 /* SyntaxKind.PropertySignature */ - || kind === 168 /* SyntaxKind.MethodSignature */; + return kind === 176 /* SyntaxKind.CallSignature */ + || kind === 177 /* SyntaxKind.ConstructSignature */ + || kind === 178 /* SyntaxKind.IndexSignature */ + || kind === 168 /* SyntaxKind.PropertySignature */ + || kind === 170 /* SyntaxKind.MethodSignature */; } function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) { - return kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */; + return kind === 259 /* SyntaxKind.FunctionDeclaration */ + || kind === 173 /* SyntaxKind.Constructor */ + || kind === 171 /* SyntaxKind.MethodDeclaration */ + || kind === 174 /* SyntaxKind.GetAccessor */ + || kind === 175 /* SyntaxKind.SetAccessor */; } function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) { - return kind === 261 /* SyntaxKind.ModuleDeclaration */; + return kind === 264 /* SyntaxKind.ModuleDeclaration */; } function syntaxRequiresTrailingSemicolonOrASI(kind) { - return kind === 237 /* SyntaxKind.VariableStatement */ - || kind === 238 /* SyntaxKind.ExpressionStatement */ - || kind === 240 /* SyntaxKind.DoStatement */ - || kind === 245 /* SyntaxKind.ContinueStatement */ - || kind === 246 /* SyntaxKind.BreakStatement */ - || kind === 247 /* SyntaxKind.ReturnStatement */ - || kind === 251 /* SyntaxKind.ThrowStatement */ - || kind === 253 /* SyntaxKind.DebuggerStatement */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */ - || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ - || kind === 266 /* SyntaxKind.ImportDeclaration */ - || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ - || kind === 272 /* SyntaxKind.ExportDeclaration */ - || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ - || kind === 271 /* SyntaxKind.ExportAssignment */; + return kind === 240 /* SyntaxKind.VariableStatement */ + || kind === 241 /* SyntaxKind.ExpressionStatement */ + || kind === 243 /* SyntaxKind.DoStatement */ + || kind === 248 /* SyntaxKind.ContinueStatement */ + || kind === 249 /* SyntaxKind.BreakStatement */ + || kind === 250 /* SyntaxKind.ReturnStatement */ + || kind === 254 /* SyntaxKind.ThrowStatement */ + || kind === 256 /* SyntaxKind.DebuggerStatement */ + || kind === 169 /* SyntaxKind.PropertyDeclaration */ + || kind === 262 /* SyntaxKind.TypeAliasDeclaration */ + || kind === 269 /* SyntaxKind.ImportDeclaration */ + || kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ + || kind === 275 /* SyntaxKind.ExportDeclaration */ + || kind === 267 /* SyntaxKind.NamespaceExportDeclaration */ + || kind === 274 /* SyntaxKind.ExportAssignment */; } ts.syntaxRequiresTrailingSemicolonOrASI = syntaxRequiresTrailingSemicolonOrASI; ts.syntaxMayBeASICandidate = ts.or(syntaxRequiresTrailingCommaOrSemicolonOrASI, syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, syntaxRequiresTrailingModuleBlockOrSemicolonOrASI, syntaxRequiresTrailingSemicolonOrASI); @@ -131572,7 +132783,7 @@ var ts; return false; } // See comment in parser’s `parseDoStatement` - if (node.kind === 240 /* SyntaxKind.DoStatement */) { + if (node.kind === 243 /* SyntaxKind.DoStatement */) { return true; } var topNode = ts.findAncestor(node, function (ancestor) { return !ancestor.parent; }); @@ -132061,6 +133272,10 @@ var ts; return jsx === 2 /* JsxEmit.React */ || jsx === 3 /* JsxEmit.ReactNative */; } ts.jsxModeNeedsExplicitImport = jsxModeNeedsExplicitImport; + function isSourceFileFromLibrary(program, node) { + return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); + } + ts.isSourceFileFromLibrary = isSourceFileFromLibrary; // #endregion })(ts || (ts = {})); /*@internal*/ @@ -132176,14 +133391,16 @@ var ts; search: function (importingFile, preferCapitalized, matches, action) { if (importingFile !== usableByFileName) return; - exportInfo.forEach(function (info, key) { + return ts.forEachEntry(exportInfo, function (info, key) { var _a = parseKey(key), symbolName = _a.symbolName, ambientModuleName = _a.ambientModuleName; var name = preferCapitalized && info[0].capitalizedSymbolName || symbolName; if (matches(name, info[0].targetFlags)) { var rehydrated = info.map(rehydrateCachedInfo); var filtered = rehydrated.filter(function (r, i) { return isNotShadowedByDeeperNodeModulesPackage(r, info[i].packageName); }); if (filtered.length) { - action(filtered, name, !!ambientModuleName, key); + var res = action(filtered, name, !!ambientModuleName, key); + if (res !== undefined) + return res; } } }); @@ -132571,11 +133788,11 @@ var ts; angleBracketStack--; } break; - case 130 /* SyntaxKind.AnyKeyword */: - case 150 /* SyntaxKind.StringKeyword */: - case 147 /* SyntaxKind.NumberKeyword */: - case 133 /* SyntaxKind.BooleanKeyword */: - case 151 /* SyntaxKind.SymbolKeyword */: + case 131 /* SyntaxKind.AnyKeyword */: + case 152 /* SyntaxKind.StringKeyword */: + case 148 /* SyntaxKind.NumberKeyword */: + case 134 /* SyntaxKind.BooleanKeyword */: + case 153 /* SyntaxKind.SymbolKeyword */: if (angleBracketStack > 0 && !syntacticClassifierAbsent) { // If it looks like we're could be in something generic, don't classify this // as a keyword. We may just get overwritten by the syntactic classifier, @@ -132764,10 +133981,11 @@ var ts; return true; } switch (keyword2) { - case 136 /* SyntaxKind.GetKeyword */: - case 149 /* SyntaxKind.SetKeyword */: - case 134 /* SyntaxKind.ConstructorKeyword */: + case 137 /* SyntaxKind.GetKeyword */: + case 151 /* SyntaxKind.SetKeyword */: + case 135 /* SyntaxKind.ConstructorKeyword */: case 124 /* SyntaxKind.StaticKeyword */: + case 127 /* SyntaxKind.AccessorKeyword */: return true; // Allow things like "public get", "public constructor" and "public static". default: return false; // Any other keyword following "public" is actually an identifier, not a real keyword. @@ -132814,7 +134032,8 @@ var ts; case 33 /* SyntaxKind.GreaterThanEqualsToken */: case 102 /* SyntaxKind.InstanceOfKeyword */: case 101 /* SyntaxKind.InKeyword */: - case 127 /* SyntaxKind.AsKeyword */: + case 128 /* SyntaxKind.AsKeyword */: + case 150 /* SyntaxKind.SatisfiesKeyword */: case 34 /* SyntaxKind.EqualsEqualsToken */: case 35 /* SyntaxKind.ExclamationEqualsToken */: case 36 /* SyntaxKind.EqualsEqualsEqualsToken */: @@ -132910,13 +134129,13 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 261 /* SyntaxKind.ModuleDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } } @@ -133138,46 +134357,46 @@ var ts; pos = tag.tagName.end; var commentStart = tag.tagName.end; switch (tag.kind) { - case 340 /* SyntaxKind.JSDocParameterTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: var param = tag; processJSDocParameterTag(param); commentStart = param.isNameFirst && ((_a = param.typeExpression) === null || _a === void 0 ? void 0 : _a.end) || param.name.end; break; - case 347 /* SyntaxKind.JSDocPropertyTag */: + case 350 /* SyntaxKind.JSDocPropertyTag */: var prop = tag; commentStart = prop.isNameFirst && ((_b = prop.typeExpression) === null || _b === void 0 ? void 0 : _b.end) || prop.name.end; break; - case 344 /* SyntaxKind.JSDocTemplateTag */: + case 347 /* SyntaxKind.JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; commentStart = tag.typeParameters.end; break; - case 345 /* SyntaxKind.JSDocTypedefTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: var type = tag; - commentStart = ((_c = type.typeExpression) === null || _c === void 0 ? void 0 : _c.kind) === 309 /* SyntaxKind.JSDocTypeExpression */ && ((_d = type.fullName) === null || _d === void 0 ? void 0 : _d.end) || ((_e = type.typeExpression) === null || _e === void 0 ? void 0 : _e.end) || commentStart; + commentStart = ((_c = type.typeExpression) === null || _c === void 0 ? void 0 : _c.kind) === 312 /* SyntaxKind.JSDocTypeExpression */ && ((_d = type.fullName) === null || _d === void 0 ? void 0 : _d.end) || ((_e = type.typeExpression) === null || _e === void 0 ? void 0 : _e.end) || commentStart; break; - case 338 /* SyntaxKind.JSDocCallbackTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: commentStart = tag.typeExpression.end; break; - case 343 /* SyntaxKind.JSDocTypeTag */: + case 346 /* SyntaxKind.JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; commentStart = tag.typeExpression.end; break; - case 342 /* SyntaxKind.JSDocThisTag */: - case 339 /* SyntaxKind.JSDocEnumTag */: + case 345 /* SyntaxKind.JSDocThisTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: commentStart = tag.typeExpression.end; break; - case 341 /* SyntaxKind.JSDocReturnTag */: + case 344 /* SyntaxKind.JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; commentStart = ((_f = tag.typeExpression) === null || _f === void 0 ? void 0 : _f.end) || commentStart; break; - case 346 /* SyntaxKind.JSDocSeeTag */: + case 349 /* SyntaxKind.JSDocSeeTag */: commentStart = ((_g = tag.name) === null || _g === void 0 ? void 0 : _g.end) || commentStart; break; - case 328 /* SyntaxKind.JSDocAugmentsTag */: - case 329 /* SyntaxKind.JSDocImplementsTag */: + case 331 /* SyntaxKind.JSDocAugmentsTag */: + case 332 /* SyntaxKind.JSDocImplementsTag */: commentStart = tag.class.end; break; } @@ -133224,7 +134443,7 @@ var ts; // defined in `ts.commentPragmas` would be excessive, but we can avoid // some obvious false positives (e.g. in XML-like doc comments) by // checking the element name. - // eslint-disable-next-line no-in-operator + // eslint-disable-next-line local/no-in-operator if (!match[3] || !(match[3] in ts.commentPragmas)) { return false; } @@ -133334,22 +134553,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 280 /* SyntaxKind.JsxOpeningElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* ClassificationType.jsxOpenTagName */; } break; - case 281 /* SyntaxKind.JsxClosingElement */: + case 284 /* SyntaxKind.JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* ClassificationType.jsxCloseTagName */; } break; - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* ClassificationType.jsxSelfClosingTagName */; } break; - case 285 /* SyntaxKind.JsxAttribute */: + case 288 /* SyntaxKind.JsxAttribute */: if (token.parent.name === token) { return 22 /* ClassificationType.jsxAttribute */; } @@ -133378,17 +134597,17 @@ var ts; var parent = token.parent; if (tokenKind === 63 /* SyntaxKind.EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (parent.kind === 254 /* SyntaxKind.VariableDeclaration */ || - parent.kind === 167 /* SyntaxKind.PropertyDeclaration */ || - parent.kind === 164 /* SyntaxKind.Parameter */ || - parent.kind === 285 /* SyntaxKind.JsxAttribute */) { + if (parent.kind === 257 /* SyntaxKind.VariableDeclaration */ || + parent.kind === 169 /* SyntaxKind.PropertyDeclaration */ || + parent.kind === 166 /* SyntaxKind.Parameter */ || + parent.kind === 288 /* SyntaxKind.JsxAttribute */) { return 5 /* ClassificationType.operator */; } } - if (parent.kind === 221 /* SyntaxKind.BinaryExpression */ || - parent.kind === 219 /* SyntaxKind.PrefixUnaryExpression */ || - parent.kind === 220 /* SyntaxKind.PostfixUnaryExpression */ || - parent.kind === 222 /* SyntaxKind.ConditionalExpression */) { + if (parent.kind === 223 /* SyntaxKind.BinaryExpression */ || + parent.kind === 221 /* SyntaxKind.PrefixUnaryExpression */ || + parent.kind === 222 /* SyntaxKind.PostfixUnaryExpression */ || + parent.kind === 224 /* SyntaxKind.ConditionalExpression */) { return 5 /* ClassificationType.operator */; } } @@ -133401,7 +134620,7 @@ var ts; return 25 /* ClassificationType.bigintLiteral */; } else if (tokenKind === 10 /* SyntaxKind.StringLiteral */) { - return token && token.parent.kind === 285 /* SyntaxKind.JsxAttribute */ ? 24 /* ClassificationType.jsxAttributeStringLiteralValue */ : 6 /* ClassificationType.stringLiteral */; + return token && token.parent.kind === 288 /* SyntaxKind.JsxAttribute */ ? 24 /* ClassificationType.jsxAttributeStringLiteralValue */ : 6 /* ClassificationType.stringLiteral */; } else if (tokenKind === 13 /* SyntaxKind.RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -133417,32 +134636,32 @@ var ts; else if (tokenKind === 79 /* SyntaxKind.Identifier */) { if (token) { switch (token.parent.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: if (token.parent.name === token) { return 11 /* ClassificationType.className */; } return; - case 163 /* SyntaxKind.TypeParameter */: + case 165 /* SyntaxKind.TypeParameter */: if (token.parent.name === token) { return 15 /* ClassificationType.typeParameterName */; } return; - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* ClassificationType.interfaceName */; } return; - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: if (token.parent.name === token) { return 12 /* ClassificationType.enumName */; } return; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: if (token.parent.name === token) { return 14 /* ClassificationType.moduleName */; } return; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* ClassificationType.keyword */ : 17 /* ClassificationType.parameterName */; } @@ -133547,13 +134766,13 @@ var ts; var inJSXElement = false; function visit(node) { switch (node.kind) { - case 261 /* SyntaxKind.ModuleDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth()) || node.getFullWidth() === 0) { @@ -133593,7 +134812,7 @@ var ts; if (modifiers & 32 /* ModifierFlags.Static */) { modifierSet |= 1 << 1 /* TokenModifier.static */; } - if (modifiers & 256 /* ModifierFlags.Async */) { + if (modifiers & 512 /* ModifierFlags.Async */) { modifierSet |= 1 << 2 /* TokenModifier.async */; } if (typeIdx !== 0 /* TokenType.class */ && typeIdx !== 2 /* TokenType.interface */) { @@ -133699,25 +134918,25 @@ var ts; return (ts.isQualifiedName(node.parent) && node.parent.right === node) || (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node); } var tokenFromDeclarationMapping = new ts.Map([ - [254 /* SyntaxKind.VariableDeclaration */, 7 /* TokenType.variable */], - [164 /* SyntaxKind.Parameter */, 6 /* TokenType.parameter */], - [167 /* SyntaxKind.PropertyDeclaration */, 9 /* TokenType.property */], - [261 /* SyntaxKind.ModuleDeclaration */, 3 /* TokenType.namespace */], - [260 /* SyntaxKind.EnumDeclaration */, 1 /* TokenType.enum */], - [299 /* SyntaxKind.EnumMember */, 8 /* TokenType.enumMember */], - [257 /* SyntaxKind.ClassDeclaration */, 0 /* TokenType.class */], - [169 /* SyntaxKind.MethodDeclaration */, 11 /* TokenType.member */], - [256 /* SyntaxKind.FunctionDeclaration */, 10 /* TokenType.function */], - [213 /* SyntaxKind.FunctionExpression */, 10 /* TokenType.function */], - [168 /* SyntaxKind.MethodSignature */, 11 /* TokenType.member */], - [172 /* SyntaxKind.GetAccessor */, 9 /* TokenType.property */], - [173 /* SyntaxKind.SetAccessor */, 9 /* TokenType.property */], - [166 /* SyntaxKind.PropertySignature */, 9 /* TokenType.property */], - [258 /* SyntaxKind.InterfaceDeclaration */, 2 /* TokenType.interface */], - [259 /* SyntaxKind.TypeAliasDeclaration */, 5 /* TokenType.type */], - [163 /* SyntaxKind.TypeParameter */, 4 /* TokenType.typeParameter */], - [296 /* SyntaxKind.PropertyAssignment */, 9 /* TokenType.property */], - [297 /* SyntaxKind.ShorthandPropertyAssignment */, 9 /* TokenType.property */] + [257 /* SyntaxKind.VariableDeclaration */, 7 /* TokenType.variable */], + [166 /* SyntaxKind.Parameter */, 6 /* TokenType.parameter */], + [169 /* SyntaxKind.PropertyDeclaration */, 9 /* TokenType.property */], + [264 /* SyntaxKind.ModuleDeclaration */, 3 /* TokenType.namespace */], + [263 /* SyntaxKind.EnumDeclaration */, 1 /* TokenType.enum */], + [302 /* SyntaxKind.EnumMember */, 8 /* TokenType.enumMember */], + [260 /* SyntaxKind.ClassDeclaration */, 0 /* TokenType.class */], + [171 /* SyntaxKind.MethodDeclaration */, 11 /* TokenType.member */], + [259 /* SyntaxKind.FunctionDeclaration */, 10 /* TokenType.function */], + [215 /* SyntaxKind.FunctionExpression */, 10 /* TokenType.function */], + [170 /* SyntaxKind.MethodSignature */, 11 /* TokenType.member */], + [174 /* SyntaxKind.GetAccessor */, 9 /* TokenType.property */], + [175 /* SyntaxKind.SetAccessor */, 9 /* TokenType.property */], + [168 /* SyntaxKind.PropertySignature */, 9 /* TokenType.property */], + [261 /* SyntaxKind.InterfaceDeclaration */, 2 /* TokenType.interface */], + [262 /* SyntaxKind.TypeAliasDeclaration */, 5 /* TokenType.type */], + [165 /* SyntaxKind.TypeParameter */, 4 /* TokenType.typeParameter */], + [299 /* SyntaxKind.PropertyAssignment */, 9 /* TokenType.property */], + [300 /* SyntaxKind.ShorthandPropertyAssignment */, 9 /* TokenType.property */] ]); })(v2020 = classifier.v2020 || (classifier.v2020 = {})); })(classifier = ts.classifier || (ts.classifier = {})); @@ -133851,18 +135070,18 @@ var ts; function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, preferences) { var parent = walkUpParentheses(node.parent); switch (parent.kind) { - case 196 /* SyntaxKind.LiteralType */: { + case 198 /* SyntaxKind.LiteralType */: { var grandParent_1 = walkUpParentheses(parent.parent); switch (grandParent_1.kind) { - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: - case 178 /* SyntaxKind.TypeReference */: { + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: + case 180 /* SyntaxKind.TypeReference */: { var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === grandParent_1; }); if (typeArgument) { return { kind: 2 /* StringLiteralCompletionKind.Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), isNewIdentifier: false }; } return undefined; } - case 194 /* SyntaxKind.IndexedAccessType */: + case 196 /* SyntaxKind.IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { // foo: string; @@ -133874,9 +135093,9 @@ var ts; return undefined; } return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType)); - case 200 /* SyntaxKind.ImportType */: + case 202 /* SyntaxKind.ImportType */: return { kind: 0 /* StringLiteralCompletionKind.Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; - case 187 /* SyntaxKind.UnionType */: { + case 189 /* SyntaxKind.UnionType */: { if (!ts.isTypeReferenceNode(grandParent_1.parent)) { return undefined; } @@ -133888,7 +135107,7 @@ var ts; return undefined; } } - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { @@ -133905,7 +135124,7 @@ var ts; return stringLiteralCompletionsForObjectLiteral(typeChecker, parent.parent); } return fromContextualType(); - case 207 /* SyntaxKind.ElementAccessExpression */: { + case 209 /* SyntaxKind.ElementAccessExpression */: { var _b = parent, expression = _b.expression, argumentExpression = _b.argumentExpression; if (node === ts.skipParentheses(argumentExpression)) { // Get all names of properties on the expression @@ -133918,20 +135137,20 @@ var ts; } return undefined; } - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: - case 285 /* SyntaxKind.JsxAttribute */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: + case 288 /* SyntaxKind.JsxAttribute */: if (!isRequireCallArgument(node) && !ts.isImportCall(parent)) { - var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(parent.kind === 285 /* SyntaxKind.JsxAttribute */ ? parent.parent : node, position, sourceFile); + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(parent.kind === 288 /* SyntaxKind.JsxAttribute */ ? parent.parent : node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); // f("/*completion position*/") - return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) : fromContextualType(); + return argumentInfo && getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || fromContextualType(); } // falls through (is `require("")` or `require(""` or `import("")`) - case 266 /* SyntaxKind.ImportDeclaration */: - case 272 /* SyntaxKind.ExportDeclaration */: - case 277 /* SyntaxKind.ExternalModuleReference */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: + case 280 /* SyntaxKind.ExternalModuleReference */: // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; // var y = import("/*completion position*/"); @@ -133950,9 +135169,9 @@ var ts; } function walkUpParentheses(node) { switch (node.kind) { - case 191 /* SyntaxKind.ParenthesizedType */: + case 193 /* SyntaxKind.ParenthesizedType */: return ts.walkUpParenthesizedTypes(node); - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return ts.walkUpParenthesizedExpressions(node); default: return node; @@ -133982,7 +135201,7 @@ var ts; isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* TypeFlags.String */); return getStringLiteralTypes(type, uniques); }); - return { kind: 2 /* StringLiteralCompletionKind.Types */, types: types, isNewIdentifier: isNewIdentifier }; + return ts.length(types) ? { kind: 2 /* StringLiteralCompletionKind.Types */, types: types, isNewIdentifier: isNewIdentifier } : undefined; } function stringLiteralCompletionsFromProperties(type) { return type && { @@ -134500,7 +135719,7 @@ var ts; if (!dependencies) continue; for (var dep in dependencies) { - if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { + if (ts.hasProperty(dependencies, dep) && !ts.startsWith(dep, "@types/")) { result.push(dep); } } @@ -134875,7 +136094,7 @@ var ts; } function keywordFiltersFromSyntaxKind(keywordCompletion) { switch (keywordCompletion) { - case 152 /* SyntaxKind.TypeKeyword */: return 8 /* KeywordCompletionFilters.TypeKeyword */; + case 154 /* SyntaxKind.TypeKeyword */: return 8 /* KeywordCompletionFilters.TypeKeyword */; default: ts.Debug.fail("Unknown mapping from SyntaxKind to KeywordCompletionFilters"); } } @@ -134884,7 +136103,7 @@ var ts; return (location === null || location === void 0 ? void 0 : location.kind) === 79 /* SyntaxKind.Identifier */ ? ts.createTextSpanFromNode(location) : undefined; } function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position) { - var symbols = completionData.symbols, contextToken = completionData.contextToken, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, isRightOfOpenTag = completionData.isRightOfOpenTag, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap, hasUnresolvedAutoImports = completionData.hasUnresolvedAutoImports; + var symbols = completionData.symbols, contextToken = completionData.contextToken, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, isRightOfOpenTag = completionData.isRightOfOpenTag, importStatementCompletion = completionData.importStatementCompletion, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap, hasUnresolvedAutoImports = completionData.hasUnresolvedAutoImports; // Verify if the file is JSX language variant if (ts.getLanguageVariant(sourceFile.scriptKind) === 1 /* LanguageVariant.JSX */) { var completionInfo = getJsxClosingTagCompletion(location, sourceFile); @@ -134898,7 +136117,7 @@ var ts; return undefined; } var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); if (keywordFilters !== 0 /* KeywordCompletionFilters.None */) { for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; @@ -134951,12 +136170,12 @@ var ts; // We wanna walk up the tree till we find a JSX closing element var jsxClosingElement = ts.findAncestor(location, function (node) { switch (node.kind) { - case 281 /* SyntaxKind.JsxClosingElement */: + case 284 /* SyntaxKind.JsxClosingElement */: return true; case 43 /* SyntaxKind.SlashToken */: case 31 /* SyntaxKind.GreaterThanToken */: case 79 /* SyntaxKind.Identifier */: - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return false; default: return "quit"; @@ -135016,7 +136235,7 @@ var ts; function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* ScriptElementKind.string */, kindModifiers: "" /* ScriptElementKindModifier.none */, sortText: Completions.SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences, completionKind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag) { + function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importStatementCompletion, useSemicolons, options, preferences, completionKind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag) { var _a, _b; var insertText; var replacementSpan = ts.getReplacementSpanForContextToken(replacementToken); @@ -135072,8 +136291,8 @@ var ts; } if (originIsResolvedExport(origin)) { sourceDisplay = [ts.textPart(origin.moduleSpecifier)]; - if (importCompletionNode) { - (_a = getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, contextToken, origin, useSemicolons, options, preferences), insertText = _a.insertText, replacementSpan = _a.replacementSpan); + if (importStatementCompletion) { + (_a = getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences), insertText = _a.insertText, replacementSpan = _a.replacementSpan); isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; } } @@ -135083,7 +136302,7 @@ var ts; if (preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === 3 /* CompletionKind.MemberLike */ && - isClassLikeMemberCompletion(symbol, location)) { + isClassLikeMemberCompletion(symbol, location, sourceFile)) { var importAdder = void 0; (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken, formatContext), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder, replacementSpan = _b.replacementSpan); sortText = Completions.SortText.ClassMemberSnippets; // sortText has to be lower priority than the sortText for keywords. See #47852. @@ -135128,7 +136347,7 @@ var ts; } if (originIsExport(origin) || originIsResolvedExport(origin)) { data = originToCompletionEntryData(origin); - hasAction = !importCompletionNode; + hasAction = !importStatementCompletion; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but @@ -135151,11 +136370,11 @@ var ts; labelDetails: labelDetails, isSnippet: isSnippet, isPackageJsonImport: originIsPackageJsonImport(origin) || undefined, - isImportStatementCompletion: !!importCompletionNode || undefined, + isImportStatementCompletion: !!importStatementCompletion || undefined, data: data, }; } - function isClassLikeMemberCompletion(symbol, location) { + function isClassLikeMemberCompletion(symbol, location, sourceFile) { // TODO: support JS files. if (ts.isInJSFile(location)) { return false; @@ -135189,6 +136408,7 @@ var ts; location.parent.parent && ts.isClassElement(location.parent) && location === location.parent.name && + location.parent.getLastToken(sourceFile) === location.parent.name && ts.isClassLike(location.parent.parent)) || (location.parent && ts.isSyntaxList(location) && @@ -135230,7 +136450,7 @@ var ts; // Whether the suggested member should be abstract. // e.g. in `abstract class C { abstract | }`, we should offer abstract method signatures at position `|`. var _a = getPresentModifiers(contextToken), presentModifiers = _a.modifiers, modifiersSpan = _a.span; - var isAbstract = !!(presentModifiers & 128 /* ModifierFlags.Abstract */); + var isAbstract = !!(presentModifiers & 256 /* ModifierFlags.Abstract */); var completionNodes = []; ts.codefix.addNewNodeForMemberSymbol(symbol, classLikeDeclaration, sourceFile, { program: program, host: host }, preferences, importAdder, // `addNewNodeForMemberSymbol` calls this callback function for each new member node @@ -135243,7 +136463,7 @@ var ts; function (node) { var requiredModifiers = 0 /* ModifierFlags.None */; if (isAbstract) { - requiredModifiers |= 128 /* ModifierFlags.Abstract */; + requiredModifiers |= 256 /* ModifierFlags.Abstract */; } if (ts.isClassElement(node) && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node) === 1 /* MemberOverrideStatus.NeedsOverride */) { @@ -135304,7 +136524,7 @@ var ts; span = ts.createTextSpanFromNode(contextToken); } if (ts.isPropertyDeclaration(contextToken.parent)) { - modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers) & 125951 /* ModifierFlags.Modifier */; + modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers) & 126975 /* ModifierFlags.Modifier */; span = ts.createTextSpanFromNode(contextToken.parent); } return { modifiers: modifiers, span: span }; @@ -135353,7 +136573,6 @@ var ts; var labelDetails = { detail: signaturePrinter.printNode(4 /* EmitHint.Unspecified */, methodSignature, sourceFile) }; return { isSnippet: isSnippet, insertText: insertText, labelDetails: labelDetails }; } - ; function createObjectLiteralMethod(symbol, enclosingDeclaration, sourceFile, program, host, preferences) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { @@ -135366,10 +136585,10 @@ var ts; var quotePreference = ts.getQuotePreference(sourceFile, preferences); var builderFlags = 33554432 /* NodeBuilderFlags.OmitThisParameter */ | (quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : 0 /* NodeBuilderFlags.None */); switch (declaration.kind) { - case 166 /* SyntaxKind.PropertySignature */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 169 /* SyntaxKind.MethodDeclaration */: { + case 168 /* SyntaxKind.PropertySignature */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: { var effectiveType = type.flags & 1048576 /* TypeFlags.Union */ && type.types.length < 10 ? checker.getUnionType(type.types, 2 /* UnionReduction.Subtype */) : type; @@ -135403,7 +136622,8 @@ var ts; } var parameters = typeNode.parameters.map(function (typedParam) { return ts.factory.createParameterDeclaration( - /*modifiers*/ undefined, typedParam.dotDotDotToken, typedParam.name, typedParam.questionToken, + /*modifiers*/ undefined, typedParam.dotDotDotToken, typedParam.name, + /*questionToken*/ undefined, /*type*/ undefined, typedParam.initializer); }); return ts.factory.createMethodDeclaration( @@ -135523,20 +136743,17 @@ var ts; }; return unresolvedOrigin; } - function getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, contextToken, origin, useSemicolons, options, preferences) { - var _a, _b, _c; - var sourceFile = importCompletionNode.getSourceFile(); - var replacementSpan = ts.createTextSpanFromNode(ts.findAncestor(importCompletionNode, ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration)) || importCompletionNode, sourceFile); + function getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences) { + var replacementSpan = importStatementCompletion.replacementSpan; var quotedModuleSpecifier = ts.quote(sourceFile, preferences, origin.moduleSpecifier); var exportKind = origin.isDefaultExport ? 1 /* ExportKind.Default */ : origin.exportName === "export=" /* InternalSymbolName.ExportEquals */ ? 2 /* ExportKind.ExportEquals */ : 0 /* ExportKind.Named */; var tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : ""; var importKind = ts.codefix.getImportKind(sourceFile, exportKind, options, /*forceImportKeyword*/ true); - var isTopLevelTypeOnly = ((_b = (_a = ts.tryCast(importCompletionNode, ts.isImportDeclaration)) === null || _a === void 0 ? void 0 : _a.importClause) === null || _b === void 0 ? void 0 : _b.isTypeOnly) || ((_c = ts.tryCast(importCompletionNode, ts.isImportEqualsDeclaration)) === null || _c === void 0 ? void 0 : _c.isTypeOnly); - var isImportSpecifierTypeOnly = couldBeTypeOnlyImportSpecifier(importCompletionNode, contextToken); - var topLevelTypeOnlyText = isTopLevelTypeOnly ? " ".concat(ts.tokenToString(152 /* SyntaxKind.TypeKeyword */), " ") : " "; - var importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? "".concat(ts.tokenToString(152 /* SyntaxKind.TypeKeyword */), " ") : ""; + var isImportSpecifierTypeOnly = importStatementCompletion.couldBeTypeOnlyImportSpecifier; + var topLevelTypeOnlyText = importStatementCompletion.isTopLevelTypeOnly ? " ".concat(ts.tokenToString(154 /* SyntaxKind.TypeKeyword */), " ") : " "; + var importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? "".concat(ts.tokenToString(154 /* SyntaxKind.TypeKeyword */), " ") : ""; var suffix = useSemicolons ? ";" : ""; switch (importKind) { case 3 /* ImportKind.CommonJS */: return { replacementSpan: replacementSpan, insertText: "import".concat(topLevelTypeOnlyText).concat(ts.escapeSnippetText(name)).concat(tabStop, " = require(").concat(quotedModuleSpecifier, ")").concat(suffix) }; @@ -135569,7 +136786,7 @@ var ts; return CompletionSource.TypeOnlyAlias; } } - function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, host, program, target, log, kind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag) { + function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, host, program, target, log, kind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag) { var _a; var start = ts.timestamp(); var variableDeclaration = getVariableDeclaration(location); @@ -135590,7 +136807,7 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var originalSortText = (_a = symbolToSortTextMap === null || symbolToSortTextMap === void 0 ? void 0 : symbolToSortTextMap[ts.getSymbolId(symbol)]) !== null && _a !== void 0 ? _a : Completions.SortText.LocationPriority; var sortText = (isDeprecated(symbol, typeChecker) ? Completions.SortText.Deprecated(originalSortText) : originalSortText); - var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences, kind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag); + var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importStatementCompletion, useSemicolons, compilerOptions, preferences, kind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag); if (!entry) { continue; } @@ -135750,7 +136967,7 @@ var ts; } case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, contextToken_2 = symbolCompletion.contextToken, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken_2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken_2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source, cancellationToken), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -135779,9 +136996,9 @@ var ts; return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source, sourceDisplay: source }; } Completions.createCompletionDetails = createCompletionDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source) { + function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source, cancellationToken) { if (data === null || data === void 0 ? void 0 : data.moduleSpecifier) { - if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken).replacementNode) { + if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken).replacementSpan) { // Import statement completion: 'import c|' return { codeActions: undefined, sourceDisplay: [ts.textPart(data.moduleSpecifier)] }; } @@ -135811,7 +137028,7 @@ var ts; var moduleSymbol = origin.moduleSymbol; var targetSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); var isJsxOpeningTagName = (contextToken === null || contextToken === void 0 ? void 0 : contextToken.kind) === 29 /* SyntaxKind.LessThanToken */ && ts.isJsxOpeningLikeElement(contextToken.parent); - var _a = ts.codefix.getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions), isJsxOpeningTagName), isJsxOpeningTagName, host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var _a = ts.codefix.getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions), isJsxOpeningTagName), isJsxOpeningTagName, host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences, cancellationToken), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; ts.Debug.assert(!(data === null || data === void 0 ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier); return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -135854,11 +137071,11 @@ var ts; return ts.getContextualTypeFromParent(previousToken, checker); case 63 /* SyntaxKind.EqualsToken */: switch (parent.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return checker.getContextualType(parent.initializer); // TODO: GH#18217 - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 285 /* SyntaxKind.JsxAttribute */: + case 288 /* SyntaxKind.JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; @@ -135889,7 +137106,7 @@ var ts; } function isModuleSymbol(symbol) { var _a; - return !!((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.kind === 305 /* SyntaxKind.SourceFile */; })); + return !!((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.kind === 308 /* SyntaxKind.SourceFile */; })); } function getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, detailsEntryId, host, formatContext, cancellationToken) { var typeChecker = program.getTypeChecker(); @@ -135946,7 +137163,7 @@ var ts; currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 347 /* SyntaxKind.JSDocPropertyTag */ || + (currentToken.parent.kind !== 350 /* SyntaxKind.JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(typeExpression); @@ -135982,34 +137199,34 @@ var ts; var isStartingCloseTag = false; var isJsxInitializer = false; var isJsxIdentifierExpected = false; - var importCompletionNode; + var importStatementCompletion; var location = ts.getTouchingPropertyName(sourceFile, position); var keywordFilters = 0 /* KeywordCompletionFilters.None */; var isNewIdentifierLocation = false; var flags = 0 /* CompletionInfoFlags.None */; if (contextToken) { - var importStatementCompletion = getImportStatementCompletionInfo(contextToken); - isNewIdentifierLocation = importStatementCompletion.isNewIdentifierLocation; - if (importStatementCompletion.keywordCompletion) { - if (importStatementCompletion.isKeywordOnlyCompletion) { + var importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken); + if (importStatementCompletionInfo.keywordCompletion) { + if (importStatementCompletionInfo.isKeywordOnlyCompletion) { return { kind: 4 /* CompletionDataKind.Keywords */, - keywordCompletions: [keywordToCompletionEntry(importStatementCompletion.keywordCompletion)], - isNewIdentifierLocation: isNewIdentifierLocation, + keywordCompletions: [keywordToCompletionEntry(importStatementCompletionInfo.keywordCompletion)], + isNewIdentifierLocation: importStatementCompletionInfo.isNewIdentifierLocation, }; } - keywordFilters = keywordFiltersFromSyntaxKind(importStatementCompletion.keywordCompletion); + keywordFilters = keywordFiltersFromSyntaxKind(importStatementCompletionInfo.keywordCompletion); } - if (importStatementCompletion.replacementNode && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + if (importStatementCompletionInfo.replacementSpan && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { // Import statement completions use `insertText`, and also require the `data` property of `CompletionEntryIdentifier` // added in TypeScript 4.3 to be sent back from the client during `getCompletionEntryDetails`. Since this feature // is not backward compatible with older clients, the language service defaults to disabling it, allowing newer clients // to opt in with the `includeCompletionsForImportStatements` user preference. - importCompletionNode = importStatementCompletion.replacementNode; flags |= 2 /* CompletionInfoFlags.IsImportStatementCompletion */; + importStatementCompletion = importStatementCompletionInfo; + isNewIdentifierLocation = importStatementCompletionInfo.isNewIdentifierLocation; } // Bail out if this is a known invalid completion location - if (!importCompletionNode && isCompletionListBlocker(contextToken)) { + if (!importStatementCompletionInfo.replacementSpan && isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, isNewIdentifierDefinitionLocation()) @@ -136020,7 +137237,7 @@ var ts; isRightOfDot = contextToken.kind === 24 /* SyntaxKind.DotToken */; isRightOfQuestionDot = contextToken.kind === 28 /* SyntaxKind.QuestionDotToken */; switch (parent.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; var leftmostAccessExpression = ts.getLeftmostAccessExpression(propertyAccessToConvert); @@ -136036,16 +137253,16 @@ var ts; return undefined; } break; - case 161 /* SyntaxKind.QualifiedName */: + case 163 /* SyntaxKind.QualifiedName */: node = parent.left; break; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: node = parent.name; break; - case 200 /* SyntaxKind.ImportType */: + case 202 /* SyntaxKind.ImportType */: node = parent; break; - case 231 /* SyntaxKind.MetaProperty */: + case 233 /* SyntaxKind.MetaProperty */: node = parent.getFirstToken(sourceFile); ts.Debug.assert(node.kind === 100 /* SyntaxKind.ImportKeyword */ || node.kind === 103 /* SyntaxKind.NewKeyword */); break; @@ -136055,11 +137272,11 @@ var ts; return undefined; } } - else if (!importCompletionNode && sourceFile.languageVariant === 1 /* LanguageVariant.JSX */) { + else if (!importStatementCompletion) { // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + if (parent && parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } @@ -136067,46 +137284,46 @@ var ts; if (currentToken.parent === location) { switch (currentToken.kind) { case 31 /* SyntaxKind.GreaterThanToken */: - if (currentToken.parent.kind === 278 /* SyntaxKind.JsxElement */ || currentToken.parent.kind === 280 /* SyntaxKind.JsxOpeningElement */) { + if (currentToken.parent.kind === 281 /* SyntaxKind.JsxElement */ || currentToken.parent.kind === 283 /* SyntaxKind.JsxOpeningElement */) { location = currentToken; } break; case 43 /* SyntaxKind.SlashToken */: - if (currentToken.parent.kind === 279 /* SyntaxKind.JsxSelfClosingElement */) { + if (currentToken.parent.kind === 282 /* SyntaxKind.JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 281 /* SyntaxKind.JsxClosingElement */: + case 284 /* SyntaxKind.JsxClosingElement */: if (contextToken.kind === 43 /* SyntaxKind.SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 278 /* SyntaxKind.JsxElement */: - case 280 /* SyntaxKind.JsxOpeningElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: + case 281 /* SyntaxKind.JsxElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: isJsxIdentifierExpected = true; if (contextToken.kind === 29 /* SyntaxKind.LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 288 /* SyntaxKind.JsxExpression */: - case 287 /* SyntaxKind.JsxSpreadAttribute */: + case 291 /* SyntaxKind.JsxExpression */: + case 290 /* SyntaxKind.JsxSpreadAttribute */: // For `
`, `parent` will be `{true}` and `previousToken` will be `}` if (previousToken.kind === 19 /* SyntaxKind.CloseBraceToken */ && currentToken.kind === 31 /* SyntaxKind.GreaterThanToken */) { isJsxIdentifierExpected = true; } break; - case 285 /* SyntaxKind.JsxAttribute */: + case 288 /* SyntaxKind.JsxAttribute */: // For `
`, `parent` will be JsxAttribute and `previousToken` will be its initializer if (parent.initializer === previousToken && previousToken.end < position) { @@ -136198,19 +137415,19 @@ var ts; isTypeOnlyLocation: isTypeOnlyLocation, isJsxIdentifierExpected: isJsxIdentifierExpected, isRightOfOpenTag: isRightOfOpenTag, - importCompletionNode: importCompletionNode, + importStatementCompletion: importStatementCompletion, hasUnresolvedAutoImports: hasUnresolvedAutoImports, flags: flags, }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 340 /* SyntaxKind.JSDocParameterTag */: - case 347 /* SyntaxKind.JSDocPropertyTag */: - case 341 /* SyntaxKind.JSDocReturnTag */: - case 343 /* SyntaxKind.JSDocTypeTag */: - case 345 /* SyntaxKind.JSDocTypedefTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: + case 350 /* SyntaxKind.JSDocPropertyTag */: + case 344 /* SyntaxKind.JSDocReturnTag */: + case 346 /* SyntaxKind.JSDocTypeTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: return true; - case 344 /* SyntaxKind.JSDocTemplateTag */: + case 347 /* SyntaxKind.JSDocTemplateTag */: return !!tag.constraint; default: return false; @@ -136219,7 +137436,7 @@ var ts; function tryGetTypeExpressionFromTag(tag) { if (isTagWithTypeExpression(tag)) { var typeExpression = ts.isJSDocTemplateTag(tag) ? tag.constraint : tag.typeExpression; - return typeExpression && typeExpression.kind === 309 /* SyntaxKind.JSDocTypeExpression */ ? typeExpression : undefined; + return typeExpression && typeExpression.kind === 312 /* SyntaxKind.JSDocTypeExpression */ ? typeExpression : undefined; } return undefined; } @@ -136262,7 +137479,7 @@ var ts; // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). if (!isTypeLocation && symbol.declarations && - symbol.declarations.some(function (d) { return d.kind !== 305 /* SyntaxKind.SourceFile */ && d.kind !== 261 /* SyntaxKind.ModuleDeclaration */ && d.kind !== 260 /* SyntaxKind.EnumDeclaration */; })) { + symbol.declarations.some(function (d) { return d.kind !== 308 /* SyntaxKind.SourceFile */ && d.kind !== 264 /* SyntaxKind.ModuleDeclaration */ && d.kind !== 263 /* SyntaxKind.EnumDeclaration */; })) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { @@ -136308,7 +137525,7 @@ var ts; if (isRightOfQuestionDot && ts.some(type.getCallSignatures())) { isNewIdentifierLocation = true; } - var propertyAccess = node.kind === 200 /* SyntaxKind.ImportType */ ? node : node.parent; + var propertyAccess = node.kind === 202 /* SyntaxKind.ImportType */ ? node : node.parent; if (inCheckedFile) { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; @@ -136452,7 +137669,7 @@ var ts; return 1 /* GlobalsSearch.Success */; } function tryGetImportCompletionSymbols() { - if (!importCompletionNode) + if (!importStatementCompletion) return 0 /* GlobalsSearch.Continue */; isNewIdentifierLocation = true; collectAutoImports(); @@ -136515,7 +137732,7 @@ var ts; } } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 305 /* SyntaxKind.SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 308 /* SyntaxKind.SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false, ts.isClassLike(scopeNode.parent) ? scopeNode : undefined); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { @@ -136535,7 +137752,7 @@ var ts; } function shouldOfferImportCompletions() { // If already typing an import statement, provide completions for it. - if (importCompletionNode) + if (importStatementCompletion) return true; // If current completion is for non-contextual Object literal shortahands, ignore auto-import symbols if (isNonContextualObjectLiteral) @@ -136554,10 +137771,10 @@ var ts; } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { - case 305 /* SyntaxKind.SourceFile */: - case 223 /* SyntaxKind.TemplateExpression */: - case 288 /* SyntaxKind.JsxExpression */: - case 235 /* SyntaxKind.Block */: + case 308 /* SyntaxKind.SourceFile */: + case 225 /* SyntaxKind.TemplateExpression */: + case 291 /* SyntaxKind.JsxExpression */: + case 238 /* SyntaxKind.Block */: return true; default: return ts.isStatement(scopeNode); @@ -136565,7 +137782,7 @@ var ts; } function isTypeOnlyCompletion() { return insideJsDocTagTypeExpression - || !!importCompletionNode && ts.isTypeOnlyImportOrExportDeclaration(location.parent) + || !!importStatementCompletion && ts.isTypeOnlyImportOrExportDeclaration(location.parent) || !isContextTokenValueLocation(contextToken) && (ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker) || ts.isPartOfTypeNode(location) @@ -136574,28 +137791,30 @@ var ts; function isContextTokenValueLocation(contextToken) { return contextToken && ((contextToken.kind === 112 /* SyntaxKind.TypeOfKeyword */ && - (contextToken.parent.kind === 181 /* SyntaxKind.TypeQuery */ || ts.isTypeOfExpression(contextToken.parent))) || - (contextToken.kind === 128 /* SyntaxKind.AssertsKeyword */ && contextToken.parent.kind === 177 /* SyntaxKind.TypePredicate */)); + (contextToken.parent.kind === 183 /* SyntaxKind.TypeQuery */ || ts.isTypeOfExpression(contextToken.parent))) || + (contextToken.kind === 129 /* SyntaxKind.AssertsKeyword */ && contextToken.parent.kind === 179 /* SyntaxKind.TypePredicate */)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { case 58 /* SyntaxKind.ColonToken */: - return parentKind === 167 /* SyntaxKind.PropertyDeclaration */ || - parentKind === 166 /* SyntaxKind.PropertySignature */ || - parentKind === 164 /* SyntaxKind.Parameter */ || - parentKind === 254 /* SyntaxKind.VariableDeclaration */ || + return parentKind === 169 /* SyntaxKind.PropertyDeclaration */ || + parentKind === 168 /* SyntaxKind.PropertySignature */ || + parentKind === 166 /* SyntaxKind.Parameter */ || + parentKind === 257 /* SyntaxKind.VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); case 63 /* SyntaxKind.EqualsToken */: - return parentKind === 259 /* SyntaxKind.TypeAliasDeclaration */; - case 127 /* SyntaxKind.AsKeyword */: - return parentKind === 229 /* SyntaxKind.AsExpression */; + return parentKind === 262 /* SyntaxKind.TypeAliasDeclaration */; + case 128 /* SyntaxKind.AsKeyword */: + return parentKind === 231 /* SyntaxKind.AsExpression */; case 29 /* SyntaxKind.LessThanToken */: - return parentKind === 178 /* SyntaxKind.TypeReference */ || - parentKind === 211 /* SyntaxKind.TypeAssertionExpression */; + return parentKind === 180 /* SyntaxKind.TypeReference */ || + parentKind === 213 /* SyntaxKind.TypeAssertionExpression */; case 94 /* SyntaxKind.ExtendsKeyword */: - return parentKind === 163 /* SyntaxKind.TypeParameter */; + return parentKind === 165 /* SyntaxKind.TypeParameter */; + case 150 /* SyntaxKind.SatisfiesKeyword */: + return parentKind === 235 /* SyntaxKind.SatisfiesExpression */; } } return false; @@ -136613,8 +137832,7 @@ var ts; flags |= 1 /* CompletionInfoFlags.MayIncludeAutoImports */; // import { type | -> token text should be blank var isAfterTypeOnlyImportSpecifierModifier = previousToken === contextToken - && importCompletionNode - && couldBeTypeOnlyImportSpecifier(importCompletionNode, contextToken); + && importStatementCompletion; var lowerCaseTokenText = isAfterTypeOnlyImportSpecifierModifier ? "" : previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; @@ -136622,14 +137840,14 @@ var ts; var exportInfo = ts.getExportInfoMap(sourceFile, host, program, preferences, cancellationToken); var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); - resolvingModuleSpecifiers("collectAutoImports", host, importSpecifierResolver || (importSpecifierResolver = ts.codefix.createImportSpecifierResolver(sourceFile, program, host, preferences)), program, position, preferences, !!importCompletionNode, ts.isValidTypeOnlyAliasUseSite(location), function (context) { + resolvingModuleSpecifiers("collectAutoImports", host, importSpecifierResolver || (importSpecifierResolver = ts.codefix.createImportSpecifierResolver(sourceFile, program, host, preferences)), program, position, preferences, !!importStatementCompletion, ts.isValidTypeOnlyAliasUseSite(location), function (context) { exportInfo.search(sourceFile.path, /*preferCapitalized*/ isRightOfOpenTag, function (symbolName, targetFlags) { if (!ts.isIdentifierText(symbolName, ts.getEmitScriptTarget(host.getCompilationSettings()))) return false; if (!detailsEntryId && ts.isStringANonContextualKeyword(symbolName)) return false; - if (!isTypeOnlyLocation && !importCompletionNode && !(targetFlags & 111551 /* SymbolFlags.Value */)) + if (!isTypeOnlyLocation && !importStatementCompletion && !(targetFlags & 111551 /* SymbolFlags.Value */)) return false; if (isTypeOnlyLocation && !(targetFlags & (1536 /* SymbolFlags.Module */ | 788968 /* SymbolFlags.Type */))) return false; @@ -136710,7 +137928,7 @@ var ts; return; } symbolToOriginInfoMap[symbols.length] = origin; - symbolToSortTextMap[symbolId] = importCompletionNode ? Completions.SortText.LocationPriority : Completions.SortText.AutoImportSuggestions; + symbolToSortTextMap[symbolId] = importStatementCompletion ? Completions.SortText.LocationPriority : Completions.SortText.AutoImportSuggestions; symbols.push(symbol); } /* Mutates `symbols` and `symbolToOriginInfoMap`. */ @@ -136786,18 +138004,18 @@ var ts; // - contextToken: GreaterThanToken (before cursor) // - location: JsxSelfClosingElement or JsxOpeningElement // - contextToken.parent === location - if (location === contextToken.parent && (location.kind === 280 /* SyntaxKind.JsxOpeningElement */ || location.kind === 279 /* SyntaxKind.JsxSelfClosingElement */)) { + if (location === contextToken.parent && (location.kind === 283 /* SyntaxKind.JsxOpeningElement */ || location.kind === 282 /* SyntaxKind.JsxSelfClosingElement */)) { return false; } - if (contextToken.parent.kind === 280 /* SyntaxKind.JsxOpeningElement */) { + if (contextToken.parent.kind === 283 /* SyntaxKind.JsxOpeningElement */) { //
/**/ // - contextToken: GreaterThanToken (before cursor) // - location: JSXElement // - different parents (JSXOpeningElement, JSXElement) - return location.parent.kind !== 280 /* SyntaxKind.JsxOpeningElement */; + return location.parent.kind !== 283 /* SyntaxKind.JsxOpeningElement */; } - if (contextToken.parent.kind === 281 /* SyntaxKind.JsxClosingElement */ || contextToken.parent.kind === 279 /* SyntaxKind.JsxSelfClosingElement */) { - return !!contextToken.parent.parent && contextToken.parent.parent.kind === 278 /* SyntaxKind.JsxElement */; + if (contextToken.parent.kind === 284 /* SyntaxKind.JsxClosingElement */ || contextToken.parent.kind === 282 /* SyntaxKind.JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 281 /* SyntaxKind.JsxElement */; } } return false; @@ -136809,44 +138027,44 @@ var ts; // Previous token may have been a keyword that was converted to an identifier. switch (tokenKind) { case 27 /* SyntaxKind.CommaToken */: - return containingNodeKind === 208 /* SyntaxKind.CallExpression */ // func( a, | - || containingNodeKind === 171 /* SyntaxKind.Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 209 /* SyntaxKind.NewExpression */ // new C(a, | - || containingNodeKind === 204 /* SyntaxKind.ArrayLiteralExpression */ // [a, | - || containingNodeKind === 221 /* SyntaxKind.BinaryExpression */ // const x = (a, | - || containingNodeKind === 179 /* SyntaxKind.FunctionType */ // var x: (s: string, list| - || containingNodeKind === 205 /* SyntaxKind.ObjectLiteralExpression */; // const obj = { x, | + return containingNodeKind === 210 /* SyntaxKind.CallExpression */ // func( a, | + || containingNodeKind === 173 /* SyntaxKind.Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 211 /* SyntaxKind.NewExpression */ // new C(a, | + || containingNodeKind === 206 /* SyntaxKind.ArrayLiteralExpression */ // [a, | + || containingNodeKind === 223 /* SyntaxKind.BinaryExpression */ // const x = (a, | + || containingNodeKind === 181 /* SyntaxKind.FunctionType */ // var x: (s: string, list| + || containingNodeKind === 207 /* SyntaxKind.ObjectLiteralExpression */; // const obj = { x, | case 20 /* SyntaxKind.OpenParenToken */: - return containingNodeKind === 208 /* SyntaxKind.CallExpression */ // func( | - || containingNodeKind === 171 /* SyntaxKind.Constructor */ // constructor( | - || containingNodeKind === 209 /* SyntaxKind.NewExpression */ // new C(a| - || containingNodeKind === 212 /* SyntaxKind.ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 191 /* SyntaxKind.ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + return containingNodeKind === 210 /* SyntaxKind.CallExpression */ // func( | + || containingNodeKind === 173 /* SyntaxKind.Constructor */ // constructor( | + || containingNodeKind === 211 /* SyntaxKind.NewExpression */ // new C(a| + || containingNodeKind === 214 /* SyntaxKind.ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 193 /* SyntaxKind.ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 22 /* SyntaxKind.OpenBracketToken */: - return containingNodeKind === 204 /* SyntaxKind.ArrayLiteralExpression */ // [ | - || containingNodeKind === 176 /* SyntaxKind.IndexSignature */ // [ | : string ] - || containingNodeKind === 162 /* SyntaxKind.ComputedPropertyName */; // [ | /* this can become an index signature */ - case 141 /* SyntaxKind.ModuleKeyword */: // module | - case 142 /* SyntaxKind.NamespaceKeyword */: // namespace | + return containingNodeKind === 206 /* SyntaxKind.ArrayLiteralExpression */ // [ | + || containingNodeKind === 178 /* SyntaxKind.IndexSignature */ // [ | : string ] + || containingNodeKind === 164 /* SyntaxKind.ComputedPropertyName */; // [ | /* this can become an index signature */ + case 142 /* SyntaxKind.ModuleKeyword */: // module | + case 143 /* SyntaxKind.NamespaceKeyword */: // namespace | case 100 /* SyntaxKind.ImportKeyword */: // import | return true; case 24 /* SyntaxKind.DotToken */: - return containingNodeKind === 261 /* SyntaxKind.ModuleDeclaration */; // module A.| + return containingNodeKind === 264 /* SyntaxKind.ModuleDeclaration */; // module A.| case 18 /* SyntaxKind.OpenBraceToken */: - return containingNodeKind === 257 /* SyntaxKind.ClassDeclaration */ // class A { | - || containingNodeKind === 205 /* SyntaxKind.ObjectLiteralExpression */; // const obj = { | + return containingNodeKind === 260 /* SyntaxKind.ClassDeclaration */ // class A { | + || containingNodeKind === 207 /* SyntaxKind.ObjectLiteralExpression */; // const obj = { | case 63 /* SyntaxKind.EqualsToken */: - return containingNodeKind === 254 /* SyntaxKind.VariableDeclaration */ // const x = a| - || containingNodeKind === 221 /* SyntaxKind.BinaryExpression */; // x = a| + return containingNodeKind === 257 /* SyntaxKind.VariableDeclaration */ // const x = a| + || containingNodeKind === 223 /* SyntaxKind.BinaryExpression */; // x = a| case 15 /* SyntaxKind.TemplateHead */: - return containingNodeKind === 223 /* SyntaxKind.TemplateExpression */; // `aa ${| + return containingNodeKind === 225 /* SyntaxKind.TemplateExpression */; // `aa ${| case 16 /* SyntaxKind.TemplateMiddle */: - return containingNodeKind === 233 /* SyntaxKind.TemplateSpan */; // `aa ${10} dd ${| - case 131 /* SyntaxKind.AsyncKeyword */: - return containingNodeKind === 169 /* SyntaxKind.MethodDeclaration */ // const obj = { async c|() - || containingNodeKind === 297 /* SyntaxKind.ShorthandPropertyAssignment */; // const obj = { async c| + return containingNodeKind === 236 /* SyntaxKind.TemplateSpan */; // `aa ${10} dd ${| + case 132 /* SyntaxKind.AsyncKeyword */: + return containingNodeKind === 171 /* SyntaxKind.MethodDeclaration */ // const obj = { async c|() + || containingNodeKind === 300 /* SyntaxKind.ShorthandPropertyAssignment */; // const obj = { async c| case 41 /* SyntaxKind.AsteriskToken */: - return containingNodeKind === 169 /* SyntaxKind.MethodDeclaration */; // const obj = { * c| + return containingNodeKind === 171 /* SyntaxKind.MethodDeclaration */; // const obj = { * c| } if (isClassMemberCompletionKeyword(tokenKind)) { return true; @@ -136896,7 +138114,7 @@ var ts; completionKind = 0 /* CompletionKind.ObjectPropertyDeclaration */; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) { var instantiatedType = tryGetObjectLiteralContextualType(objectLikeContainer, typeChecker); // Check completions for Object property value shorthand if (instantiatedType === undefined) { @@ -136921,7 +138139,7 @@ var ts; } } else { - ts.Debug.assert(objectLikeContainer.kind === 201 /* SyntaxKind.ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 203 /* SyntaxKind.ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -136932,12 +138150,12 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = ts.hasInitializer(rootDeclaration) || !!ts.getEffectiveTypeAnnotationNode(rootDeclaration) || rootDeclaration.parent.parent.kind === 244 /* SyntaxKind.ForOfStatement */; - if (!canGetType && rootDeclaration.kind === 164 /* SyntaxKind.Parameter */) { + var canGetType = ts.hasInitializer(rootDeclaration) || !!ts.getEffectiveTypeAnnotationNode(rootDeclaration) || rootDeclaration.parent.parent.kind === 247 /* SyntaxKind.ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 166 /* SyntaxKind.Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 169 /* SyntaxKind.MethodDeclaration */ || rootDeclaration.parent.kind === 173 /* SyntaxKind.SetAccessor */) { + else if (rootDeclaration.parent.kind === 171 /* SyntaxKind.MethodDeclaration */ || rootDeclaration.parent.kind === 175 /* SyntaxKind.SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -136956,7 +138174,7 @@ var ts; var filteredMembers = filterObjectMembersList(typeMembers, ts.Debug.checkDefined(existingMembers)); symbols = ts.concatenate(symbols, filteredMembers); setSortTextToOptionalMember(); - if (objectLikeContainer.kind === 205 /* SyntaxKind.ObjectLiteralExpression */ + if (objectLikeContainer.kind === 207 /* SyntaxKind.ObjectLiteralExpression */ && preferences.includeCompletionsWithObjectLiteralMethodSnippets && preferences.includeCompletionsWithInsertText) { transformObjectLiteralMembersSortText(symbolsStartIndex); @@ -136991,10 +138209,10 @@ var ts; keywordFilters = 8 /* KeywordCompletionFilters.TypeKeyword */; } // try to show exported member for imported/re-exported module - var moduleSpecifier = (namedImportsOrExports.kind === 269 /* SyntaxKind.NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifier = (namedImportsOrExports.kind === 272 /* SyntaxKind.NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; if (!moduleSpecifier) { isNewIdentifierLocation = true; - return namedImportsOrExports.kind === 269 /* SyntaxKind.NamedImports */ ? 2 /* GlobalsSearch.Fail */ : 0 /* GlobalsSearch.Continue */; + return namedImportsOrExports.kind === 272 /* SyntaxKind.NamedImports */ ? 2 /* GlobalsSearch.Fail */ : 0 /* GlobalsSearch.Continue */; } var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) { @@ -137139,11 +138357,11 @@ var ts; case 30 /* SyntaxKind.LessThanSlashToken */: case 43 /* SyntaxKind.SlashToken */: case 79 /* SyntaxKind.Identifier */: - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 286 /* SyntaxKind.JsxAttributes */: - case 285 /* SyntaxKind.JsxAttribute */: - case 287 /* SyntaxKind.JsxSpreadAttribute */: - if (parent && (parent.kind === 279 /* SyntaxKind.JsxSelfClosingElement */ || parent.kind === 280 /* SyntaxKind.JsxOpeningElement */)) { + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 289 /* SyntaxKind.JsxAttributes */: + case 288 /* SyntaxKind.JsxAttribute */: + case 290 /* SyntaxKind.JsxSpreadAttribute */: + if (parent && (parent.kind === 282 /* SyntaxKind.JsxSelfClosingElement */ || parent.kind === 283 /* SyntaxKind.JsxOpeningElement */)) { if (contextToken.kind === 31 /* SyntaxKind.GreaterThanToken */) { var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); if (!parent.typeArguments || (precedingToken && precedingToken.kind === 43 /* SyntaxKind.SlashToken */)) @@ -137151,7 +138369,7 @@ var ts; } return parent; } - else if (parent.kind === 285 /* SyntaxKind.JsxAttribute */) { + else if (parent.kind === 288 /* SyntaxKind.JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -137163,7 +138381,7 @@ var ts; // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 10 /* SyntaxKind.StringLiteral */: - if (parent && ((parent.kind === 285 /* SyntaxKind.JsxAttribute */) || (parent.kind === 287 /* SyntaxKind.JsxSpreadAttribute */))) { + if (parent && ((parent.kind === 288 /* SyntaxKind.JsxAttribute */) || (parent.kind === 290 /* SyntaxKind.JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -137173,8 +138391,8 @@ var ts; break; case 19 /* SyntaxKind.CloseBraceToken */: if (parent && - parent.kind === 288 /* SyntaxKind.JsxExpression */ && - parent.parent && parent.parent.kind === 285 /* SyntaxKind.JsxAttribute */) { + parent.kind === 291 /* SyntaxKind.JsxExpression */ && + parent.parent && parent.parent.kind === 288 /* SyntaxKind.JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -137182,7 +138400,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 287 /* SyntaxKind.JsxSpreadAttribute */) { + if (parent && parent.kind === 290 /* SyntaxKind.JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -137202,54 +138420,54 @@ var ts; var containingNodeKind = parent.kind; switch (contextToken.kind) { case 27 /* SyntaxKind.CommaToken */: - return containingNodeKind === 254 /* SyntaxKind.VariableDeclaration */ || + return containingNodeKind === 257 /* SyntaxKind.VariableDeclaration */ || isVariableDeclarationListButNotTypeArgument(contextToken) || - containingNodeKind === 237 /* SyntaxKind.VariableStatement */ || - containingNodeKind === 260 /* SyntaxKind.EnumDeclaration */ || // enum a { foo, | + containingNodeKind === 240 /* SyntaxKind.VariableStatement */ || + containingNodeKind === 263 /* SyntaxKind.EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 258 /* SyntaxKind.InterfaceDeclaration */ || // interface A= contextToken.pos); case 24 /* SyntaxKind.DotToken */: - return containingNodeKind === 202 /* SyntaxKind.ArrayBindingPattern */; // var [.| + return containingNodeKind === 204 /* SyntaxKind.ArrayBindingPattern */; // var [.| case 58 /* SyntaxKind.ColonToken */: - return containingNodeKind === 203 /* SyntaxKind.BindingElement */; // var {x :html| + return containingNodeKind === 205 /* SyntaxKind.BindingElement */; // var {x :html| case 22 /* SyntaxKind.OpenBracketToken */: - return containingNodeKind === 202 /* SyntaxKind.ArrayBindingPattern */; // var [x| + return containingNodeKind === 204 /* SyntaxKind.ArrayBindingPattern */; // var [x| case 20 /* SyntaxKind.OpenParenToken */: - return containingNodeKind === 292 /* SyntaxKind.CatchClause */ || + return containingNodeKind === 295 /* SyntaxKind.CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 18 /* SyntaxKind.OpenBraceToken */: - return containingNodeKind === 260 /* SyntaxKind.EnumDeclaration */; // enum a { | + return containingNodeKind === 263 /* SyntaxKind.EnumDeclaration */; // enum a { | case 29 /* SyntaxKind.LessThanToken */: - return containingNodeKind === 257 /* SyntaxKind.ClassDeclaration */ || // class A< | - containingNodeKind === 226 /* SyntaxKind.ClassExpression */ || // var C = class D< | - containingNodeKind === 258 /* SyntaxKind.InterfaceDeclaration */ || // interface A< | - containingNodeKind === 259 /* SyntaxKind.TypeAliasDeclaration */ || // type List< | + return containingNodeKind === 260 /* SyntaxKind.ClassDeclaration */ || // class A< | + containingNodeKind === 228 /* SyntaxKind.ClassExpression */ || // var C = class D< | + containingNodeKind === 261 /* SyntaxKind.InterfaceDeclaration */ || // interface A< | + containingNodeKind === 262 /* SyntaxKind.TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 124 /* SyntaxKind.StaticKeyword */: - return containingNodeKind === 167 /* SyntaxKind.PropertyDeclaration */ && !ts.isClassLike(parent.parent); + return containingNodeKind === 169 /* SyntaxKind.PropertyDeclaration */ && !ts.isClassLike(parent.parent); case 25 /* SyntaxKind.DotDotDotToken */: - return containingNodeKind === 164 /* SyntaxKind.Parameter */ || - (!!parent.parent && parent.parent.kind === 202 /* SyntaxKind.ArrayBindingPattern */); // var [...z| + return containingNodeKind === 166 /* SyntaxKind.Parameter */ || + (!!parent.parent && parent.parent.kind === 204 /* SyntaxKind.ArrayBindingPattern */); // var [...z| case 123 /* SyntaxKind.PublicKeyword */: case 121 /* SyntaxKind.PrivateKeyword */: case 122 /* SyntaxKind.ProtectedKeyword */: - return containingNodeKind === 164 /* SyntaxKind.Parameter */ && !ts.isConstructorDeclaration(parent.parent); - case 127 /* SyntaxKind.AsKeyword */: - return containingNodeKind === 270 /* SyntaxKind.ImportSpecifier */ || - containingNodeKind === 275 /* SyntaxKind.ExportSpecifier */ || - containingNodeKind === 268 /* SyntaxKind.NamespaceImport */; - case 136 /* SyntaxKind.GetKeyword */: - case 149 /* SyntaxKind.SetKeyword */: + return containingNodeKind === 166 /* SyntaxKind.Parameter */ && !ts.isConstructorDeclaration(parent.parent); + case 128 /* SyntaxKind.AsKeyword */: + return containingNodeKind === 273 /* SyntaxKind.ImportSpecifier */ || + containingNodeKind === 278 /* SyntaxKind.ExportSpecifier */ || + containingNodeKind === 271 /* SyntaxKind.NamespaceImport */; + case 137 /* SyntaxKind.GetKeyword */: + case 151 /* SyntaxKind.SetKeyword */: return !isFromObjectTypeDeclaration(contextToken); case 79 /* SyntaxKind.Identifier */: - if (containingNodeKind === 270 /* SyntaxKind.ImportSpecifier */ && + if (containingNodeKind === 273 /* SyntaxKind.ImportSpecifier */ && contextToken === parent.name && contextToken.text === "type") { // import { type | } @@ -137264,11 +138482,11 @@ var ts; case 100 /* SyntaxKind.ImportKeyword */: case 119 /* SyntaxKind.LetKeyword */: case 85 /* SyntaxKind.ConstKeyword */: - case 137 /* SyntaxKind.InferKeyword */: + case 138 /* SyntaxKind.InferKeyword */: return true; - case 152 /* SyntaxKind.TypeKeyword */: + case 154 /* SyntaxKind.TypeKeyword */: // import { type foo| } - return containingNodeKind !== 270 /* SyntaxKind.ImportSpecifier */; + return containingNodeKind !== 273 /* SyntaxKind.ImportSpecifier */; case 41 /* SyntaxKind.AsteriskToken */: return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } @@ -137293,7 +138511,7 @@ var ts; case 126 /* SyntaxKind.AbstractKeyword */: case 84 /* SyntaxKind.ClassKeyword */: case 85 /* SyntaxKind.ConstKeyword */: - case 135 /* SyntaxKind.DeclareKeyword */: + case 136 /* SyntaxKind.DeclareKeyword */: case 92 /* SyntaxKind.EnumKeyword */: case 98 /* SyntaxKind.FunctionKeyword */: case 118 /* SyntaxKind.InterfaceKeyword */: @@ -137304,7 +138522,7 @@ var ts; case 124 /* SyntaxKind.StaticKeyword */: case 113 /* SyntaxKind.VarKeyword */: return true; - case 131 /* SyntaxKind.AsyncKeyword */: + case 132 /* SyntaxKind.AsyncKeyword */: return ts.isPropertyDeclaration(contextToken.parent); } // If we are inside a class declaration, and `constructor` is totally not present, @@ -137313,7 +138531,7 @@ var ts; if (ancestorClassLike && contextToken === previousToken && isPreviousPropertyDeclarationTerminated(contextToken, position)) { return false; // Don't block completions. } - var ancestorPropertyDeclaraion = ts.getAncestor(contextToken.parent, 167 /* SyntaxKind.PropertyDeclaration */); + var ancestorPropertyDeclaraion = ts.getAncestor(contextToken.parent, 169 /* SyntaxKind.PropertyDeclaration */); // If we are inside a class declaration and typing `constructor` after property declaration... if (ancestorPropertyDeclaraion && contextToken !== previousToken @@ -137345,7 +138563,7 @@ var ts; || !ts.positionsAreOnSameLine(contextToken.end, position, sourceFile)); } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 171 /* SyntaxKind.Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 173 /* SyntaxKind.Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* SyntaxKind.NumericLiteral */) { @@ -137355,7 +138573,7 @@ var ts; return false; } function isVariableDeclarationListButNotTypeArgument(node) { - return node.parent.kind === 255 /* SyntaxKind.VariableDeclarationList */ + return node.parent.kind === 258 /* SyntaxKind.VariableDeclarationList */ && !ts.isPossiblyTypeArgumentPosition(node, sourceFile, typeChecker); } /** @@ -137373,13 +138591,13 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 296 /* SyntaxKind.PropertyAssignment */ && - m.kind !== 297 /* SyntaxKind.ShorthandPropertyAssignment */ && - m.kind !== 203 /* SyntaxKind.BindingElement */ && - m.kind !== 169 /* SyntaxKind.MethodDeclaration */ && - m.kind !== 172 /* SyntaxKind.GetAccessor */ && - m.kind !== 173 /* SyntaxKind.SetAccessor */ && - m.kind !== 298 /* SyntaxKind.SpreadAssignment */) { + if (m.kind !== 299 /* SyntaxKind.PropertyAssignment */ && + m.kind !== 300 /* SyntaxKind.ShorthandPropertyAssignment */ && + m.kind !== 205 /* SyntaxKind.BindingElement */ && + m.kind !== 171 /* SyntaxKind.MethodDeclaration */ && + m.kind !== 174 /* SyntaxKind.GetAccessor */ && + m.kind !== 175 /* SyntaxKind.SetAccessor */ && + m.kind !== 301 /* SyntaxKind.SpreadAssignment */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -137470,10 +138688,10 @@ var ts; for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 167 /* SyntaxKind.PropertyDeclaration */ && - m.kind !== 169 /* SyntaxKind.MethodDeclaration */ && - m.kind !== 172 /* SyntaxKind.GetAccessor */ && - m.kind !== 173 /* SyntaxKind.SetAccessor */) { + if (m.kind !== 169 /* SyntaxKind.PropertyDeclaration */ && + m.kind !== 171 /* SyntaxKind.MethodDeclaration */ && + m.kind !== 174 /* SyntaxKind.GetAccessor */ && + m.kind !== 175 /* SyntaxKind.SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -137515,7 +138733,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 285 /* SyntaxKind.JsxAttribute */) { + if (attr.kind === 288 /* SyntaxKind.JsxAttribute */) { seenNames.add(attr.name.escapedText); } else if (ts.isJsxSpreadAttribute(attr)) { @@ -137613,7 +138831,7 @@ var ts; var _keywordCompletions = []; var allKeywordsCompletions = ts.memoize(function () { var res = []; - for (var i = 81 /* SyntaxKind.FirstKeyword */; i <= 160 /* SyntaxKind.LastKeyword */; i++) { + for (var i = 81 /* SyntaxKind.FirstKeyword */; i <= 162 /* SyntaxKind.LastKeyword */; i++) { res.push({ name: ts.tokenToString(i), kind: "keyword" /* ScriptElementKind.keyword */, @@ -137639,12 +138857,12 @@ var ts; return false; case 1 /* KeywordCompletionFilters.All */: return isFunctionLikeBodyKeyword(kind) - || kind === 135 /* SyntaxKind.DeclareKeyword */ - || kind === 141 /* SyntaxKind.ModuleKeyword */ - || kind === 152 /* SyntaxKind.TypeKeyword */ - || kind === 142 /* SyntaxKind.NamespaceKeyword */ + || kind === 136 /* SyntaxKind.DeclareKeyword */ + || kind === 142 /* SyntaxKind.ModuleKeyword */ + || kind === 154 /* SyntaxKind.TypeKeyword */ + || kind === 143 /* SyntaxKind.NamespaceKeyword */ || kind === 126 /* SyntaxKind.AbstractKeyword */ - || ts.isTypeKeyword(kind) && kind !== 153 /* SyntaxKind.UndefinedKeyword */; + || ts.isTypeKeyword(kind) && kind !== 155 /* SyntaxKind.UndefinedKeyword */; case 5 /* KeywordCompletionFilters.FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); case 2 /* KeywordCompletionFilters.ClassElementKeywords */: @@ -137658,7 +138876,7 @@ var ts; case 7 /* KeywordCompletionFilters.TypeKeywords */: return ts.isTypeKeyword(kind); case 8 /* KeywordCompletionFilters.TypeKeyword */: - return kind === 152 /* SyntaxKind.TypeKeyword */; + return kind === 154 /* SyntaxKind.TypeKeyword */; default: return ts.Debug.assertNever(keywordFilter); } @@ -137667,59 +138885,61 @@ var ts; function isTypeScriptOnlyKeyword(kind) { switch (kind) { case 126 /* SyntaxKind.AbstractKeyword */: - case 130 /* SyntaxKind.AnyKeyword */: - case 158 /* SyntaxKind.BigIntKeyword */: - case 133 /* SyntaxKind.BooleanKeyword */: - case 135 /* SyntaxKind.DeclareKeyword */: + case 131 /* SyntaxKind.AnyKeyword */: + case 160 /* SyntaxKind.BigIntKeyword */: + case 134 /* SyntaxKind.BooleanKeyword */: + case 136 /* SyntaxKind.DeclareKeyword */: case 92 /* SyntaxKind.EnumKeyword */: - case 157 /* SyntaxKind.GlobalKeyword */: + case 159 /* SyntaxKind.GlobalKeyword */: case 117 /* SyntaxKind.ImplementsKeyword */: - case 137 /* SyntaxKind.InferKeyword */: + case 138 /* SyntaxKind.InferKeyword */: case 118 /* SyntaxKind.InterfaceKeyword */: - case 139 /* SyntaxKind.IsKeyword */: - case 140 /* SyntaxKind.KeyOfKeyword */: - case 141 /* SyntaxKind.ModuleKeyword */: - case 142 /* SyntaxKind.NamespaceKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: - case 147 /* SyntaxKind.NumberKeyword */: - case 148 /* SyntaxKind.ObjectKeyword */: - case 159 /* SyntaxKind.OverrideKeyword */: + case 140 /* SyntaxKind.IsKeyword */: + case 141 /* SyntaxKind.KeyOfKeyword */: + case 142 /* SyntaxKind.ModuleKeyword */: + case 143 /* SyntaxKind.NamespaceKeyword */: + case 144 /* SyntaxKind.NeverKeyword */: + case 148 /* SyntaxKind.NumberKeyword */: + case 149 /* SyntaxKind.ObjectKeyword */: + case 161 /* SyntaxKind.OverrideKeyword */: case 121 /* SyntaxKind.PrivateKeyword */: case 122 /* SyntaxKind.ProtectedKeyword */: case 123 /* SyntaxKind.PublicKeyword */: - case 145 /* SyntaxKind.ReadonlyKeyword */: - case 150 /* SyntaxKind.StringKeyword */: - case 151 /* SyntaxKind.SymbolKeyword */: - case 152 /* SyntaxKind.TypeKeyword */: - case 154 /* SyntaxKind.UniqueKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: + case 146 /* SyntaxKind.ReadonlyKeyword */: + case 152 /* SyntaxKind.StringKeyword */: + case 153 /* SyntaxKind.SymbolKeyword */: + case 154 /* SyntaxKind.TypeKeyword */: + case 156 /* SyntaxKind.UniqueKeyword */: + case 157 /* SyntaxKind.UnknownKeyword */: return true; default: return false; } } function isInterfaceOrTypeLiteralCompletionKeyword(kind) { - return kind === 145 /* SyntaxKind.ReadonlyKeyword */; + return kind === 146 /* SyntaxKind.ReadonlyKeyword */; } function isClassMemberCompletionKeyword(kind) { switch (kind) { case 126 /* SyntaxKind.AbstractKeyword */: - case 134 /* SyntaxKind.ConstructorKeyword */: - case 136 /* SyntaxKind.GetKeyword */: - case 149 /* SyntaxKind.SetKeyword */: - case 131 /* SyntaxKind.AsyncKeyword */: - case 135 /* SyntaxKind.DeclareKeyword */: - case 159 /* SyntaxKind.OverrideKeyword */: + case 127 /* SyntaxKind.AccessorKeyword */: + case 135 /* SyntaxKind.ConstructorKeyword */: + case 137 /* SyntaxKind.GetKeyword */: + case 151 /* SyntaxKind.SetKeyword */: + case 132 /* SyntaxKind.AsyncKeyword */: + case 136 /* SyntaxKind.DeclareKeyword */: + case 161 /* SyntaxKind.OverrideKeyword */: return true; default: return ts.isClassMemberModifier(kind); } } function isFunctionLikeBodyKeyword(kind) { - return kind === 131 /* SyntaxKind.AsyncKeyword */ - || kind === 132 /* SyntaxKind.AwaitKeyword */ - || kind === 127 /* SyntaxKind.AsKeyword */ - || kind === 152 /* SyntaxKind.TypeKeyword */ + return kind === 132 /* SyntaxKind.AsyncKeyword */ + || kind === 133 /* SyntaxKind.AwaitKeyword */ + || kind === 128 /* SyntaxKind.AsKeyword */ + || kind === 150 /* SyntaxKind.SatisfiesKeyword */ + || kind === 154 /* SyntaxKind.TypeKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { @@ -137744,7 +138964,7 @@ var ts; && contextToken === parent.moduleSpecifier && tokenLine === currentLine) { entries.push({ - name: ts.tokenToString(129 /* SyntaxKind.AssertKeyword */), + name: ts.tokenToString(130 /* SyntaxKind.AssertKeyword */), kind: "keyword" /* ScriptElementKind.keyword */, kindModifiers: "" /* ScriptElementKindModifier.none */, sortText: Completions.SortText.GlobalsOrKeywords, @@ -137810,7 +139030,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) { // class c { method() { } | method2() { } } switch (location.kind) { - case 348 /* SyntaxKind.SyntaxList */: + case 351 /* SyntaxKind.SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* SyntaxKind.EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -137836,7 +139056,7 @@ var ts; if (!contextToken) return undefined; // class C { blah; constructor/**/ } and so on - if (location.kind === 134 /* SyntaxKind.ConstructorKeyword */ + if (location.kind === 135 /* SyntaxKind.ConstructorKeyword */ // class C { blah \n constructor/**/ } || (ts.isIdentifier(contextToken) && ts.isPropertyDeclaration(contextToken.parent) && ts.isClassLike(location))) { return ts.findAncestor(contextToken, ts.isClassLike); @@ -137879,7 +139099,7 @@ var ts; case 26 /* SyntaxKind.SemicolonToken */: case 27 /* SyntaxKind.CommaToken */: case 79 /* SyntaxKind.Identifier */: - if (parent.kind === 166 /* SyntaxKind.PropertySignature */ && ts.isTypeLiteralNode(parent.parent)) { + if (parent.kind === 168 /* SyntaxKind.PropertySignature */ && ts.isTypeLiteralNode(parent.parent)) { return parent.parent; } break; @@ -137896,11 +139116,11 @@ var ts; if (!t) return undefined; switch (node.kind) { - case 166 /* SyntaxKind.PropertySignature */: + case 168 /* SyntaxKind.PropertySignature */: return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); - case 188 /* SyntaxKind.IntersectionType */: - case 182 /* SyntaxKind.TypeLiteral */: - case 187 /* SyntaxKind.UnionType */: + case 190 /* SyntaxKind.IntersectionType */: + case 184 /* SyntaxKind.TypeLiteral */: + case 189 /* SyntaxKind.UnionType */: return t; } } @@ -137928,7 +139148,7 @@ var ts; ? !!ts.tryGetImportFromModuleSpecifier(contextToken) : contextToken.kind === 43 /* SyntaxKind.SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); case " ": - return !!contextToken && ts.isImportKeyword(contextToken) && contextToken.parent.kind === 305 /* SyntaxKind.SourceFile */; + return !!contextToken && ts.isImportKeyword(contextToken) && contextToken.parent.kind === 308 /* SyntaxKind.SourceFile */; default: return ts.Debug.assertNever(triggerCharacter); } @@ -137976,21 +139196,22 @@ var ts; return undefined; } function getImportStatementCompletionInfo(contextToken) { + var _a, _b, _c; var keywordCompletion; var isKeywordOnlyCompletion = false; var candidate = getCandidate(); return { isKeywordOnlyCompletion: isKeywordOnlyCompletion, keywordCompletion: keywordCompletion, - isNewIdentifierLocation: !!(candidate || keywordCompletion === 152 /* SyntaxKind.TypeKeyword */), - replacementNode: candidate && ts.rangeIsOnSingleLine(candidate, candidate.getSourceFile()) - ? candidate - : undefined + isNewIdentifierLocation: !!(candidate || keywordCompletion === 154 /* SyntaxKind.TypeKeyword */), + isTopLevelTypeOnly: !!((_b = (_a = ts.tryCast(candidate, ts.isImportDeclaration)) === null || _a === void 0 ? void 0 : _a.importClause) === null || _b === void 0 ? void 0 : _b.isTypeOnly) || !!((_c = ts.tryCast(candidate, ts.isImportEqualsDeclaration)) === null || _c === void 0 ? void 0 : _c.isTypeOnly), + couldBeTypeOnlyImportSpecifier: !!candidate && couldBeTypeOnlyImportSpecifier(candidate, contextToken), + replacementSpan: getSingleLineReplacementSpanForImportCompletionNode(candidate), }; function getCandidate() { var parent = contextToken.parent; if (ts.isImportEqualsDeclaration(parent)) { - keywordCompletion = contextToken.kind === 152 /* SyntaxKind.TypeKeyword */ ? undefined : 152 /* SyntaxKind.TypeKeyword */; + keywordCompletion = contextToken.kind === 154 /* SyntaxKind.TypeKeyword */ ? undefined : 154 /* SyntaxKind.TypeKeyword */; return isModuleSpecifierMissingOrEmpty(parent.moduleReference) ? parent : undefined; } if (couldBeTypeOnlyImportSpecifier(parent, contextToken) && canCompleteFromNamedBindings(parent.parent)) { @@ -138000,13 +139221,13 @@ var ts; if (!parent.parent.isTypeOnly && (contextToken.kind === 18 /* SyntaxKind.OpenBraceToken */ || contextToken.kind === 100 /* SyntaxKind.ImportKeyword */ || contextToken.kind === 27 /* SyntaxKind.CommaToken */)) { - keywordCompletion = 152 /* SyntaxKind.TypeKeyword */; + keywordCompletion = 154 /* SyntaxKind.TypeKeyword */; } if (canCompleteFromNamedBindings(parent)) { // At `import { ... } |` or `import * as Foo |`, the only possible completion is `from` if (contextToken.kind === 19 /* SyntaxKind.CloseBraceToken */ || contextToken.kind === 79 /* SyntaxKind.Identifier */) { isKeywordOnlyCompletion = true; - keywordCompletion = 156 /* SyntaxKind.FromKeyword */; + keywordCompletion = 158 /* SyntaxKind.FromKeyword */; } else { return parent.parent.parent; @@ -138016,25 +139237,82 @@ var ts; } if (ts.isImportKeyword(contextToken) && ts.isSourceFile(parent)) { // A lone import keyword with nothing following it does not parse as a statement at all - keywordCompletion = 152 /* SyntaxKind.TypeKeyword */; + keywordCompletion = 154 /* SyntaxKind.TypeKeyword */; return contextToken; } if (ts.isImportKeyword(contextToken) && ts.isImportDeclaration(parent)) { // `import s| from` - keywordCompletion = 152 /* SyntaxKind.TypeKeyword */; + keywordCompletion = 154 /* SyntaxKind.TypeKeyword */; return isModuleSpecifierMissingOrEmpty(parent.moduleSpecifier) ? parent : undefined; } return undefined; } } + function getSingleLineReplacementSpanForImportCompletionNode(node) { + var _a, _b, _c; + if (!node) + return undefined; + var top = (_a = ts.findAncestor(node, ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration))) !== null && _a !== void 0 ? _a : node; + var sourceFile = top.getSourceFile(); + if (ts.rangeIsOnSingleLine(top, sourceFile)) { + return ts.createTextSpanFromNode(top, sourceFile); + } + // ImportKeyword was necessarily on one line; ImportSpecifier was necessarily parented in an ImportDeclaration + ts.Debug.assert(top.kind !== 100 /* SyntaxKind.ImportKeyword */ && top.kind !== 273 /* SyntaxKind.ImportSpecifier */); + // Guess which point in the import might actually be a later statement parsed as part of the import + // during parser recovery - either in the middle of named imports, or the module specifier. + var potentialSplitPoint = top.kind === 269 /* SyntaxKind.ImportDeclaration */ + ? (_c = getPotentiallyInvalidImportSpecifier((_b = top.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings)) !== null && _c !== void 0 ? _c : top.moduleSpecifier + : top.moduleReference; + var withoutModuleSpecifier = { + pos: top.getFirstToken().getStart(), + end: potentialSplitPoint.pos, + }; + // The module specifier/reference was previously found to be missing, empty, or + // not a string literal - in this last case, it's likely that statement on a following + // line was parsed as the module specifier of a partially-typed import, e.g. + // import Foo| + // interface Blah {} + // This appears to be a multiline-import, and editors can't replace multiple lines. + // But if everything but the "module specifier" is on one line, by this point we can + // assume that the "module specifier" is actually just another statement, and return + // the single-line range of the import excluding that probable statement. + if (ts.rangeIsOnSingleLine(withoutModuleSpecifier, sourceFile)) { + return ts.createTextSpanFromRange(withoutModuleSpecifier); + } + } + // Tries to identify the first named import that is not really a named import, but rather + // just parser recovery for a situation like: + // import { Foo| + // interface Bar {} + // in which `Foo`, `interface`, and `Bar` are all parsed as import specifiers. The caller + // will also check if this token is on a separate line from the rest of the import. + function getPotentiallyInvalidImportSpecifier(namedBindings) { + var _a; + return ts.find((_a = ts.tryCast(namedBindings, ts.isNamedImports)) === null || _a === void 0 ? void 0 : _a.elements, function (e) { + var _a; + return !e.propertyName && + ts.isStringANonContextualKeyword(e.name.text) && + ((_a = ts.findPrecedingToken(e.name.pos, namedBindings.getSourceFile(), namedBindings)) === null || _a === void 0 ? void 0 : _a.kind) !== 27 /* SyntaxKind.CommaToken */; + }); + } function couldBeTypeOnlyImportSpecifier(importSpecifier, contextToken) { return ts.isImportSpecifier(importSpecifier) && (importSpecifier.isTypeOnly || contextToken === importSpecifier.name && ts.isTypeKeywordTokenOrIdentifier(contextToken)); } function canCompleteFromNamedBindings(namedBindings) { - return isModuleSpecifierMissingOrEmpty(namedBindings.parent.parent.moduleSpecifier) - && (ts.isNamespaceImport(namedBindings) || namedBindings.elements.length < 2) - && !namedBindings.parent.name; + if (!isModuleSpecifierMissingOrEmpty(namedBindings.parent.parent.moduleSpecifier) || namedBindings.parent.name) { + return false; + } + if (ts.isNamedImports(namedBindings)) { + // We can only complete on named imports if there are no other named imports already, + // but parser recovery sometimes puts later statements in the named imports list, so + // we try to only consider the probably-valid ones. + var invalidNamedImport = getPotentiallyInvalidImportSpecifier(namedBindings); + var validImports = invalidNamedImport ? namedBindings.elements.indexOf(invalidNamedImport) : namedBindings.elements.length; + return validImports < 2; + } + return true; } function isModuleSpecifierMissingOrEmpty(specifier) { var _a; @@ -138053,7 +139331,6 @@ var ts; function isArrowFunctionBody(node) { return node.parent && ts.isArrowFunction(node.parent) && node.parent.body === node; } - ; /** True if symbol is a type or a module containing at least one type. */ function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules) { if (seenModules === void 0) { seenModules = new ts.Map(); } @@ -138202,14 +139479,14 @@ var ts; case 115 /* SyntaxKind.WhileKeyword */: case 90 /* SyntaxKind.DoKeyword */: return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); - case 134 /* SyntaxKind.ConstructorKeyword */: - return getFromAllDeclarations(ts.isConstructorDeclaration, [134 /* SyntaxKind.ConstructorKeyword */]); - case 136 /* SyntaxKind.GetKeyword */: - case 149 /* SyntaxKind.SetKeyword */: - return getFromAllDeclarations(ts.isAccessor, [136 /* SyntaxKind.GetKeyword */, 149 /* SyntaxKind.SetKeyword */]); - case 132 /* SyntaxKind.AwaitKeyword */: + case 135 /* SyntaxKind.ConstructorKeyword */: + return getFromAllDeclarations(ts.isConstructorDeclaration, [135 /* SyntaxKind.ConstructorKeyword */]); + case 137 /* SyntaxKind.GetKeyword */: + case 151 /* SyntaxKind.SetKeyword */: + return getFromAllDeclarations(ts.isAccessor, [137 /* SyntaxKind.GetKeyword */, 151 /* SyntaxKind.SetKeyword */]); + case 133 /* SyntaxKind.AwaitKeyword */: return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); - case 131 /* SyntaxKind.AsyncKeyword */: + case 132 /* SyntaxKind.AsyncKeyword */: return highlightSpans(getAsyncAndAwaitOccurrences(node)); case 125 /* SyntaxKind.YieldKeyword */: return highlightSpans(getYieldOccurrences(node)); @@ -138256,7 +139533,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 305 /* SyntaxKind.SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 308 /* SyntaxKind.SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -138288,16 +139565,16 @@ var ts; function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 249 /* SyntaxKind.SwitchStatement */: - if (statement.kind === 245 /* SyntaxKind.ContinueStatement */) { + case 252 /* SyntaxKind.SwitchStatement */: + if (statement.kind === 248 /* SyntaxKind.ContinueStatement */) { return false; } // falls through - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 240 /* SyntaxKind.DoStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 243 /* SyntaxKind.DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. @@ -138313,26 +139590,26 @@ var ts; // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 262 /* SyntaxKind.ModuleBlock */: - case 305 /* SyntaxKind.SourceFile */: - case 235 /* SyntaxKind.Block */: - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: + case 265 /* SyntaxKind.ModuleBlock */: + case 308 /* SyntaxKind.SourceFile */: + case 238 /* SyntaxKind.Block */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration - if (modifierFlag & 128 /* ModifierFlags.Abstract */ && ts.isClassDeclaration(declaration)) { + if (modifierFlag & 256 /* ModifierFlags.Abstract */ && ts.isClassDeclaration(declaration)) { return __spreadArray(__spreadArray([], declaration.members, true), [declaration], false); } else { return container.statements; } - case 171 /* SyntaxKind.Constructor */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return __spreadArray(__spreadArray([], container.parameters, true), (ts.isClassLike(container.parent) ? container.parent.members : []), true); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 182 /* SyntaxKind.TypeLiteral */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 184 /* SyntaxKind.TypeLiteral */: var nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -138342,12 +139619,12 @@ var ts; return __spreadArray(__spreadArray([], nodes, true), constructor.parameters, true); } } - else if (modifierFlag & 128 /* ModifierFlags.Abstract */) { + else if (modifierFlag & 256 /* ModifierFlags.Abstract */) { return __spreadArray(__spreadArray([], nodes, true), [container], false); } return nodes; // Syntactically invalid positions that the parser might produce anyway - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return undefined; default: ts.Debug.assertNever(container, "Invalid container kind."); @@ -138368,7 +139645,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 97 /* SyntaxKind.ForKeyword */, 115 /* SyntaxKind.WhileKeyword */, 90 /* SyntaxKind.DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 240 /* SyntaxKind.DoStatement */) { + if (loopNode.kind === 243 /* SyntaxKind.DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 115 /* SyntaxKind.WhileKeyword */)) { @@ -138388,13 +139665,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 249 /* SyntaxKind.SwitchStatement */: + case 252 /* SyntaxKind.SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -138467,13 +139744,13 @@ var ts; var keywords = []; if (func.modifiers) { func.modifiers.forEach(function (modifier) { - pushKeywordIf(keywords, modifier, 131 /* SyntaxKind.AsyncKeyword */); + pushKeywordIf(keywords, modifier, 132 /* SyntaxKind.AsyncKeyword */); }); } ts.forEachChild(func, function (child) { traverseWithoutCrossingFunction(child, function (node) { if (ts.isAwaitExpression(node)) { - pushKeywordIf(keywords, node.getFirstToken(), 132 /* SyntaxKind.AwaitKeyword */); + pushKeywordIf(keywords, node.getFirstToken(), 133 /* SyntaxKind.AwaitKeyword */); } }); }); @@ -138857,14 +140134,14 @@ var ts; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: if (ts.isImportCall(direct)) { handleImportCall(direct); break; } if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportKind.ExportEquals */ && parent.kind === 254 /* SyntaxKind.VariableDeclaration */) { + if (exportKind === 2 /* ExportKind.ExportEquals */ && parent.kind === 257 /* SyntaxKind.VariableDeclaration */) { var name = parent.name; if (name.kind === 79 /* SyntaxKind.Identifier */) { directImports.push(name); @@ -138875,25 +140152,25 @@ var ts; break; case 79 /* SyntaxKind.Identifier */: // for 'const x = require("y"); break; // TODO: GH#23879 - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasSyntacticModifier(direct, 1 /* ModifierFlags.Export */), /*alreadyAddedDirect*/ false); break; - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { + if (namedBindings && namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); } - else if (direct.exportClause.kind === 274 /* SyntaxKind.NamespaceExport */) { + else if (direct.exportClause.kind === 277 /* SyntaxKind.NamespaceExport */) { // `export * as foo from "foo"` add to indirect uses addIndirectUser(getSourceFileLikeForImportDeclaration(direct), /** addTransitiveDependencies */ true); } @@ -138902,9 +140179,9 @@ var ts; directImports.push(direct); } break; - case 200 /* SyntaxKind.ImportType */: + case 202 /* SyntaxKind.ImportType */: // Only check for typeof import('xyz') - if (direct.isTypeOf && !direct.qualifier && isExported(direct)) { + if (!isAvailableThroughGlobal && direct.isTypeOf && !direct.qualifier && isExported(direct)) { addIndirectUser(direct.getSourceFile(), /** addTransitiveDependencies */ true); } directImports.push(direct); @@ -138935,7 +140212,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 305 /* SyntaxKind.SourceFile */ || sourceFileLike.kind === 261 /* SyntaxKind.ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 308 /* SyntaxKind.SourceFile */ || sourceFileLike.kind === 264 /* SyntaxKind.ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUser(sourceFileLike, /** addTransitiveDependencies */ true); } @@ -138991,7 +140268,7 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { + if (decl.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } @@ -139001,7 +140278,7 @@ var ts; handleNamespaceImportLike(decl); return; } - if (decl.kind === 200 /* SyntaxKind.ImportType */) { + if (decl.kind === 202 /* SyntaxKind.ImportType */) { if (decl.qualifier) { var firstIdentifier = ts.getFirstIdentifier(decl.qualifier); if (firstIdentifier.escapedText === ts.symbolName(exportSymbol)) { @@ -139017,7 +140294,7 @@ var ts; if (decl.moduleSpecifier.kind !== 10 /* SyntaxKind.StringLiteral */) { return; } - if (decl.kind === 272 /* SyntaxKind.ExportDeclaration */) { + if (decl.kind === 275 /* SyntaxKind.ExportDeclaration */) { if (decl.exportClause && ts.isNamedExports(decl.exportClause)) { searchForNamedImport(decl.exportClause); } @@ -139026,10 +140303,10 @@ var ts; var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 268 /* SyntaxKind.NamespaceImport */: + case 271 /* SyntaxKind.NamespaceImport */: handleNamespaceImportLike(namedBindings.name); break; - case 269 /* SyntaxKind.NamedImports */: + case 272 /* SyntaxKind.NamedImports */: // 'default' might be accessed as a named import `{ default as foo }`. if (exportKind === 0 /* ExportKind.Named */ || exportKind === 1 /* ExportKind.Default */) { searchForNamedImport(namedBindings); @@ -139079,7 +140356,7 @@ var ts; } } else { - var localSymbol = element.kind === 275 /* SyntaxKind.ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 278 /* SyntaxKind.ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -139108,7 +140385,7 @@ var ts; for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { var referencingFile = sourceFiles_1[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if ((searchSourceFile === null || searchSourceFile === void 0 ? void 0 : searchSourceFile.kind) === 305 /* SyntaxKind.SourceFile */) { + if ((searchSourceFile === null || searchSourceFile === void 0 ? void 0 : searchSourceFile.kind) === 308 /* SyntaxKind.SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -139156,7 +140433,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 305 /* SyntaxKind.SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 308 /* SyntaxKind.SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -139171,15 +140448,15 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 272 /* SyntaxKind.ExportDeclaration */: - case 266 /* SyntaxKind.ImportDeclaration */: { + case 275 /* SyntaxKind.ExportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 265 /* SyntaxKind.ImportEqualsDeclaration */: { + case 268 /* SyntaxKind.ImportEqualsDeclaration */: { var decl = statement; if (isExternalModuleImportEquals(decl)) { action(decl, decl.moduleReference.expression); @@ -139204,7 +140481,7 @@ var ts; var parent = node.parent; var grandparent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + if (parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandparent) @@ -139288,6 +140565,8 @@ var ts; // Similarly, skip past the symbol for 'export =' if (importedSymbol.escapedName === "export=") { importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); + if (importedSymbol === undefined) + return undefined; } // If the import has a different name than the export, do not continue searching. // If `importedName` is undefined, do continue searching as the export is anonymous. @@ -139303,25 +140582,25 @@ var ts; } // Not meant for use with export specifiers or export assignment. function getExportKindForDeclaration(node) { - return ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */) ? 1 /* ExportKind.Default */ : 0 /* ExportKind.Named */; + return ts.hasSyntacticModifier(node, 1024 /* ModifierFlags.Default */) ? 1 /* ExportKind.Default */ : 0 /* ExportKind.Named */; } } FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol; function getExportEqualsLocalSymbol(importedSymbol, checker) { if (importedSymbol.flags & 2097152 /* SymbolFlags.Alias */) { - return ts.Debug.checkDefined(checker.getImmediateAliasedSymbol(importedSymbol)); + return checker.getImmediateAliasedSymbol(importedSymbol); } var decl = ts.Debug.checkDefined(importedSymbol.valueDeclaration); if (ts.isExportAssignment(decl)) { // `export = class {}` - return ts.Debug.checkDefined(decl.expression.symbol); + return decl.expression.symbol; } else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` - return ts.Debug.checkDefined(decl.right.symbol); + return decl.right.symbol; } else if (ts.isSourceFile(decl)) { // json module - return ts.Debug.checkDefined(decl.symbol); + return decl.symbol; } - return ts.Debug.fail(); + return undefined; } // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. @@ -139338,16 +140617,16 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent); - case 270 /* SyntaxKind.ImportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. return !parent.propertyName; - case 267 /* SyntaxKind.ImportClause */: - case 268 /* SyntaxKind.NamespaceImport */: + case 270 /* SyntaxKind.ImportClause */: + case 271 /* SyntaxKind.NamespaceImport */: ts.Debug.assert(parent.name === node); return true; - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: return ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(parent.parent.parent); default: return false; @@ -139388,21 +140667,21 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 208 /* SyntaxKind.CallExpression */) { + if (node.kind === 210 /* SyntaxKind.CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 305 /* SyntaxKind.SourceFile */) { + if (parent.kind === 308 /* SyntaxKind.SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 262 /* SyntaxKind.ModuleBlock */); + ts.Debug.assert(parent.kind === 265 /* SyntaxKind.ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 261 /* SyntaxKind.ModuleDeclaration */ && node.name.kind === 10 /* SyntaxKind.StringLiteral */; + return node.kind === 264 /* SyntaxKind.ModuleDeclaration */ && node.name.kind === 10 /* SyntaxKind.StringLiteral */; } function isExternalModuleImportEquals(eq) { - return eq.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* SyntaxKind.StringLiteral */; + return eq.moduleReference.kind === 280 /* SyntaxKind.ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* SyntaxKind.StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -139496,7 +140775,7 @@ var ts; ((ts.isImportOrExportSpecifier(node.parent) || ts.isBindingElement(node.parent)) && node.parent.propertyName === node) || // Is default export - (node.kind === 88 /* SyntaxKind.DefaultKeyword */ && ts.hasSyntacticModifier(node.parent, 513 /* ModifierFlags.ExportDefault */))) { + (node.kind === 88 /* SyntaxKind.DefaultKeyword */ && ts.hasSyntacticModifier(node.parent, 1025 /* ModifierFlags.ExportDefault */))) { return getContextNode(node.parent); } return undefined; @@ -139505,7 +140784,7 @@ var ts; if (!node) return undefined; switch (node.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return !ts.isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ? node : ts.isVariableStatement(node.parent.parent) ? @@ -139513,28 +140792,28 @@ var ts; ts.isForInOrOfStatement(node.parent.parent) ? getContextNode(node.parent.parent) : node.parent; - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: return getContextNode(node.parent.parent); - case 270 /* SyntaxKind.ImportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: return node.parent.parent.parent; - case 275 /* SyntaxKind.ExportSpecifier */: - case 268 /* SyntaxKind.NamespaceImport */: + case 278 /* SyntaxKind.ExportSpecifier */: + case 271 /* SyntaxKind.NamespaceImport */: return node.parent.parent; - case 267 /* SyntaxKind.ImportClause */: - case 274 /* SyntaxKind.NamespaceExport */: + case 270 /* SyntaxKind.ImportClause */: + case 277 /* SyntaxKind.NamespaceExport */: return node.parent; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return ts.isExpressionStatement(node.parent) ? node.parent : node; - case 244 /* SyntaxKind.ForOfStatement */: - case 243 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 246 /* SyntaxKind.ForInStatement */: return { start: node.initializer, end: node.expression }; - case 296 /* SyntaxKind.PropertyAssignment */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode(ts.findAncestor(node.parent, function (node) { return ts.isBinaryExpression(node) || ts.isForInOrOfStatement(node); @@ -139595,15 +140874,15 @@ var ts; return node.kind === 88 /* SyntaxKind.DefaultKeyword */ || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node) - || (node.kind === 134 /* SyntaxKind.ConstructorKeyword */ && ts.isConstructorDeclaration(node.parent)); + || (node.kind === 135 /* SyntaxKind.ConstructorKeyword */ && ts.isConstructorDeclaration(node.parent)); } function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); var referenceEntries; var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); - if (node.parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */ - || node.parent.kind === 203 /* SyntaxKind.BindingElement */ - || node.parent.kind === 207 /* SyntaxKind.ElementAccessExpression */ + if (node.parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */ + || node.parent.kind === 205 /* SyntaxKind.BindingElement */ + || node.parent.kind === 209 /* SyntaxKind.ElementAccessExpression */ || node.kind === 106 /* SyntaxKind.SuperKeyword */) { referenceEntries = entries && __spreadArray([], entries, true); } @@ -139627,13 +140906,13 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 305 /* SyntaxKind.SourceFile */) { + if (node.kind === 308 /* SyntaxKind.SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */) { + if (node.parent.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */) { var result_2 = []; Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_2.push(nodeEntry(node)); }); return result_2; @@ -139809,13 +141088,13 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { + else if (node.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) { return { kind: "interface" /* ScriptElementKind.interfaceElement */, displayParts: [ts.punctuationPart(20 /* SyntaxKind.OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* SyntaxKind.CloseParenToken */)] }; } - else if (node.kind === 226 /* SyntaxKind.ClassExpression */) { + else if (node.kind === 228 /* SyntaxKind.ClassExpression */) { return { kind: "local class" /* ScriptElementKind.localClassElement */, displayParts: [ts.punctuationPart(20 /* SyntaxKind.OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* SyntaxKind.CloseParenToken */)] @@ -139869,7 +141148,7 @@ var ts; var source = ts.getDeclarationFromName(node) || (node.kind === 88 /* SyntaxKind.DefaultKeyword */ ? node.parent : ts.isLiteralComputedPropertyDeclarationName(node) ? node.parent.parent - : node.kind === 134 /* SyntaxKind.ConstructorKeyword */ && ts.isConstructorDeclaration(node.parent) ? node.parent.parent + : node.kind === 135 /* SyntaxKind.ConstructorKeyword */ && ts.isConstructorDeclaration(node.parent) ? node.parent.parent : undefined); var commonjsSource = source && ts.isBinaryExpression(source) ? source.left : undefined; return !!(source && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === source || d === commonjsSource; }))); @@ -139884,47 +141163,47 @@ var ts; if (!!(decl.flags & 16777216 /* NodeFlags.Ambient */)) return true; switch (decl.kind) { - case 221 /* SyntaxKind.BinaryExpression */: - case 203 /* SyntaxKind.BindingElement */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 223 /* SyntaxKind.BinaryExpression */: + case 205 /* SyntaxKind.BindingElement */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: case 88 /* SyntaxKind.DefaultKeyword */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 299 /* SyntaxKind.EnumMember */: - case 275 /* SyntaxKind.ExportSpecifier */: - case 267 /* SyntaxKind.ImportClause */: // default import - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 285 /* SyntaxKind.JsxAttribute */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 264 /* SyntaxKind.NamespaceExportDeclaration */: - case 268 /* SyntaxKind.NamespaceImport */: - case 274 /* SyntaxKind.NamespaceExport */: - case 164 /* SyntaxKind.Parameter */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 163 /* SyntaxKind.TypeParameter */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 302 /* SyntaxKind.EnumMember */: + case 278 /* SyntaxKind.ExportSpecifier */: + case 270 /* SyntaxKind.ImportClause */: // default import + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 288 /* SyntaxKind.JsxAttribute */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 267 /* SyntaxKind.NamespaceExportDeclaration */: + case 271 /* SyntaxKind.NamespaceImport */: + case 277 /* SyntaxKind.NamespaceExport */: + case 166 /* SyntaxKind.Parameter */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 165 /* SyntaxKind.TypeParameter */: return true; - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 171 /* SyntaxKind.Constructor */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 173 /* SyntaxKind.Constructor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return !!decl.body; - case 254 /* SyntaxKind.VariableDeclaration */: - case 167 /* SyntaxKind.PropertyDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: return !!decl.initializer || ts.isCatchClause(decl.parent); - case 168 /* SyntaxKind.MethodSignature */: - case 166 /* SyntaxKind.PropertySignature */: - case 347 /* SyntaxKind.JSDocPropertyTag */: - case 340 /* SyntaxKind.JSDocParameterTag */: + case 170 /* SyntaxKind.MethodSignature */: + case 168 /* SyntaxKind.PropertySignature */: + case 350 /* SyntaxKind.JSDocPropertyTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: return false; default: return ts.Debug.failBadSyntaxKind(decl); @@ -140150,10 +141429,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { references.push(nodeEntry(decl.name)); } @@ -140182,9 +141461,9 @@ var ts; } /** As in a `readonly prop: any` or `constructor(readonly prop: any)`, not a `readonly any[]`. */ function isReadonlyTypeOperator(node) { - return node.kind === 145 /* SyntaxKind.ReadonlyKeyword */ + return node.kind === 146 /* SyntaxKind.ReadonlyKeyword */ && ts.isTypeOperatorNode(node.parent) - && node.parent.operator === 145 /* SyntaxKind.ReadonlyKeyword */; + && node.parent.operator === 146 /* SyntaxKind.ReadonlyKeyword */; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -140195,12 +141474,12 @@ var ts; } // A modifier readonly (like on a property declaration) is not special; // a readonly type keyword (like `readonly string[]`) is. - if (node.kind === 145 /* SyntaxKind.ReadonlyKeyword */ && !isReadonlyTypeOperator(node)) { + if (node.kind === 146 /* SyntaxKind.ReadonlyKeyword */ && !isReadonlyTypeOperator(node)) { return undefined; } // Likewise, when we *are* looking for a special keyword, make sure we // *don’t* include readonly member modifiers. - return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken, node.kind === 145 /* SyntaxKind.ReadonlyKeyword */ ? isReadonlyTypeOperator : undefined); + return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken, node.kind === 146 /* SyntaxKind.ReadonlyKeyword */ ? isReadonlyTypeOperator : undefined); } if (ts.isImportMeta(node.parent) && node.parent.name === node) { return getAllReferencesForImportMeta(sourceFiles, cancellationToken); @@ -140267,8 +141546,8 @@ var ts; } function getSpecialSearchKind(node) { switch (node.kind) { - case 171 /* SyntaxKind.Constructor */: - case 134 /* SyntaxKind.ConstructorKeyword */: + case 173 /* SyntaxKind.Constructor */: + case 135 /* SyntaxKind.ConstructorKeyword */: return 1 /* SpecialSearchKind.Constructor */; case 79 /* SyntaxKind.Identifier */: if (ts.isClassLike(node.parent)) { @@ -140516,7 +141795,7 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 213 /* SyntaxKind.FunctionExpression */ || valueDeclaration.kind === 226 /* SyntaxKind.ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 215 /* SyntaxKind.FunctionExpression */ || valueDeclaration.kind === 228 /* SyntaxKind.ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -140526,7 +141805,7 @@ var ts; if (flags & (4 /* SymbolFlags.Property */ | 8192 /* SymbolFlags.Method */)) { var privateDeclaration = ts.find(declarations, function (d) { return ts.hasEffectiveModifier(d, 8 /* ModifierFlags.Private */) || ts.isPrivateIdentifierClassElementDeclaration(d); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 257 /* SyntaxKind.ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 260 /* SyntaxKind.ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; @@ -140555,7 +141834,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 305 /* SyntaxKind.SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 308 /* SyntaxKind.SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -140813,7 +142092,7 @@ var ts; } // Use the parent symbol if the location is commonjs require syntax on javascript files only. if (ts.isInJSFile(referenceLocation) - && referenceLocation.parent.kind === 203 /* SyntaxKind.BindingElement */ + && referenceLocation.parent.kind === 205 /* SyntaxKind.BindingElement */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent)) { referenceSymbol = referenceLocation.parent.symbol; // The parent will not have a symbol if it's an ObjectBindingPattern (when destructuring is used). In @@ -140920,7 +142199,7 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; // eslint-disable-line no-in-operator + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; // eslint-disable-line local/no-in-operator // if rename symbol from default export anonymous function, for example `export default function() {}`, we do not need to add reference if (state.options.use === 2 /* FindReferencesUse.Rename */ && referenceLocation.kind === 88 /* SyntaxKind.DefaultKeyword */) { return; @@ -140986,15 +142265,15 @@ var ts; if (constructorSymbol && constructorSymbol.declarations) { for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var ctrKeyword = ts.findChildOfKind(decl, 134 /* SyntaxKind.ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 171 /* SyntaxKind.Constructor */ && !!ctrKeyword); + var ctrKeyword = ts.findChildOfKind(decl, 135 /* SyntaxKind.ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 173 /* SyntaxKind.Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } } if (classSymbol.exports) { classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 169 /* SyntaxKind.MethodDeclaration */) { + if (decl && decl.kind === 171 /* SyntaxKind.MethodDeclaration */) { var body = decl.body; if (body) { forEachDescendantOfKind(body, 108 /* SyntaxKind.ThisKeyword */, function (thisKeyword) { @@ -141018,7 +142297,7 @@ var ts; } for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 171 /* SyntaxKind.Constructor */); + ts.Debug.assert(decl.kind === 173 /* SyntaxKind.Constructor */); var body = decl.body; if (body) { forEachDescendantOfKind(body, 106 /* SyntaxKind.SuperKeyword */, function (node) { @@ -141048,7 +142327,7 @@ var ts; if (refNode.kind !== 79 /* SyntaxKind.Identifier */) { return; } - if (refNode.parent.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -141068,7 +142347,7 @@ var ts; } else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { var body = typeHavingNode.body; - if (body.kind === 235 /* SyntaxKind.Block */) { + if (body.kind === 238 /* SyntaxKind.Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression) addIfImplementation(returnStatement.expression); @@ -141096,13 +142375,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 214 /* SyntaxKind.ArrowFunction */: - case 213 /* SyntaxKind.FunctionExpression */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 226 /* SyntaxKind.ClassExpression */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 228 /* SyntaxKind.ClassExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return true; default: return false; @@ -141155,13 +142434,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* ModifierFlags.Static */; switch (searchSpaceNode.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -141182,43 +142461,43 @@ var ts; return [{ definition: { type: 0 /* DefinitionKind.Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function isParameterName(node) { - return node.kind === 79 /* SyntaxKind.Identifier */ && node.parent.kind === 164 /* SyntaxKind.Parameter */ && node.parent.name === node; + return node.kind === 79 /* SyntaxKind.Identifier */ && node.parent.kind === 166 /* SyntaxKind.Parameter */ && node.parent.name === node; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* ModifierFlags.Static */; switch (searchSpaceNode.kind) { - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning object literals break; } // falls through - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return undefined; } // falls through - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. default: return undefined; } - var references = ts.flatMap(searchSpaceNode.kind === 305 /* SyntaxKind.SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + var references = ts.flatMap(searchSpaceNode.kind === 308 /* SyntaxKind.SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { if (!ts.isThis(node)) { @@ -141226,20 +142505,20 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 213 /* SyntaxKind.FunctionExpression */: - case 256 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: return searchSpaceNode.symbol === container.symbol; - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; - case 226 /* SyntaxKind.ClassExpression */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 228 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: // Make sure the container belongs to the same class/object literals // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && ts.isStatic(container) === !!staticFlag; - case 305 /* SyntaxKind.SourceFile */: - return container.kind === 305 /* SyntaxKind.SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); + case 308 /* SyntaxKind.SourceFile */: + return container.kind === 308 /* SyntaxKind.SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); } }); }).map(function (n) { return nodeEntry(n); }); @@ -141350,7 +142629,7 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* SymbolFlags.FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* SymbolFlags.Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* SymbolFlags.FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - var exportSpecifier = ts.getDeclarationOfKind(symbol, 275 /* SyntaxKind.ExportSpecifier */); + var exportSpecifier = ts.getDeclarationOfKind(symbol, 278 /* SyntaxKind.ExportSpecifier */); if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) { var localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (localSymbol) { @@ -141395,7 +142674,7 @@ var ts; }); } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = ts.getDeclarationOfKind(symbol, 203 /* SyntaxKind.BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 205 /* SyntaxKind.BindingElement */); if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) { return ts.getPropertySymbolFromBindingElement(checker, bindingElement); } @@ -141658,16 +142937,16 @@ var ts; return; } switch (node.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 169 /* SyntaxKind.MethodDeclaration */: - if (node.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: + if (node.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) { return (_a = ts.getAssignedName(node.parent)) === null || _a === void 0 ? void 0 : _a.getText(); } return (_b = ts.getNameOfDeclaration(node.parent)) === null || _b === void 0 ? void 0 : _b.getText(); - case 256 /* SyntaxKind.FunctionDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: if (ts.isModuleBlock(node.parent) && ts.isIdentifier(node.parent.parent.name)) { return node.parent.parent.name.getText(); } @@ -141882,61 +143161,65 @@ var ts; } switch (node.kind) { case 79 /* SyntaxKind.Identifier */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 266 /* SyntaxKind.ImportDeclaration */: - case 272 /* SyntaxKind.ExportDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: // do not descend into nodes that cannot contain callable nodes return; - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: recordCallSite(node); return; - case 211 /* SyntaxKind.TypeAssertionExpression */: - case 229 /* SyntaxKind.AsExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: + case 231 /* SyntaxKind.AsExpression */: // do not descend into the type side of an assertion collect(node.expression); return; - case 254 /* SyntaxKind.VariableDeclaration */: - case 164 /* SyntaxKind.Parameter */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 166 /* SyntaxKind.Parameter */: // do not descend into the type of a variable or parameter declaration collect(node.name); collect(node.initializer); return; - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: // do not descend into the type arguments of a call expression recordCallSite(node); collect(node.expression); ts.forEach(node.arguments, collect); return; - case 209 /* SyntaxKind.NewExpression */: + case 211 /* SyntaxKind.NewExpression */: // do not descend into the type arguments of a new expression recordCallSite(node); collect(node.expression); ts.forEach(node.arguments, collect); return; - case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: // do not descend into the type arguments of a tagged template expression recordCallSite(node); collect(node.tag); collect(node.template); return; - case 280 /* SyntaxKind.JsxOpeningElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: // do not descend into the type arguments of a JsxOpeningLikeElement recordCallSite(node); collect(node.tagName); collect(node.attributes); return; - case 165 /* SyntaxKind.Decorator */: + case 167 /* SyntaxKind.Decorator */: recordCallSite(node); collect(node.expression); return; - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: recordCallSite(node); ts.forEachChild(node, collect); break; + case 235 /* SyntaxKind.SatisfiesExpression */: + // do not descend into the type side of an assertion + collect(node.expression); + return; } if (ts.isPartOfTypeNode(node)) { // do not descend into types @@ -141991,25 +143274,25 @@ var ts; var callSites = []; var collect = createCallSiteCollector(program, callSites); switch (node.kind) { - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: collectCallSitesOfSourceFile(node, collect); break; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: collectCallSitesOfModuleDeclaration(node, collect); break; - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect); break; - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: collectCallSitesOfClassLikeDeclaration(node, collect); break; - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 172 /* SyntaxKind.ClassStaticBlockDeclaration */: collectCallSitesOfClassStaticBlockDeclaration(node, collect); break; default: @@ -142280,7 +143563,7 @@ var ts; } var parent = node.parent; var typeChecker = program.getTypeChecker(); - if (node.kind === 159 /* SyntaxKind.OverrideKeyword */ || (ts.isJSDocOverrideTag(node) && ts.rangeContainsPosition(node.tagName, position))) { + if (node.kind === 161 /* SyntaxKind.OverrideKeyword */ || (ts.isIdentifier(node) && ts.isJSDocOverrideTag(parent) && parent.tagName === node)) { return getDefinitionFromOverriddenMember(typeChecker, node) || ts.emptyArray; } // Labels @@ -142288,6 +143571,12 @@ var ts; var label = ts.getTargetLabel(node.parent, node.text); return label ? [createDefinitionInfoFromName(typeChecker, label, "label" /* ScriptElementKind.label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 } + if (node.kind === 105 /* SyntaxKind.ReturnKeyword */) { + var functionDeclaration = ts.findAncestor(node.parent, function (n) { + return ts.isClassStaticBlockDeclaration(n) ? "quit" : ts.isFunctionLikeDeclaration(n); + }); + return functionDeclaration ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : undefined; + } if (ts.isStaticModifier(node) && ts.isClassStaticBlockDeclaration(node.parent)) { var classDecl = node.parent.parent; var _c = getSymbol(classDecl, typeChecker, stopAtAlias), symbol_1 = _c.symbol, failedAliasResolution_1 = _c.failedAliasResolution; @@ -142356,7 +143645,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */) { + if (node.parent.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */) { var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); var definitions = (shorthandSymbol_1 === null || shorthandSymbol_1 === void 0 ? void 0 : shorthandSymbol_1.declarations) ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node, /*unverified*/ false, failedAliasResolution); }) : ts.emptyArray; return ts.concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node) || ts.emptyArray); @@ -142423,13 +143712,16 @@ var ts; if (!baseDeclaration) return; var baseTypeNode = ts.getEffectiveBaseTypeNode(baseDeclaration); - var baseType = baseTypeNode ? typeChecker.getTypeAtLocation(baseTypeNode) : undefined; - if (!baseType) + if (!baseTypeNode) + return; + var expression = ts.skipParentheses(baseTypeNode.expression); + var base = ts.isClassExpression(expression) ? expression.symbol : typeChecker.getSymbolAtLocation(expression); + if (!base) return; var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(classElement.name)); var symbol = ts.hasStaticModifier(classElement) - ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbolAtLocation(baseType.symbol, baseDeclaration), name) - : typeChecker.getPropertyOfType(baseType, name); + ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbol(base), name) + : typeChecker.getPropertyOfType(typeChecker.getDeclaredTypeOfSymbol(base), name); if (!symbol) return; return getDefinitionFromSymbol(typeChecker, symbol, node); @@ -142562,7 +143854,7 @@ var ts; if (node.parent === declaration) { return true; } - if (declaration.kind === 268 /* SyntaxKind.NamespaceImport */) { + if (declaration.kind === 271 /* SyntaxKind.NamespaceImport */) { return false; } return true; @@ -142604,7 +143896,7 @@ var ts; function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (symbol.flags & 32 /* SymbolFlags.Class */ && !(symbol.flags & (16 /* SymbolFlags.Function */ | 3 /* SymbolFlags.Variable */)) && (ts.isNewExpressionTarget(node) || node.kind === 134 /* SyntaxKind.ConstructorKeyword */)) { + if (symbol.flags & 32 /* SymbolFlags.Class */ && !(symbol.flags & (16 /* SymbolFlags.Function */ | 3 /* SymbolFlags.Variable */)) && (ts.isNewExpressionTarget(node) || node.kind === 135 /* SyntaxKind.ConstructorKeyword */)) { var cls = ts.find(filteredDeclarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } @@ -142656,22 +143948,22 @@ var ts; return isDefinitionVisible(checker, declaration.parent); // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent switch (declaration.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 169 /* SyntaxKind.MethodDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 171 /* SyntaxKind.MethodDeclaration */: // Private/protected properties/methods are not visible if (ts.hasEffectiveModifier(declaration, 8 /* ModifierFlags.Private */)) return false; // Public properties/methods are visible if its parents are visible, so: // falls through - case 171 /* SyntaxKind.Constructor */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 226 /* SyntaxKind.ClassExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 213 /* SyntaxKind.FunctionExpression */: + case 173 /* SyntaxKind.Constructor */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 228 /* SyntaxKind.ClassExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: return isDefinitionVisible(checker, declaration.parent); default: return false; @@ -142709,9 +144001,9 @@ var ts; } function isConstructorLike(node) { switch (node.kind) { - case 171 /* SyntaxKind.Constructor */: - case 180 /* SyntaxKind.ConstructorType */: - case 175 /* SyntaxKind.ConstructSignature */: + case 173 /* SyntaxKind.Constructor */: + case 182 /* SyntaxKind.ConstructorType */: + case 177 /* SyntaxKind.ConstructSignature */: return true; default: return false; @@ -142817,17 +144109,17 @@ var ts; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var jsdoc = _a[_i]; - var inheritDoc = ts.isJSDoc(jsdoc) && jsdoc.tags && ts.find(jsdoc.tags, function (t) { return t.kind === 327 /* SyntaxKind.JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc"); }); + var inheritDoc = ts.isJSDoc(jsdoc) && jsdoc.tags && ts.find(jsdoc.tags, function (t) { return t.kind === 330 /* SyntaxKind.JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc"); }); // skip comments containing @typedefs since they're not associated with particular declarations // Exceptions: // - @typedefs are themselves declarations with associated comments // - @param or @return indicate that the author thinks of it as a 'local' @typedef that's part of the function documentation if (jsdoc.comment === undefined && !inheritDoc || ts.isJSDoc(jsdoc) - && declaration.kind !== 345 /* SyntaxKind.JSDocTypedefTag */ && declaration.kind !== 338 /* SyntaxKind.JSDocCallbackTag */ + && declaration.kind !== 348 /* SyntaxKind.JSDocTypedefTag */ && declaration.kind !== 341 /* SyntaxKind.JSDocCallbackTag */ && jsdoc.tags - && jsdoc.tags.some(function (t) { return t.kind === 345 /* SyntaxKind.JSDocTypedefTag */ || t.kind === 338 /* SyntaxKind.JSDocCallbackTag */; }) - && !jsdoc.tags.some(function (t) { return t.kind === 340 /* SyntaxKind.JSDocParameterTag */ || t.kind === 341 /* SyntaxKind.JSDocReturnTag */; })) { + && jsdoc.tags.some(function (t) { return t.kind === 348 /* SyntaxKind.JSDocTypedefTag */ || t.kind === 341 /* SyntaxKind.JSDocCallbackTag */; }) + && !jsdoc.tags.some(function (t) { return t.kind === 343 /* SyntaxKind.JSDocParameterTag */ || t.kind === 344 /* SyntaxKind.JSDocReturnTag */; })) { continue; } var newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : []; @@ -142847,11 +144139,11 @@ var ts; } function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 340 /* SyntaxKind.JSDocParameterTag */: - case 347 /* SyntaxKind.JSDocPropertyTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: + case 350 /* SyntaxKind.JSDocPropertyTag */: return [declaration]; - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 345 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); @@ -142865,8 +144157,8 @@ var ts; // skip comments containing @typedefs since they're not associated with particular declarations // Exceptions: // - @param or @return indicate that the author thinks of it as a 'local' @typedef that's part of the function documentation - if (tags.some(function (t) { return t.kind === 345 /* SyntaxKind.JSDocTypedefTag */ || t.kind === 338 /* SyntaxKind.JSDocCallbackTag */; }) - && !tags.some(function (t) { return t.kind === 340 /* SyntaxKind.JSDocParameterTag */ || t.kind === 341 /* SyntaxKind.JSDocReturnTag */; })) { + if (tags.some(function (t) { return t.kind === 348 /* SyntaxKind.JSDocTypedefTag */ || t.kind === 341 /* SyntaxKind.JSDocCallbackTag */; }) + && !tags.some(function (t) { return t.kind === 343 /* SyntaxKind.JSDocParameterTag */ || t.kind === 344 /* SyntaxKind.JSDocReturnTag */; })) { return; } for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) { @@ -142881,17 +144173,17 @@ var ts; if (typeof comment === "string") { return [ts.textPart(comment)]; } - return ts.flatMap(comment, function (node) { return node.kind === 321 /* SyntaxKind.JSDocText */ ? [ts.textPart(node.text)] : ts.buildLinkParts(node, checker); }); + return ts.flatMap(comment, function (node) { return node.kind === 324 /* SyntaxKind.JSDocText */ ? [ts.textPart(node.text)] : ts.buildLinkParts(node, checker); }); } function getCommentDisplayParts(tag, checker) { var comment = tag.comment, kind = tag.kind; var namePart = getTagNameDisplayPart(kind); switch (kind) { - case 329 /* SyntaxKind.JSDocImplementsTag */: + case 332 /* SyntaxKind.JSDocImplementsTag */: return withNode(tag.class); - case 328 /* SyntaxKind.JSDocAugmentsTag */: + case 331 /* SyntaxKind.JSDocAugmentsTag */: return withNode(tag.class); - case 344 /* SyntaxKind.JSDocTemplateTag */: + case 347 /* SyntaxKind.JSDocTemplateTag */: var templateTag = tag; var displayParts_3 = []; if (templateTag.constraint) { @@ -142913,13 +144205,13 @@ var ts; displayParts_3.push.apply(displayParts_3, __spreadArray([ts.spacePart()], getDisplayPartsFromComment(comment, checker), true)); } return displayParts_3; - case 343 /* SyntaxKind.JSDocTypeTag */: + case 346 /* SyntaxKind.JSDocTypeTag */: return withNode(tag.typeExpression); - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 347 /* SyntaxKind.JSDocPropertyTag */: - case 340 /* SyntaxKind.JSDocParameterTag */: - case 346 /* SyntaxKind.JSDocSeeTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 350 /* SyntaxKind.JSDocPropertyTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: + case 349 /* SyntaxKind.JSDocSeeTag */: var name = tag.name; return name ? withNode(name) : comment === undefined ? undefined @@ -142946,14 +144238,14 @@ var ts; } function getTagNameDisplayPart(kind) { switch (kind) { - case 340 /* SyntaxKind.JSDocParameterTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: return ts.parameterNamePart; - case 347 /* SyntaxKind.JSDocPropertyTag */: + case 350 /* SyntaxKind.JSDocPropertyTag */: return ts.propertyNamePart; - case 344 /* SyntaxKind.JSDocTemplateTag */: + case 347 /* SyntaxKind.JSDocTemplateTag */: return ts.typeParameterNamePart; - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: return ts.typeAliasNamePart; default: return ts.textPart; @@ -143124,43 +144416,48 @@ var ts; } function getCommentOwnerInfoWorker(commentOwner, options) { switch (commentOwner.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 171 /* SyntaxKind.Constructor */: - case 168 /* SyntaxKind.MethodSignature */: - case 214 /* SyntaxKind.ArrowFunction */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 170 /* SyntaxKind.MethodSignature */: + case 216 /* SyntaxKind.ArrowFunction */: var host = commentOwner; return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) }; - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: return getCommentOwnerInfoWorker(commentOwner.initializer, options); - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 299 /* SyntaxKind.EnumMember */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 302 /* SyntaxKind.EnumMember */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return { commentOwner: commentOwner }; - case 237 /* SyntaxKind.VariableStatement */: { - var varStatement = commentOwner; - var varDeclarations = varStatement.declarationList.declarations; - var host_1 = varDeclarations.length === 1 && varDeclarations[0].initializer - ? getRightHandSideOfAssignment(varDeclarations[0].initializer) - : undefined; - return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } + case 168 /* SyntaxKind.PropertySignature */: { + var host_1 = commentOwner; + return host_1.type && ts.isFunctionTypeNode(host_1.type) + ? { commentOwner: commentOwner, parameters: host_1.type.parameters, hasReturn: hasReturn(host_1.type, options) } : { commentOwner: commentOwner }; } - case 305 /* SyntaxKind.SourceFile */: + case 240 /* SyntaxKind.VariableStatement */: { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + var host_2 = varDeclarations.length === 1 && varDeclarations[0].initializer + ? getRightHandSideOfAssignment(varDeclarations[0].initializer) + : undefined; + return host_2 + ? { commentOwner: commentOwner, parameters: host_2.parameters, hasReturn: hasReturn(host_2, options) } + : { commentOwner: commentOwner }; + } + case 308 /* SyntaxKind.SourceFile */: return "quit"; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - return commentOwner.parent.kind === 261 /* SyntaxKind.ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 238 /* SyntaxKind.ExpressionStatement */: + return commentOwner.parent.kind === 264 /* SyntaxKind.ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 241 /* SyntaxKind.ExpressionStatement */: return getCommentOwnerInfoWorker(commentOwner.expression, options); - case 221 /* SyntaxKind.BinaryExpression */: { + case 223 /* SyntaxKind.BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* AssignmentDeclarationKind.None */) { return "quit"; @@ -143169,7 +144466,7 @@ var ts; ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner: commentOwner }; } - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: var init = commentOwner.initializer; if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) { return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) }; @@ -143178,18 +144475,18 @@ var ts; } function hasReturn(node, options) { return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && - (ts.isArrowFunction(node) && ts.isExpression(node.body) + (ts.isFunctionTypeNode(node) || ts.isArrowFunction(node) && ts.isExpression(node.body) || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 212 /* SyntaxKind.ParenthesizedExpression */) { + while (rightHandSide.kind === 214 /* SyntaxKind.ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: return rightHandSide; - case 226 /* SyntaxKind.ClassExpression */: + case 228 /* SyntaxKind.ClassExpression */: return ts.find(rightHandSide.members, ts.isConstructorDeclaration); } } @@ -143248,9 +144545,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 267 /* SyntaxKind.ImportClause */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 270 /* SyntaxKind.ImportClause */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -143260,7 +144557,7 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - return !!name && (pushLiteral(name, containers) || name.kind === 162 /* SyntaxKind.ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + return !!name && (pushLiteral(name, containers) || name.kind === 164 /* SyntaxKind.ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // @@ -143277,7 +144574,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + if (name && name.kind === 164 /* SyntaxKind.ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } // Don't include the last portion. @@ -143494,7 +144791,7 @@ var ts; */ function hasNavigationBarName(node) { return !ts.hasDynamicName(node) || - (node.kind !== 221 /* SyntaxKind.BinaryExpression */ && + (node.kind !== 223 /* SyntaxKind.BinaryExpression */ && ts.isPropertyAccessExpression(node.name.expression) && ts.isIdentifier(node.name.expression.expression) && ts.idText(node.name.expression.expression) === "Symbol"); @@ -143507,7 +144804,7 @@ var ts; return; } switch (node.kind) { - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -143519,25 +144816,25 @@ var ts; } } break; - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 168 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 170 /* SyntaxKind.MethodSignature */: if (hasNavigationBarName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: if (hasNavigationBarName(node)) { addNodeWithRecursiveInitializer(node); } break; - case 166 /* SyntaxKind.PropertySignature */: + case 168 /* SyntaxKind.PropertySignature */: if (hasNavigationBarName(node)) { addLeafNode(node); } break; - case 267 /* SyntaxKind.ImportClause */: + case 270 /* SyntaxKind.ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -143549,7 +144846,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { + if (namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -143560,17 +144857,17 @@ var ts; } } break; - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: addNodeWithRecursiveChild(node, node.name); break; - case 298 /* SyntaxKind.SpreadAssignment */: + case 301 /* SyntaxKind.SpreadAssignment */: var expression = node.expression; // Use the expression as the name of the SpreadAssignment, otherwise show as . ts.isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node); break; - case 203 /* SyntaxKind.BindingElement */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 254 /* SyntaxKind.VariableDeclaration */: { + case 205 /* SyntaxKind.BindingElement */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 257 /* SyntaxKind.VariableDeclaration */: { var child = node; if (ts.isBindingPattern(child.name)) { addChildrenRecursively(child.name); @@ -143580,7 +144877,7 @@ var ts; } break; } - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: var nameNode = node.name; // If we see a function declaration track as a possible ES5 class if (nameNode && ts.isIdentifier(nameNode)) { @@ -143588,11 +144885,11 @@ var ts; } addNodeWithRecursiveChild(node, node.body); break; - case 214 /* SyntaxKind.ArrowFunction */: - case 213 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -143602,9 +144899,9 @@ var ts; } endNode(); break; - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -143612,10 +144909,10 @@ var ts; } endNode(); break; - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 271 /* SyntaxKind.ExportAssignment */: { + case 274 /* SyntaxKind.ExportAssignment */: { var expression_1 = node.expression; var child = ts.isObjectLiteralExpression(expression_1) || ts.isCallExpression(expression_1) ? expression_1 : ts.isArrowFunction(expression_1) || ts.isFunctionExpression(expression_1) ? expression_1.body : undefined; @@ -143629,16 +144926,16 @@ var ts; } break; } - case 275 /* SyntaxKind.ExportSpecifier */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 176 /* SyntaxKind.IndexSignature */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 278 /* SyntaxKind.ExportSpecifier */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 178 /* SyntaxKind.IndexSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: addLeafNode(node); break; - case 208 /* SyntaxKind.CallExpression */: - case 221 /* SyntaxKind.BinaryExpression */: { + case 210 /* SyntaxKind.CallExpression */: + case 223 /* SyntaxKind.BinaryExpression */: { var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* AssignmentDeclarationKind.ExportsProperty */: @@ -143878,12 +145175,12 @@ var ts; return false; } switch (a.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return ts.isStatic(a) === ts.isStatic(b); - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return areSameModule(a, b) && getFullyQualifiedModuleName(a) === getFullyQualifiedModuleName(b); default: @@ -143905,7 +145202,7 @@ var ts; if (!a.body || !b.body) { return a.body === b.body; } - return a.body.kind === b.body.kind && (a.body.kind !== 261 /* SyntaxKind.ModuleDeclaration */ || areSameModule(a.body, b.body)); + return a.body.kind === b.body.kind && (a.body.kind !== 264 /* SyntaxKind.ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { @@ -143935,7 +145232,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 261 /* SyntaxKind.ModuleDeclaration */) { + if (node.kind === 264 /* SyntaxKind.ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -143944,16 +145241,16 @@ var ts; return propertyName && ts.unescapeLeadingUnderscores(propertyName); } switch (node.kind) { - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 226 /* SyntaxKind.ClassExpression */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 228 /* SyntaxKind.ClassExpression */: return getFunctionOrClassName(node); default: return undefined; } } function getItemName(node, name) { - if (node.kind === 261 /* SyntaxKind.ModuleDeclaration */) { + if (node.kind === 264 /* SyntaxKind.ModuleDeclaration */) { return cleanText(getModuleName(node)); } if (name) { @@ -143965,32 +145262,32 @@ var ts; } } switch (node.kind) { - case 305 /* SyntaxKind.SourceFile */: + case 308 /* SyntaxKind.SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"".concat(ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))), "\"") : ""; - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: return ts.isExportAssignment(node) && node.isExportEquals ? "export=" /* InternalSymbolName.ExportEquals */ : "default" /* InternalSymbolName.Default */; - case 214 /* SyntaxKind.ArrowFunction */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - if (ts.getSyntacticModifierFlags(node) & 512 /* ModifierFlags.Default */) { + case 216 /* SyntaxKind.ArrowFunction */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + if (ts.getSyntacticModifierFlags(node) & 1024 /* ModifierFlags.Default */) { return "default"; } // We may get a string with newlines or other whitespace in the case of an object dereference // (eg: "app\n.onactivated"), so we should remove the whitespace for readability in the // navigation bar. return getFunctionOrClassName(node); - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return "constructor"; - case 175 /* SyntaxKind.ConstructSignature */: + case 177 /* SyntaxKind.ConstructSignature */: return "new()"; - case 174 /* SyntaxKind.CallSignature */: + case 176 /* SyntaxKind.CallSignature */: return "()"; - case 176 /* SyntaxKind.IndexSignature */: + case 178 /* SyntaxKind.IndexSignature */: return "[]"; default: return ""; @@ -144023,19 +145320,19 @@ var ts; } // Some nodes are otherwise important enough to always include in the primary navigation menu. switch (navigationBarNodeKind(item)) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 305 /* SyntaxKind.SourceFile */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 308 /* SyntaxKind.SourceFile */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: return true; - case 214 /* SyntaxKind.ArrowFunction */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -144045,10 +145342,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 262 /* SyntaxKind.ModuleBlock */: - case 305 /* SyntaxKind.SourceFile */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 171 /* SyntaxKind.Constructor */: + case 265 /* SyntaxKind.ModuleBlock */: + case 308 /* SyntaxKind.SourceFile */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 173 /* SyntaxKind.Constructor */: return true; default: return false; @@ -144110,7 +145407,7 @@ var ts; function getFullyQualifiedModuleName(moduleDeclaration) { // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = [ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)]; - while (moduleDeclaration.body && moduleDeclaration.body.kind === 261 /* SyntaxKind.ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 264 /* SyntaxKind.ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -144124,13 +145421,13 @@ var ts; return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 162 /* SyntaxKind.ComputedPropertyName */; + return !member.name || member.name.kind === 164 /* SyntaxKind.ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 305 /* SyntaxKind.SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 308 /* SyntaxKind.SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 254 /* SyntaxKind.VariableDeclaration */) { + if (node.parent && node.parent.kind === 257 /* SyntaxKind.VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); @@ -144153,7 +145450,7 @@ var ts; return nodeText(parent.name); } // Default exports are named "default" - else if (ts.getSyntacticModifierFlags(node) & 512 /* ModifierFlags.Default */) { + else if (ts.getSyntacticModifierFlags(node) & 1024 /* ModifierFlags.Default */) { return "default"; } else if (ts.isClassLike(node)) { @@ -144188,9 +145485,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 214 /* SyntaxKind.ArrowFunction */: - case 213 /* SyntaxKind.FunctionExpression */: - case 226 /* SyntaxKind.ClassExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: + case 228 /* SyntaxKind.ClassExpression */: return true; default: return false; @@ -144219,23 +145516,39 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { + function organizeImports(sourceFile, formatContext, host, program, preferences, mode) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var shouldSort = mode === "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ || mode === "All" /* OrganizeImportsMode.All */; + var shouldCombine = shouldSort; // These are currently inseparable, but I draw a distinction for clarity and in case we add modes in the future. + var shouldRemove = mode === "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */ || mode === "All" /* OrganizeImportsMode.All */; + var maybeRemove = shouldRemove ? removeUnusedImports : ts.identity; + var maybeCoalesce = shouldCombine ? coalesceImports : ts.identity; + var processImportsOfSameModuleSpecifier = function (importGroup) { + var processedDeclarations = maybeCoalesce(maybeRemove(importGroup, sourceFile, program)); + return shouldSort + ? ts.stableSort(processedDeclarations, function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }) + : processedDeclarations; + }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, sourceFile.statements.filter(ts.isImportDeclaration)); - topLevelImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, coalesceAndOrganizeImports); }); - // All of the old ExportDeclarations in the file, in syntactic order. - var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); - organizeImportsWorker(topLevelExportDecls, coalesceExports); + topLevelImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier); }); + // Exports are always used + if (mode !== "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */) { + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); + } for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; if (!ambientModule.body) continue; var ambientModuleImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, ambientModule.body.statements.filter(ts.isImportDeclaration)); - ambientModuleImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, coalesceAndOrganizeImports); }); - var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); - organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + ambientModuleImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier); }); + // Exports are always used + if (mode !== "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */) { + var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + } } return changeTracker.getChanges(); function organizeImportsWorker(oldImportDecls, coalesce) { @@ -144248,8 +145561,12 @@ var ts; // Consider: we could do a more careful check that this trivia is actually a header, // but the consequences of being wrong are very minor. ts.suppressLeadingTrivia(oldImportDecls[0]); - var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); - var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var oldImportGroups = shouldCombine + ? ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }) + : [oldImportDecls]; + var sortedImportGroups = shouldSort + ? ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }) + : oldImportGroups; var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { return getExternalModuleName(importGroup[0].moduleSpecifier) ? coalesce(importGroup) @@ -144313,11 +145630,7 @@ var ts; } return false; } - function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { - // As a precaution, consider unused import detection to be destructive (GH #43051) - if (skipDestructiveCodeActions) { - return oldImports; - } + function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); @@ -144591,11 +145904,11 @@ var ts; function getModuleSpecifierExpression(declaration) { var _a; switch (declaration.kind) { - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return (_a = ts.tryCast(declaration.moduleReference, ts.isExternalModuleReference)) === null || _a === void 0 ? void 0 : _a.expression; - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return declaration.moduleSpecifier; - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return declaration.declarationList.declarations[0].initializer.arguments[0]; } } @@ -144634,19 +145947,19 @@ var ts; function getImportKindOrder(s1) { var _a; switch (s1.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: if (!s1.importClause) return 0; if (s1.importClause.isTypeOnly) return 1; - if (((_a = s1.importClause.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 268 /* SyntaxKind.NamespaceImport */) + if (((_a = s1.importClause.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 271 /* SyntaxKind.NamespaceImport */) return 2; if (s1.importClause.name) return 3; return 4; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return 5; - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return 6; } } @@ -144835,7 +146148,7 @@ var ts; } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: if (ts.isFunctionLike(n.parent)) { return functionSpan(n.parent, n, sourceFile); } @@ -144843,16 +146156,16 @@ var ts; // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. switch (n.parent.kind) { - case 240 /* SyntaxKind.DoStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 242 /* SyntaxKind.ForStatement */: - case 239 /* SyntaxKind.IfStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 248 /* SyntaxKind.WithStatement */: - case 292 /* SyntaxKind.CatchClause */: + case 243 /* SyntaxKind.DoStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 242 /* SyntaxKind.IfStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 251 /* SyntaxKind.WithStatement */: + case 295 /* SyntaxKind.CatchClause */: return spanForNode(n.parent); - case 252 /* SyntaxKind.TryStatement */: + case 255 /* SyntaxKind.TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { @@ -144869,42 +146182,42 @@ var ts; // the span of the block, independent of any parent span. return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* OutliningSpanKind.Code */); } - case 262 /* SyntaxKind.ModuleBlock */: + case 265 /* SyntaxKind.ModuleBlock */: return spanForNode(n.parent); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 263 /* SyntaxKind.CaseBlock */: - case 182 /* SyntaxKind.TypeLiteral */: - case 201 /* SyntaxKind.ObjectBindingPattern */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 266 /* SyntaxKind.CaseBlock */: + case 184 /* SyntaxKind.TypeLiteral */: + case 203 /* SyntaxKind.ObjectBindingPattern */: return spanForNode(n); - case 184 /* SyntaxKind.TupleType */: + case 186 /* SyntaxKind.TupleType */: return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isTupleTypeNode(n.parent), 22 /* SyntaxKind.OpenBracketToken */); - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: return spanForNodeArray(n.statements); - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return spanForObjectOrArrayLiteral(n, 22 /* SyntaxKind.OpenBracketToken */); - case 278 /* SyntaxKind.JsxElement */: + case 281 /* SyntaxKind.JsxElement */: return spanForJSXElement(n); - case 282 /* SyntaxKind.JsxFragment */: + case 285 /* SyntaxKind.JsxFragment */: return spanForJSXFragment(n); - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 280 /* SyntaxKind.JsxOpeningElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: return spanForJSXAttributes(n.attributes); - case 223 /* SyntaxKind.TemplateExpression */: + case 225 /* SyntaxKind.TemplateExpression */: case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: return spanForTemplateLiteral(n); - case 202 /* SyntaxKind.ArrayBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isBindingElement(n.parent), 22 /* SyntaxKind.OpenBracketToken */); - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return spanForArrowFunction(n); - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: return spanForCallExpression(n); - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return spanForParenthesizedExpression(n); } function spanForCallExpression(node) { @@ -144977,7 +146290,7 @@ var ts; function functionSpan(node, body, sourceFile) { var openToken = tryGetFunctionOpenToken(node, body, sourceFile); var closeToken = ts.findChildOfKind(body, 19 /* SyntaxKind.CloseBraceToken */, sourceFile); - return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 214 /* SyntaxKind.ArrowFunction */); + return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 216 /* SyntaxKind.ArrowFunction */); } function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart) { if (autoCollapse === void 0) { autoCollapse = false; } @@ -145173,7 +146486,7 @@ var ts; return bestMatch; } function betterMatch(a, b) { - return ts.min(a, b, compareMatches); + return ts.min([a, b], compareMatches); } function compareMatches(a, b) { return a === undefined ? 1 /* Comparison.GreaterThan */ : b === undefined ? -1 /* Comparison.LessThan */ @@ -145521,10 +146834,10 @@ var ts; */ function tryConsumeDeclare() { var token = ts.scanner.getToken(); - if (token === 135 /* SyntaxKind.DeclareKeyword */) { + if (token === 136 /* SyntaxKind.DeclareKeyword */) { // declare module "mod" token = nextToken(); - if (token === 141 /* SyntaxKind.ModuleKeyword */) { + if (token === 142 /* SyntaxKind.ModuleKeyword */) { token = nextToken(); if (token === 10 /* SyntaxKind.StringLiteral */) { recordAmbientExternalModule(); @@ -145558,10 +146871,10 @@ var ts; return true; } else { - if (token === 152 /* SyntaxKind.TypeKeyword */) { + if (token === 154 /* SyntaxKind.TypeKeyword */) { var skipTypeKeyword = ts.scanner.lookAhead(function () { var token = ts.scanner.scan(); - return token !== 156 /* SyntaxKind.FromKeyword */ && (token === 41 /* SyntaxKind.AsteriskToken */ || + return token !== 158 /* SyntaxKind.FromKeyword */ && (token === 41 /* SyntaxKind.AsteriskToken */ || token === 18 /* SyntaxKind.OpenBraceToken */ || token === 79 /* SyntaxKind.Identifier */ || ts.isKeyword(token)); @@ -145572,7 +146885,7 @@ var ts; } if (token === 79 /* SyntaxKind.Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 156 /* SyntaxKind.FromKeyword */) { + if (token === 158 /* SyntaxKind.FromKeyword */) { token = nextToken(); if (token === 10 /* SyntaxKind.StringLiteral */) { // import d from "mod"; @@ -145603,7 +146916,7 @@ var ts; } if (token === 19 /* SyntaxKind.CloseBraceToken */) { token = nextToken(); - if (token === 156 /* SyntaxKind.FromKeyword */) { + if (token === 158 /* SyntaxKind.FromKeyword */) { token = nextToken(); if (token === 10 /* SyntaxKind.StringLiteral */) { // import {a as A} from "mod"; @@ -145615,11 +146928,11 @@ var ts; } else if (token === 41 /* SyntaxKind.AsteriskToken */) { token = nextToken(); - if (token === 127 /* SyntaxKind.AsKeyword */) { + if (token === 128 /* SyntaxKind.AsKeyword */) { token = nextToken(); if (token === 79 /* SyntaxKind.Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 156 /* SyntaxKind.FromKeyword */) { + if (token === 158 /* SyntaxKind.FromKeyword */) { token = nextToken(); if (token === 10 /* SyntaxKind.StringLiteral */) { // import * as NS from "mod" @@ -145640,7 +146953,7 @@ var ts; if (token === 93 /* SyntaxKind.ExportKeyword */) { markAsExternalModuleIfTopLevel(); token = nextToken(); - if (token === 152 /* SyntaxKind.TypeKeyword */) { + if (token === 154 /* SyntaxKind.TypeKeyword */) { var skipTypeKeyword = ts.scanner.lookAhead(function () { var token = ts.scanner.scan(); return token === 41 /* SyntaxKind.AsteriskToken */ || @@ -145659,7 +146972,7 @@ var ts; } if (token === 19 /* SyntaxKind.CloseBraceToken */) { token = nextToken(); - if (token === 156 /* SyntaxKind.FromKeyword */) { + if (token === 158 /* SyntaxKind.FromKeyword */) { token = nextToken(); if (token === 10 /* SyntaxKind.StringLiteral */) { // export {a as A} from "mod"; @@ -145671,7 +146984,7 @@ var ts; } else if (token === 41 /* SyntaxKind.AsteriskToken */) { token = nextToken(); - if (token === 156 /* SyntaxKind.FromKeyword */) { + if (token === 158 /* SyntaxKind.FromKeyword */) { token = nextToken(); if (token === 10 /* SyntaxKind.StringLiteral */) { // export * from "mod" @@ -145681,7 +146994,7 @@ var ts; } else if (token === 100 /* SyntaxKind.ImportKeyword */) { token = nextToken(); - if (token === 152 /* SyntaxKind.TypeKeyword */) { + if (token === 154 /* SyntaxKind.TypeKeyword */) { var skipTypeKeyword = ts.scanner.lookAhead(function () { var token = ts.scanner.scan(); return token === 79 /* SyntaxKind.Identifier */ || @@ -145707,7 +147020,7 @@ var ts; function tryConsumeRequireCall(skipCurrentToken, allowTemplateLiterals) { if (allowTemplateLiterals === void 0) { allowTemplateLiterals = false; } var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); - if (token === 146 /* SyntaxKind.RequireKeyword */) { + if (token === 147 /* SyntaxKind.RequireKeyword */) { token = nextToken(); if (token === 20 /* SyntaxKind.OpenParenToken */) { token = nextToken(); @@ -145782,8 +147095,8 @@ var ts; } if (ts.scanner.getToken() === 15 /* SyntaxKind.TemplateHead */) { var stack = [ts.scanner.getToken()]; - var token = ts.scanner.scan(); loop: while (ts.length(stack)) { + var token = ts.scanner.scan(); switch (token) { case 1 /* SyntaxKind.EndOfFileToken */: break loop; @@ -145811,7 +147124,6 @@ var ts; } break; } - token = ts.scanner.scan(); } nextToken(); } @@ -145919,7 +147231,7 @@ var ts; return getRenameInfoError(wouldRenameNodeModules); } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 164 /* SyntaxKind.ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); @@ -146064,6 +147376,10 @@ var ts; pushSelectionCommentRange(comment.pos, comment.end); } if (positionShouldSnapToNode(sourceFile, pos, node)) { + if (ts.isFunctionBody(node) + && ts.isFunctionLikeDeclaration(parentNode) && !ts.positionsAreOnSameLine(node.getStart(sourceFile), node.getEnd(), sourceFile)) { + pushSelectionRange(node.getStart(sourceFile), node.getEnd()); + } // 1. Blocks are effectively redundant with SyntaxLists. // 2. TemplateSpans, along with the SyntaxLists containing them, are a somewhat unintuitive grouping // of things that should be considered independently. @@ -146201,14 +147517,14 @@ var ts; ts.Debug.assertEqual(closeBraceToken.kind, 19 /* SyntaxKind.CloseBraceToken */); // Group `-/+readonly` and `-/+?` var groupedWithPlusMinusTokens = groupChildren(children, function (child) { - return child === node.readonlyToken || child.kind === 145 /* SyntaxKind.ReadonlyKeyword */ || + return child === node.readonlyToken || child.kind === 146 /* SyntaxKind.ReadonlyKeyword */ || child === node.questionToken || child.kind === 57 /* SyntaxKind.QuestionToken */; }); // Group type parameter with surrounding brackets var groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, function (_a) { var kind = _a.kind; return kind === 22 /* SyntaxKind.OpenBracketToken */ || - kind === 163 /* SyntaxKind.TypeParameter */ || + kind === 165 /* SyntaxKind.TypeParameter */ || kind === 23 /* SyntaxKind.CloseBracketToken */; }); return [ @@ -146226,7 +147542,7 @@ var ts; var children = groupChildren(node.getChildren(), function (child) { return child === node.name || ts.contains(node.modifiers, child); }); - var firstJSDocChild = ((_a = children[0]) === null || _a === void 0 ? void 0 : _a.kind) === 320 /* SyntaxKind.JSDoc */ ? children[0] : undefined; + var firstJSDocChild = ((_a = children[0]) === null || _a === void 0 ? void 0 : _a.kind) === 323 /* SyntaxKind.JSDoc */ ? children[0] : undefined; var withJSDocSeparated = firstJSDocChild ? children.slice(1) : children; var splittedChildren = splitChildren(withJSDocSeparated, function (_a) { var kind = _a.kind; @@ -146325,22 +147641,22 @@ var ts; return kind === 18 /* SyntaxKind.OpenBraceToken */ || kind === 22 /* SyntaxKind.OpenBracketToken */ || kind === 20 /* SyntaxKind.OpenParenToken */ - || kind === 280 /* SyntaxKind.JsxOpeningElement */; + || kind === 283 /* SyntaxKind.JsxOpeningElement */; } function isListCloser(token) { var kind = token && token.kind; return kind === 19 /* SyntaxKind.CloseBraceToken */ || kind === 23 /* SyntaxKind.CloseBracketToken */ || kind === 21 /* SyntaxKind.CloseParenToken */ - || kind === 281 /* SyntaxKind.JsxClosingElement */; + || kind === 284 /* SyntaxKind.JsxClosingElement */; } function getEndPos(sourceFile, node) { switch (node.kind) { - case 340 /* SyntaxKind.JSDocParameterTag */: - case 338 /* SyntaxKind.JSDocCallbackTag */: - case 347 /* SyntaxKind.JSDocPropertyTag */: - case 345 /* SyntaxKind.JSDocTypedefTag */: - case 342 /* SyntaxKind.JSDocThisTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 350 /* SyntaxKind.JSDocPropertyTag */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 345 /* SyntaxKind.JSDocThisTag */: return sourceFile.getLineEndOfPosition(node.getStart()); default: return node.getEnd(); @@ -146550,10 +147866,10 @@ var ts; } return undefined; } - else if (ts.isTemplateHead(node) && parent.parent.kind === 210 /* SyntaxKind.TaggedTemplateExpression */) { + else if (ts.isTemplateHead(node) && parent.parent.kind === 212 /* SyntaxKind.TaggedTemplateExpression */) { var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 223 /* SyntaxKind.TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 225 /* SyntaxKind.TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } @@ -146625,17 +147941,17 @@ var ts; return undefined; var parent = startingToken.parent; switch (parent.kind) { - case 212 /* SyntaxKind.ParenthesizedExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 214 /* SyntaxKind.ParenthesizedExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: var info = getArgumentOrParameterListInfo(startingToken, position, sourceFile); if (!info) return undefined; var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; - case 221 /* SyntaxKind.BinaryExpression */: { + case 223 /* SyntaxKind.BinaryExpression */: { var highestBinary = getHighestBinary(parent); var contextualType_1 = checker.getContextualType(highestBinary); var argumentIndex_1 = startingToken.kind === 20 /* SyntaxKind.OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; @@ -146706,11 +148022,11 @@ var ts; // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // - /* eslint-disable no-double-space */ + /* eslint-disable local/no-double-space */ // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 - /* eslint-enable no-double-space */ + /* eslint-enable local/no-double-space */ ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (ts.isTemplateLiteralToken(node)) { if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { @@ -146759,7 +148075,7 @@ var ts; // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 223 /* SyntaxKind.TemplateExpression */) { + if (template.kind === 225 /* SyntaxKind.TemplateExpression */) { var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -146964,14 +148280,14 @@ var ts; return; } switch (node.kind) { - case 261 /* SyntaxKind.ModuleDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 213 /* SyntaxKind.FunctionExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 214 /* SyntaxKind.ArrowFunction */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 215 /* SyntaxKind.FunctionExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 216 /* SyntaxKind.ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } if (!ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { @@ -147115,7 +148431,7 @@ var ts; } function isHintableLiteral(node) { switch (node.kind) { - case 219 /* SyntaxKind.PrefixUnaryExpression */: { + case 221 /* SyntaxKind.PrefixUnaryExpression */: { var operand = node.operand; return ts.isLiteralExpression(operand) || ts.isIdentifier(operand) && ts.isInfinityOrNaNString(operand.escapedText); } @@ -147123,7 +148439,7 @@ var ts; case 95 /* SyntaxKind.FalseKeyword */: case 104 /* SyntaxKind.NullKeyword */: case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: - case 223 /* SyntaxKind.TemplateExpression */: + case 225 /* SyntaxKind.TemplateExpression */: return true; case 79 /* SyntaxKind.Identifier */: { var name = node.escapedText; @@ -147444,11 +148760,11 @@ var ts; function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return statement.declarationList.declarations.some(function (decl) { return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); }); - case 238 /* SyntaxKind.ExpressionStatement */: { + case 241 /* SyntaxKind.ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); @@ -147465,12 +148781,12 @@ var ts; } function importNameForConvertToDefaultImport(node) { switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return node.name; default: return undefined; @@ -147546,20 +148862,20 @@ var ts; // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts function isFixablePromiseArgument(arg, checker) { switch (arg.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: var functionFlags = ts.getFunctionFlags(arg); if (functionFlags & 1 /* FunctionFlags.Generator */) { return false; } // falls through - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); // falls through case 104 /* SyntaxKind.NullKeyword */: return true; case 79 /* SyntaxKind.Identifier */: - case 206 /* SyntaxKind.PropertyAccessExpression */: { + case 208 /* SyntaxKind.PropertyAccessExpression */: { var symbol = checker.getSymbolAtLocation(arg); if (!symbol) { return false; @@ -147576,24 +148892,24 @@ var ts; } function canBeConvertedToClass(node, checker) { var _a, _b, _c, _d; - if (node.kind === 213 /* SyntaxKind.FunctionExpression */) { + if (node.kind === 215 /* SyntaxKind.FunctionExpression */) { if (ts.isVariableDeclaration(node.parent) && ((_a = node.symbol.members) === null || _a === void 0 ? void 0 : _a.size)) { return true; } var symbol = checker.getSymbolOfExpando(node, /*allowDeclaration*/ false); return !!(symbol && (((_b = symbol.exports) === null || _b === void 0 ? void 0 : _b.size) || ((_c = symbol.members) === null || _c === void 0 ? void 0 : _c.size))); } - if (node.kind === 256 /* SyntaxKind.FunctionDeclaration */) { + if (node.kind === 259 /* SyntaxKind.FunctionDeclaration */) { return !!((_d = node.symbol.members) === null || _d === void 0 ? void 0 : _d.size); } return false; } function canBeConvertedToAsync(node) { switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: return true; default: return false; @@ -147615,7 +148931,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* SymbolFlags.Class */) { - return ts.getDeclarationOfKind(symbol, 226 /* SyntaxKind.ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 228 /* SyntaxKind.ClassExpression */) ? "local class" /* ScriptElementKind.localClassElement */ : "class" /* ScriptElementKind.classElement */; } if (flags & 384 /* SymbolFlags.Enum */) @@ -147678,6 +148994,8 @@ var ts; return "method" /* ScriptElementKind.memberFunctionElement */; if (flags & 16384 /* SymbolFlags.Constructor */) return "constructor" /* ScriptElementKind.constructorImplementationElement */; + if (flags & 131072 /* SymbolFlags.Signature */) + return "index" /* ScriptElementKind.indexSignatureElement */; if (flags & 4 /* SymbolFlags.Property */) { if (flags & 33554432 /* SymbolFlags.Transient */ && symbol.checkFlags & 6 /* CheckFlags.Synthetic */) { // If union property is result of union of non method (property/accessors/variables), it is labeled as property @@ -147761,12 +149079,15 @@ var ts; var declaration = ts.find(symbol.declarations, function (declaration) { return declaration.name === location; }); if (declaration) { switch (declaration.kind) { - case 172 /* SyntaxKind.GetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: symbolKind = "getter" /* ScriptElementKind.memberGetAccessorElement */; break; - case 173 /* SyntaxKind.SetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: symbolKind = "setter" /* ScriptElementKind.memberSetAccessorElement */; break; + case 169 /* SyntaxKind.PropertyDeclaration */: + symbolKind = "accessor" /* ScriptElementKind.memberAccessorVariableElement */; + break; default: ts.Debug.assertNever(declaration); } @@ -147777,7 +149098,7 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (location.parent && location.parent.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -147797,7 +149118,7 @@ var ts; } if (callExpressionLike) { signature = typeChecker.getResolvedSignature(callExpressionLike); // TODO: GH#18217 - var useConstructSignatures = callExpressionLike.kind === 209 /* SyntaxKind.NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 106 /* SyntaxKind.SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 211 /* SyntaxKind.NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 106 /* SyntaxKind.SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (signature && !ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain @@ -147861,29 +149182,29 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* SymbolFlags.Accessor */)) || // name of function declaration - (location.kind === 134 /* SyntaxKind.ConstructorKeyword */ && location.parent.kind === 171 /* SyntaxKind.Constructor */)) { // At constructor keyword of constructor declaration + (location.kind === 135 /* SyntaxKind.ConstructorKeyword */ && location.parent.kind === 173 /* SyntaxKind.Constructor */)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) { - return declaration === (location.kind === 134 /* SyntaxKind.ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); + return declaration === (location.kind === 135 /* SyntaxKind.ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 171 /* SyntaxKind.Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 173 /* SyntaxKind.Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 171 /* SyntaxKind.Constructor */) { + if (functionDeclaration_1.kind === 173 /* SyntaxKind.Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* ScriptElementKind.constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 174 /* SyntaxKind.CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 176 /* SyntaxKind.CallSignature */ && !(type.symbol.flags & 2048 /* SymbolFlags.TypeLiteral */ || type.symbol.flags & 4096 /* SymbolFlags.ObjectLiteral */) ? type.symbol : symbol, symbolKind); } if (signature) { @@ -147896,7 +149217,7 @@ var ts; } if (symbolFlags & 32 /* SymbolFlags.Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 226 /* SyntaxKind.ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 228 /* SyntaxKind.ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -147919,7 +149240,7 @@ var ts; } if ((symbolFlags & 524288 /* SymbolFlags.TypeAlias */) && (semanticMeaning & 2 /* SemanticMeaning.Type */)) { prefixNextMeaning(); - displayParts.push(ts.keywordPart(152 /* SyntaxKind.TypeKeyword */)); + displayParts.push(ts.keywordPart(154 /* SyntaxKind.TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); @@ -147940,9 +149261,9 @@ var ts; } if (symbolFlags & 1536 /* SymbolFlags.Module */ && !isThisExpression) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 261 /* SyntaxKind.ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 264 /* SyntaxKind.ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 79 /* SyntaxKind.Identifier */; - displayParts.push(ts.keywordPart(isNamespace ? 142 /* SyntaxKind.NamespaceKeyword */ : 141 /* SyntaxKind.ModuleKeyword */)); + displayParts.push(ts.keywordPart(isNamespace ? 143 /* SyntaxKind.NamespaceKeyword */ : 142 /* SyntaxKind.ModuleKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } @@ -147961,7 +149282,7 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 163 /* SyntaxKind.TypeParameter */); + var decl = ts.getDeclarationOfKind(symbol, 165 /* SyntaxKind.TypeParameter */); if (decl === undefined) return ts.Debug.fail(); var declaration = decl.parent; @@ -147969,21 +149290,21 @@ var ts; if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 - if (declaration.kind === 175 /* SyntaxKind.ConstructSignature */) { + if (declaration.kind === 177 /* SyntaxKind.ConstructSignature */) { displayParts.push(ts.keywordPart(103 /* SyntaxKind.NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 174 /* SyntaxKind.CallSignature */ && declaration.name) { + else if (declaration.kind !== 176 /* SyntaxKind.CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* TypeFormatFlags.WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 259 /* SyntaxKind.TypeAliasDeclaration */) { + else if (declaration.kind === 262 /* SyntaxKind.TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path addInPrefix(); - displayParts.push(ts.keywordPart(152 /* SyntaxKind.TypeKeyword */)); + displayParts.push(ts.keywordPart(154 /* SyntaxKind.TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(declaration.symbol); writeTypeParametersOfSymbol(declaration.symbol, sourceFile); @@ -147995,7 +149316,7 @@ var ts; symbolKind = "enum member" /* ScriptElementKind.enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]; - if ((declaration === null || declaration === void 0 ? void 0 : declaration.kind) === 299 /* SyntaxKind.EnumMember */) { + if ((declaration === null || declaration === void 0 ? void 0 : declaration.kind) === 302 /* SyntaxKind.EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -148031,17 +149352,17 @@ var ts; } if (symbol.declarations) { switch (symbol.declarations[0].kind) { - case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 267 /* SyntaxKind.NamespaceExportDeclaration */: displayParts.push(ts.keywordPart(93 /* SyntaxKind.ExportKeyword */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(142 /* SyntaxKind.NamespaceKeyword */)); + displayParts.push(ts.keywordPart(143 /* SyntaxKind.NamespaceKeyword */)); break; - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: displayParts.push(ts.keywordPart(93 /* SyntaxKind.ExportKeyword */)); displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 63 /* SyntaxKind.EqualsToken */ : 88 /* SyntaxKind.DefaultKeyword */)); break; - case 275 /* SyntaxKind.ExportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: displayParts.push(ts.keywordPart(93 /* SyntaxKind.ExportKeyword */)); break; default: @@ -148051,13 +149372,13 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { + if (declaration.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(63 /* SyntaxKind.EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(146 /* SyntaxKind.RequireKeyword */)); + displayParts.push(ts.keywordPart(147 /* SyntaxKind.RequireKeyword */)); displayParts.push(ts.punctuationPart(20 /* SyntaxKind.OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); displayParts.push(ts.punctuationPart(21 /* SyntaxKind.CloseParenToken */)); @@ -148087,16 +149408,18 @@ var ts; } // For properties, variables and local vars: show the type if (symbolKind === "property" /* ScriptElementKind.memberVariableElement */ || + symbolKind === "accessor" /* ScriptElementKind.memberAccessorVariableElement */ || symbolKind === "getter" /* ScriptElementKind.memberGetAccessorElement */ || symbolKind === "setter" /* ScriptElementKind.memberSetAccessorElement */ || symbolKind === "JSX attribute" /* ScriptElementKind.jsxAttribute */ || symbolFlags & 3 /* SymbolFlags.Variable */ || symbolKind === "local var" /* ScriptElementKind.localVariableElement */ || + symbolKind === "index" /* ScriptElementKind.indexSignatureElement */ || isThisExpression) { displayParts.push(ts.punctuationPart(58 /* SyntaxKind.ColonToken */)); displayParts.push(ts.spacePart()); // If the type is type parameter, format it specially - if (type.symbol && type.symbol.flags & 262144 /* SymbolFlags.TypeParameter */) { + if (type.symbol && type.symbol.flags & 262144 /* SymbolFlags.TypeParameter */ && symbolKind !== "index" /* ScriptElementKind.indexSignatureElement */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeNode(4 /* EmitHint.Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); @@ -148140,10 +149463,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && symbol.declarations && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 305 /* SyntaxKind.SourceFile */; })) { + if (symbol.parent && symbol.declarations && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 308 /* SyntaxKind.SourceFile */; })) { for (var _i = 0, _b = symbol.declarations; _i < _b.length; _i++) { var declaration = _b[_i]; - if (!declaration.parent || declaration.parent.kind !== 221 /* SyntaxKind.BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 223 /* SyntaxKind.BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -148204,10 +149527,34 @@ var ts; displayParts.push(ts.spacePart()); } function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + var indexInfos; if (alias && symbolToDisplay === symbol) { symbolToDisplay = alias; } - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* SymbolFormatFlags.WriteTypeParametersOrArguments */ | 2 /* SymbolFormatFlags.UseOnlyExternalAliasing */ | 4 /* SymbolFormatFlags.AllowAnyNodeKind */); + if (symbolKind === "index" /* ScriptElementKind.indexSignatureElement */) { + indexInfos = typeChecker.getIndexInfosOfIndexSymbol(symbolToDisplay); + } + var fullSymbolDisplayParts = []; + if (symbolToDisplay.flags & 131072 /* SymbolFlags.Signature */ && indexInfos) { + if (symbolToDisplay.parent) { + fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay.parent); + } + fullSymbolDisplayParts.push(ts.punctuationPart(22 /* SyntaxKind.OpenBracketToken */)); + //Needed to handle more than one type of index + indexInfos.forEach(function (info, i) { + //Needed to handle template literals + fullSymbolDisplayParts.push.apply(fullSymbolDisplayParts, ts.typeToDisplayParts(typeChecker, info.keyType)); + if (i !== indexInfos.length - 1) { + fullSymbolDisplayParts.push(ts.spacePart()); + fullSymbolDisplayParts.push(ts.punctuationPart(51 /* SyntaxKind.BarToken */)); + fullSymbolDisplayParts.push(ts.spacePart()); + } + }); + fullSymbolDisplayParts.push(ts.punctuationPart(23 /* SyntaxKind.CloseBracketToken */)); + } + else { + fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* SymbolFormatFlags.WriteTypeParametersOrArguments */ | 2 /* SymbolFormatFlags.UseOnlyExternalAliasing */ | 4 /* SymbolFormatFlags.AllowAnyNodeKind */); + } ts.addRange(displayParts, fullSymbolDisplayParts); if (symbol.flags & 16777216 /* SymbolFlags.Optional */) { displayParts.push(ts.punctuationPart(57 /* SyntaxKind.QuestionToken */)); @@ -148255,7 +149602,7 @@ var ts; tags = signature.getJsDocTags(); if (allSignatures.length > 1 && documentation.length === 0 && tags.length === 0) { documentation = allSignatures[0].getDocumentationComment(typeChecker); - tags = allSignatures[0].getJsDocTags(); + tags = allSignatures[0].getJsDocTags().filter(function (tag) { return tag.name !== "deprecated"; }); // should only include @deprecated JSDoc tag on the first overload (#49368) } } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -148273,16 +149620,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 213 /* SyntaxKind.FunctionExpression */) { + if (declaration.kind === 215 /* SyntaxKind.FunctionExpression */) { return true; } - if (declaration.kind !== 254 /* SyntaxKind.VariableDeclaration */ && declaration.kind !== 256 /* SyntaxKind.FunctionDeclaration */) { + if (declaration.kind !== 257 /* SyntaxKind.VariableDeclaration */ && declaration.kind !== 259 /* SyntaxKind.FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 305 /* SyntaxKind.SourceFile */ || parent.kind === 262 /* SyntaxKind.ModuleBlock */) { + if (parent.kind === 308 /* SyntaxKind.SourceFile */ || parent.kind === 265 /* SyntaxKind.ModuleBlock */) { return false; } } @@ -148587,10 +149934,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 285 /* SyntaxKind.JsxAttribute */: - case 280 /* SyntaxKind.JsxOpeningElement */: - case 281 /* SyntaxKind.JsxClosingElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 288 /* SyntaxKind.JsxAttribute */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 284 /* SyntaxKind.JsxClosingElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. return ts.isKeyword(node.kind) || node.kind === 79 /* SyntaxKind.Identifier */; } @@ -148598,7 +149945,7 @@ var ts; return false; } function shouldRescanJsxText(node) { - return ts.isJsxText(node); + return ts.isJsxText(node) || ts.isJsxElement(node) && (lastTokenInfo === null || lastTokenInfo === void 0 ? void 0 : lastTokenInfo.token.kind) === 11 /* SyntaxKind.JsxText */; } function shouldRescanSlashToken(container) { return container.kind === 13 /* SyntaxKind.RegularExpressionLiteral */; @@ -148783,7 +150130,7 @@ var ts; (function (formatting) { function getAllRules() { var allTokens = []; - for (var token = 0 /* SyntaxKind.FirstToken */; token <= 160 /* SyntaxKind.LastToken */; token++) { + for (var token = 0 /* SyntaxKind.FirstToken */; token <= 162 /* SyntaxKind.LastToken */; token++) { if (token !== 1 /* SyntaxKind.EndOfFileToken */) { allTokens.push(token); } @@ -148798,9 +150145,9 @@ var ts; var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens, true), [3 /* SyntaxKind.MultiLineCommentTrivia */], false)); var anyTokenIncludingEOF = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens, true), [1 /* SyntaxKind.EndOfFileToken */], false)); - var keywords = tokenRangeFromRange(81 /* SyntaxKind.FirstKeyword */, 160 /* SyntaxKind.LastKeyword */); + var keywords = tokenRangeFromRange(81 /* SyntaxKind.FirstKeyword */, 162 /* SyntaxKind.LastKeyword */); var binaryOperators = tokenRangeFromRange(29 /* SyntaxKind.FirstBinaryOperator */, 78 /* SyntaxKind.LastBinaryOperator */); - var binaryKeywordOperators = [101 /* SyntaxKind.InKeyword */, 102 /* SyntaxKind.InstanceOfKeyword */, 160 /* SyntaxKind.OfKeyword */, 127 /* SyntaxKind.AsKeyword */, 139 /* SyntaxKind.IsKeyword */]; + var binaryKeywordOperators = [101 /* SyntaxKind.InKeyword */, 102 /* SyntaxKind.InstanceOfKeyword */, 162 /* SyntaxKind.OfKeyword */, 128 /* SyntaxKind.AsKeyword */, 140 /* SyntaxKind.IsKeyword */]; var unaryPrefixOperators = [45 /* SyntaxKind.PlusPlusToken */, 46 /* SyntaxKind.MinusMinusToken */, 54 /* SyntaxKind.TildeToken */, 53 /* SyntaxKind.ExclamationToken */]; var unaryPrefixExpressions = [ 8 /* SyntaxKind.NumericLiteral */, 9 /* SyntaxKind.BigIntLiteral */, 79 /* SyntaxKind.Identifier */, 20 /* SyntaxKind.OpenParenToken */, @@ -148831,7 +150178,7 @@ var ts; rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* SyntaxKind.QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* RuleAction.InsertSpace */), // in other cases there should be no space between '?' and next token rule("NoSpaceAfterQuestionMark", 57 /* SyntaxKind.QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), - rule("NoSpaceBeforeDot", anyToken, [24 /* SyntaxKind.DotToken */, 28 /* SyntaxKind.QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), + rule("NoSpaceBeforeDot", anyToken, [24 /* SyntaxKind.DotToken */, 28 /* SyntaxKind.QuestionDotToken */], [isNonJsxSameLineTokenContext, isNotPropertyAccessOnIntegerLiteral], 16 /* RuleAction.DeleteSpace */), rule("NoSpaceAfterDot", [24 /* SyntaxKind.DotToken */, 28 /* SyntaxKind.QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), rule("NoSpaceBetweenImportParenInImportType", 100 /* SyntaxKind.ImportKeyword */, 20 /* SyntaxKind.OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* RuleAction.DeleteSpace */), // Special handling of unary operators. @@ -148874,11 +150221,11 @@ var ts; // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: // get x() {} // set x(val) {} - rule("SpaceAfterGetSetInMember", [136 /* SyntaxKind.GetKeyword */, 149 /* SyntaxKind.SetKeyword */], 79 /* SyntaxKind.Identifier */, [isFunctionDeclContext], 4 /* RuleAction.InsertSpace */), + rule("SpaceAfterGetSetInMember", [137 /* SyntaxKind.GetKeyword */, 151 /* SyntaxKind.SetKeyword */], 79 /* SyntaxKind.Identifier */, [isFunctionDeclContext], 4 /* RuleAction.InsertSpace */), rule("NoSpaceBetweenYieldKeywordAndStar", 125 /* SyntaxKind.YieldKeyword */, 41 /* SyntaxKind.AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 16 /* RuleAction.DeleteSpace */), rule("SpaceBetweenYieldOrYieldStarAndOperand", [125 /* SyntaxKind.YieldKeyword */, 41 /* SyntaxKind.AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 4 /* RuleAction.InsertSpace */), rule("NoSpaceBetweenReturnAndSemicolon", 105 /* SyntaxKind.ReturnKeyword */, 26 /* SyntaxKind.SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), - rule("SpaceAfterCertainKeywords", [113 /* SyntaxKind.VarKeyword */, 109 /* SyntaxKind.ThrowKeyword */, 103 /* SyntaxKind.NewKeyword */, 89 /* SyntaxKind.DeleteKeyword */, 105 /* SyntaxKind.ReturnKeyword */, 112 /* SyntaxKind.TypeOfKeyword */, 132 /* SyntaxKind.AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), + rule("SpaceAfterCertainKeywords", [113 /* SyntaxKind.VarKeyword */, 109 /* SyntaxKind.ThrowKeyword */, 103 /* SyntaxKind.NewKeyword */, 89 /* SyntaxKind.DeleteKeyword */, 105 /* SyntaxKind.ReturnKeyword */, 112 /* SyntaxKind.TypeOfKeyword */, 133 /* SyntaxKind.AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), rule("SpaceAfterLetConstInVariableDeclaration", [119 /* SyntaxKind.LetKeyword */, 85 /* SyntaxKind.ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 4 /* RuleAction.InsertSpace */), rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* SyntaxKind.OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 16 /* RuleAction.DeleteSpace */), // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. @@ -148886,8 +150233,8 @@ var ts; rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* RuleAction.InsertSpace */), rule("SpaceAfterVoidOperator", 114 /* SyntaxKind.VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* RuleAction.InsertSpace */), // Async-await - rule("SpaceBetweenAsyncAndOpenParen", 131 /* SyntaxKind.AsyncKeyword */, 20 /* SyntaxKind.OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), - rule("SpaceBetweenAsyncAndFunctionKeyword", 131 /* SyntaxKind.AsyncKeyword */, [98 /* SyntaxKind.FunctionKeyword */, 79 /* SyntaxKind.Identifier */], [isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), + rule("SpaceBetweenAsyncAndOpenParen", 132 /* SyntaxKind.AsyncKeyword */, 20 /* SyntaxKind.OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 132 /* SyntaxKind.AsyncKeyword */, [98 /* SyntaxKind.FunctionKeyword */, 79 /* SyntaxKind.Identifier */], [isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), // Template string rule("NoSpaceBetweenTagAndTemplateString", [79 /* SyntaxKind.Identifier */, 21 /* SyntaxKind.CloseParenToken */], [14 /* SyntaxKind.NoSubstitutionTemplateLiteral */, 15 /* SyntaxKind.TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), // JSX opening elements @@ -148898,34 +150245,35 @@ var ts; rule("NoSpaceAfterEqualInJsxAttribute", 63 /* SyntaxKind.EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), // TypeScript-specific rules // Use of module as a function call. e.g.: import m2 = module("m2"); - rule("NoSpaceAfterModuleImport", [141 /* SyntaxKind.ModuleKeyword */, 146 /* SyntaxKind.RequireKeyword */], 20 /* SyntaxKind.OpenParenToken */, [isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), + rule("NoSpaceAfterModuleImport", [142 /* SyntaxKind.ModuleKeyword */, 147 /* SyntaxKind.RequireKeyword */], 20 /* SyntaxKind.OpenParenToken */, [isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), // Add a space around certain TypeScript keywords rule("SpaceAfterCertainTypeScriptKeywords", [ 126 /* SyntaxKind.AbstractKeyword */, + 127 /* SyntaxKind.AccessorKeyword */, 84 /* SyntaxKind.ClassKeyword */, - 135 /* SyntaxKind.DeclareKeyword */, + 136 /* SyntaxKind.DeclareKeyword */, 88 /* SyntaxKind.DefaultKeyword */, 92 /* SyntaxKind.EnumKeyword */, 93 /* SyntaxKind.ExportKeyword */, 94 /* SyntaxKind.ExtendsKeyword */, - 136 /* SyntaxKind.GetKeyword */, + 137 /* SyntaxKind.GetKeyword */, 117 /* SyntaxKind.ImplementsKeyword */, 100 /* SyntaxKind.ImportKeyword */, 118 /* SyntaxKind.InterfaceKeyword */, - 141 /* SyntaxKind.ModuleKeyword */, - 142 /* SyntaxKind.NamespaceKeyword */, + 142 /* SyntaxKind.ModuleKeyword */, + 143 /* SyntaxKind.NamespaceKeyword */, 121 /* SyntaxKind.PrivateKeyword */, 123 /* SyntaxKind.PublicKeyword */, 122 /* SyntaxKind.ProtectedKeyword */, - 145 /* SyntaxKind.ReadonlyKeyword */, - 149 /* SyntaxKind.SetKeyword */, + 146 /* SyntaxKind.ReadonlyKeyword */, + 151 /* SyntaxKind.SetKeyword */, 124 /* SyntaxKind.StaticKeyword */, - 152 /* SyntaxKind.TypeKeyword */, - 156 /* SyntaxKind.FromKeyword */, - 140 /* SyntaxKind.KeyOfKeyword */, - 137 /* SyntaxKind.InferKeyword */, + 154 /* SyntaxKind.TypeKeyword */, + 158 /* SyntaxKind.FromKeyword */, + 141 /* SyntaxKind.KeyOfKeyword */, + 138 /* SyntaxKind.InferKeyword */, ], anyToken, [isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), - rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [94 /* SyntaxKind.ExtendsKeyword */, 117 /* SyntaxKind.ImplementsKeyword */, 156 /* SyntaxKind.FromKeyword */], [isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [94 /* SyntaxKind.ExtendsKeyword */, 117 /* SyntaxKind.ImplementsKeyword */, 158 /* SyntaxKind.FromKeyword */], [isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { rule("SpaceAfterModuleName", 10 /* SyntaxKind.StringLiteral */, 18 /* SyntaxKind.OpenBraceToken */, [isModuleDeclContext], 4 /* RuleAction.InsertSpace */), // Lambda expressions @@ -148956,8 +150304,8 @@ var ts; 123 /* SyntaxKind.PublicKeyword */, 121 /* SyntaxKind.PrivateKeyword */, 122 /* SyntaxKind.ProtectedKeyword */, - 136 /* SyntaxKind.GetKeyword */, - 149 /* SyntaxKind.SetKeyword */, + 137 /* SyntaxKind.GetKeyword */, + 151 /* SyntaxKind.SetKeyword */, 22 /* SyntaxKind.OpenBracketToken */, 41 /* SyntaxKind.AsteriskToken */, ], [isEndOfDecoratorContextOnSameLine], 4 /* RuleAction.InsertSpace */), @@ -148968,8 +150316,8 @@ var ts; // These rules are applied after high priority var userConfigurableRules = [ // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses - rule("SpaceAfterConstructor", 134 /* SyntaxKind.ConstructorKeyword */, 20 /* SyntaxKind.OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), - rule("NoSpaceAfterConstructor", 134 /* SyntaxKind.ConstructorKeyword */, 20 /* SyntaxKind.OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), + rule("SpaceAfterConstructor", 135 /* SyntaxKind.ConstructorKeyword */, 20 /* SyntaxKind.OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), + rule("NoSpaceAfterConstructor", 135 /* SyntaxKind.ConstructorKeyword */, 20 /* SyntaxKind.OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), rule("SpaceAfterComma", 27 /* SyntaxKind.CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket, isNextTokenNotCloseParen], 4 /* RuleAction.InsertSpace */), rule("NoSpaceAfterComma", 27 /* SyntaxKind.CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 16 /* RuleAction.DeleteSpace */), // Insert space after function keyword for anonymous functions @@ -149043,11 +150391,11 @@ var ts; rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* SyntaxKind.OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* RuleAction.InsertSpace */, 1 /* RuleFlags.CanDeleteNewLines */), rule("NoSpaceBeforeComma", anyToken, 27 /* SyntaxKind.CommaToken */, [isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), // No space before and after indexer `x[]` - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(131 /* SyntaxKind.AsyncKeyword */, 82 /* SyntaxKind.CaseKeyword */), 22 /* SyntaxKind.OpenBracketToken */, [isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(132 /* SyntaxKind.AsyncKeyword */, 82 /* SyntaxKind.CaseKeyword */), 22 /* SyntaxKind.OpenBracketToken */, [isNonJsxSameLineTokenContext], 16 /* RuleAction.DeleteSpace */), rule("NoSpaceAfterCloseBracket", 23 /* SyntaxKind.CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 16 /* RuleAction.DeleteSpace */), rule("SpaceAfterSemicolon", 26 /* SyntaxKind.SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), // Remove extra space between for and await - rule("SpaceBetweenForAndAwaitKeyword", 97 /* SyntaxKind.ForKeyword */, 132 /* SyntaxKind.AwaitKeyword */, [isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), + rule("SpaceBetweenForAndAwaitKeyword", 97 /* SyntaxKind.ForKeyword */, 133 /* SyntaxKind.AwaitKeyword */, [isNonJsxSameLineTokenContext], 4 /* RuleAction.InsertSpace */), // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] rule("SpaceBetweenStatements", [21 /* SyntaxKind.CloseParenToken */, 90 /* SyntaxKind.DoKeyword */, 91 /* SyntaxKind.ElseKeyword */, 82 /* SyntaxKind.CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 4 /* RuleAction.InsertSpace */), @@ -149096,69 +150444,70 @@ var ts; return function (context) { return context.options && context.options[optionName] === optionValue; }; } function isOptionEnabled(optionName) { - return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + return function (context) { return context.options && ts.hasProperty(context.options, optionName) && !!context.options[optionName]; }; } function isOptionDisabled(optionName) { - return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + return function (context) { return context.options && ts.hasProperty(context.options, optionName) && !context.options[optionName]; }; } function isOptionDisabledOrUndefined(optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + return function (context) { return !context.options || !ts.hasProperty(context.options, optionName) || !context.options[optionName]; }; } function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + return function (context) { return !context.options || !ts.hasProperty(context.options, optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; } function isOptionEnabledOrUndefined(optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + return function (context) { return !context.options || !ts.hasProperty(context.options, optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 242 /* SyntaxKind.ForStatement */; + return context.contextNode.kind === 245 /* SyntaxKind.ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return context.contextNode.operatorToken.kind !== 27 /* SyntaxKind.CommaToken */; - case 222 /* SyntaxKind.ConditionalExpression */: - case 189 /* SyntaxKind.ConditionalType */: - case 229 /* SyntaxKind.AsExpression */: - case 275 /* SyntaxKind.ExportSpecifier */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 177 /* SyntaxKind.TypePredicate */: - case 187 /* SyntaxKind.UnionType */: - case 188 /* SyntaxKind.IntersectionType */: + case 224 /* SyntaxKind.ConditionalExpression */: + case 191 /* SyntaxKind.ConditionalType */: + case 231 /* SyntaxKind.AsExpression */: + case 278 /* SyntaxKind.ExportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 179 /* SyntaxKind.TypePredicate */: + case 189 /* SyntaxKind.UnionType */: + case 190 /* SyntaxKind.IntersectionType */: + case 235 /* SyntaxKind.SatisfiesExpression */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: // equals in type X = ... // falls through - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: // equal in import a = module('a'); // falls through - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: // equal in export = 1 // falls through - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: // equal in let a = 0 // falls through - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: // equal in p = 0 // falls through - case 164 /* SyntaxKind.Parameter */: - case 299 /* SyntaxKind.EnumMember */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: + case 166 /* SyntaxKind.Parameter */: + case 302 /* SyntaxKind.EnumMember */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: return context.currentTokenSpan.kind === 63 /* SyntaxKind.EqualsToken */ || context.nextTokenSpan.kind === 63 /* SyntaxKind.EqualsToken */; // "in" keyword in for (let x in []) { } - case 243 /* SyntaxKind.ForInStatement */: + case 246 /* SyntaxKind.ForInStatement */: // "in" keyword in [P in keyof T]: T[P] // falls through - case 163 /* SyntaxKind.TypeParameter */: + case 165 /* SyntaxKind.TypeParameter */: return context.currentTokenSpan.kind === 101 /* SyntaxKind.InKeyword */ || context.nextTokenSpan.kind === 101 /* SyntaxKind.InKeyword */ || context.currentTokenSpan.kind === 63 /* SyntaxKind.EqualsToken */ || context.nextTokenSpan.kind === 63 /* SyntaxKind.EqualsToken */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 244 /* SyntaxKind.ForOfStatement */: - return context.currentTokenSpan.kind === 160 /* SyntaxKind.OfKeyword */ || context.nextTokenSpan.kind === 160 /* SyntaxKind.OfKeyword */; + case 247 /* SyntaxKind.ForOfStatement */: + return context.currentTokenSpan.kind === 162 /* SyntaxKind.OfKeyword */ || context.nextTokenSpan.kind === 162 /* SyntaxKind.OfKeyword */; } return false; } @@ -149170,22 +150519,22 @@ var ts; } function isTypeAnnotationContext(context) { var contextKind = context.contextNode.kind; - return contextKind === 167 /* SyntaxKind.PropertyDeclaration */ || - contextKind === 166 /* SyntaxKind.PropertySignature */ || - contextKind === 164 /* SyntaxKind.Parameter */ || - contextKind === 254 /* SyntaxKind.VariableDeclaration */ || + return contextKind === 169 /* SyntaxKind.PropertyDeclaration */ || + contextKind === 168 /* SyntaxKind.PropertySignature */ || + contextKind === 166 /* SyntaxKind.Parameter */ || + contextKind === 257 /* SyntaxKind.VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 222 /* SyntaxKind.ConditionalExpression */ || - context.contextNode.kind === 189 /* SyntaxKind.ConditionalType */; + return context.contextNode.kind === 224 /* SyntaxKind.ConditionalExpression */ || + context.contextNode.kind === 191 /* SyntaxKind.ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 201 /* SyntaxKind.ObjectBindingPattern */ || - context.contextNode.kind === 195 /* SyntaxKind.MappedType */ || + return context.contextNode.kind === 203 /* SyntaxKind.ObjectBindingPattern */ || + context.contextNode.kind === 197 /* SyntaxKind.MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -149211,34 +150560,34 @@ var ts; return true; } switch (node.kind) { - case 235 /* SyntaxKind.Block */: - case 263 /* SyntaxKind.CaseBlock */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 262 /* SyntaxKind.ModuleBlock */: + case 238 /* SyntaxKind.Block */: + case 266 /* SyntaxKind.CaseBlock */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 265 /* SyntaxKind.ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: // falls through - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: // case SyntaxKind.MethodSignature: // falls through - case 174 /* SyntaxKind.CallSignature */: - case 213 /* SyntaxKind.FunctionExpression */: - case 171 /* SyntaxKind.Constructor */: - case 214 /* SyntaxKind.ArrowFunction */: + case 176 /* SyntaxKind.CallSignature */: + case 215 /* SyntaxKind.FunctionExpression */: + case 173 /* SyntaxKind.Constructor */: + case 216 /* SyntaxKind.ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: // falls through - case 258 /* SyntaxKind.InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 261 /* SyntaxKind.InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -149247,40 +150596,40 @@ var ts; return !isFunctionDeclContext(context); } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 256 /* SyntaxKind.FunctionDeclaration */ || context.contextNode.kind === 213 /* SyntaxKind.FunctionExpression */; + return context.contextNode.kind === 259 /* SyntaxKind.FunctionDeclaration */ || context.contextNode.kind === 215 /* SyntaxKind.FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 182 /* SyntaxKind.TypeLiteral */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 272 /* SyntaxKind.ExportDeclaration */: - case 273 /* SyntaxKind.NamedExports */: - case 266 /* SyntaxKind.ImportDeclaration */: - case 269 /* SyntaxKind.NamedImports */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 184 /* SyntaxKind.TypeLiteral */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: + case 276 /* SyntaxKind.NamedExports */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 272 /* SyntaxKind.NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 292 /* SyntaxKind.CatchClause */: - case 262 /* SyntaxKind.ModuleBlock */: - case 249 /* SyntaxKind.SwitchStatement */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 295 /* SyntaxKind.CatchClause */: + case 265 /* SyntaxKind.ModuleBlock */: + case 252 /* SyntaxKind.SwitchStatement */: return true; - case 235 /* SyntaxKind.Block */: { + case 238 /* SyntaxKind.Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 214 /* SyntaxKind.ArrowFunction */ && blockParent.kind !== 213 /* SyntaxKind.FunctionExpression */) { + if (!blockParent || blockParent.kind !== 216 /* SyntaxKind.ArrowFunction */ && blockParent.kind !== 215 /* SyntaxKind.FunctionExpression */) { return true; } } @@ -149289,32 +150638,32 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 239 /* SyntaxKind.IfStatement */: - case 249 /* SyntaxKind.SwitchStatement */: - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 252 /* SyntaxKind.TryStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 248 /* SyntaxKind.WithStatement */: + case 242 /* SyntaxKind.IfStatement */: + case 252 /* SyntaxKind.SwitchStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 255 /* SyntaxKind.TryStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 251 /* SyntaxKind.WithStatement */: // TODO // case SyntaxKind.ElseClause: // falls through - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 205 /* SyntaxKind.ObjectLiteralExpression */; + return context.contextNode.kind === 207 /* SyntaxKind.ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 208 /* SyntaxKind.CallExpression */; + return context.contextNode.kind === 210 /* SyntaxKind.CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 209 /* SyntaxKind.NewExpression */; + return context.contextNode.kind === 211 /* SyntaxKind.NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); @@ -149329,10 +150678,10 @@ var ts; return context.nextTokenSpan.kind !== 21 /* SyntaxKind.CloseParenToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 214 /* SyntaxKind.ArrowFunction */; + return context.contextNode.kind === 216 /* SyntaxKind.ArrowFunction */; } function isImportTypeContext(context) { - return context.contextNode.kind === 200 /* SyntaxKind.ImportType */; + return context.contextNode.kind === 202 /* SyntaxKind.ImportType */; } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* SyntaxKind.JsxText */; @@ -149341,19 +150690,19 @@ var ts; return context.contextNode.kind !== 11 /* SyntaxKind.JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 278 /* SyntaxKind.JsxElement */ && context.contextNode.kind !== 282 /* SyntaxKind.JsxFragment */; + return context.contextNode.kind !== 281 /* SyntaxKind.JsxElement */ && context.contextNode.kind !== 285 /* SyntaxKind.JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 288 /* SyntaxKind.JsxExpression */ || context.contextNode.kind === 287 /* SyntaxKind.JsxSpreadAttribute */; + return context.contextNode.kind === 291 /* SyntaxKind.JsxExpression */ || context.contextNode.kind === 290 /* SyntaxKind.JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 285 /* SyntaxKind.JsxAttribute */; + return context.nextTokenParent.kind === 288 /* SyntaxKind.JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 285 /* SyntaxKind.JsxAttribute */; + return context.contextNode.kind === 288 /* SyntaxKind.JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 279 /* SyntaxKind.JsxSelfClosingElement */; + return context.contextNode.kind === 282 /* SyntaxKind.JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); @@ -149365,48 +150714,48 @@ var ts; !nodeIsInDecoratorContext(context.nextTokenParent); } function nodeIsInDecoratorContext(node) { - while (ts.isExpressionNode(node)) { + while (node && ts.isExpression(node)) { node = node.parent; } - return node.kind === 165 /* SyntaxKind.Decorator */; + return node && node.kind === 167 /* SyntaxKind.Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 255 /* SyntaxKind.VariableDeclarationList */ && + return context.currentTokenParent.kind === 258 /* SyntaxKind.VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormattingRequestKind.FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 261 /* SyntaxKind.ModuleDeclaration */; + return context.contextNode.kind === 264 /* SyntaxKind.ModuleDeclaration */; } function isObjectTypeContext(context) { - return context.contextNode.kind === 182 /* SyntaxKind.TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 184 /* SyntaxKind.TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 175 /* SyntaxKind.ConstructSignature */; + return context.contextNode.kind === 177 /* SyntaxKind.ConstructSignature */; } function isTypeArgumentOrParameterOrAssertion(token, parent) { if (token.kind !== 29 /* SyntaxKind.LessThanToken */ && token.kind !== 31 /* SyntaxKind.GreaterThanToken */) { return false; } switch (parent.kind) { - case 178 /* SyntaxKind.TypeReference */: - case 211 /* SyntaxKind.TypeAssertionExpression */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 180 /* SyntaxKind.TypeReference */: + case 213 /* SyntaxKind.TypeAssertionExpression */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: return true; default: return false; @@ -149417,28 +150766,28 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 211 /* SyntaxKind.TypeAssertionExpression */; + return context.contextNode.kind === 213 /* SyntaxKind.TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 114 /* SyntaxKind.VoidKeyword */ && context.currentTokenParent.kind === 217 /* SyntaxKind.VoidExpression */; + return context.currentTokenSpan.kind === 114 /* SyntaxKind.VoidKeyword */ && context.currentTokenParent.kind === 219 /* SyntaxKind.VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 224 /* SyntaxKind.YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 226 /* SyntaxKind.YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 230 /* SyntaxKind.NonNullExpression */; + return context.contextNode.kind === 232 /* SyntaxKind.NonNullExpression */; } function isNotStatementConditionContext(context) { return !isStatementConditionContext(context); } function isStatementConditionContext(context) { switch (context.contextNode.kind) { - case 239 /* SyntaxKind.IfStatement */: - case 242 /* SyntaxKind.ForStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: + case 242 /* SyntaxKind.IfStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: return true; default: return false; @@ -149463,12 +150812,12 @@ var ts; return nextTokenKind === 19 /* SyntaxKind.CloseBraceToken */ || nextTokenKind === 1 /* SyntaxKind.EndOfFileToken */; } - if (nextTokenKind === 234 /* SyntaxKind.SemicolonClassElement */ || + if (nextTokenKind === 237 /* SyntaxKind.SemicolonClassElement */ || nextTokenKind === 26 /* SyntaxKind.SemicolonToken */) { return false; } - if (context.contextNode.kind === 258 /* SyntaxKind.InterfaceDeclaration */ || - context.contextNode.kind === 259 /* SyntaxKind.TypeAliasDeclaration */) { + if (context.contextNode.kind === 261 /* SyntaxKind.InterfaceDeclaration */ || + context.contextNode.kind === 262 /* SyntaxKind.TypeAliasDeclaration */) { // Can’t remove semicolon after `foo`; it would parse as a method declaration: // // interface I { @@ -149482,9 +150831,9 @@ var ts; if (ts.isPropertyDeclaration(context.currentTokenParent)) { return !context.currentTokenParent.initializer; } - return context.currentTokenParent.kind !== 242 /* SyntaxKind.ForStatement */ - && context.currentTokenParent.kind !== 236 /* SyntaxKind.EmptyStatement */ - && context.currentTokenParent.kind !== 234 /* SyntaxKind.SemicolonClassElement */ + return context.currentTokenParent.kind !== 245 /* SyntaxKind.ForStatement */ + && context.currentTokenParent.kind !== 239 /* SyntaxKind.EmptyStatement */ + && context.currentTokenParent.kind !== 237 /* SyntaxKind.SemicolonClassElement */ && nextTokenKind !== 22 /* SyntaxKind.OpenBracketToken */ && nextTokenKind !== 20 /* SyntaxKind.OpenParenToken */ && nextTokenKind !== 39 /* SyntaxKind.PlusToken */ @@ -149492,7 +150841,7 @@ var ts; && nextTokenKind !== 43 /* SyntaxKind.SlashToken */ && nextTokenKind !== 13 /* SyntaxKind.RegularExpressionLiteral */ && nextTokenKind !== 27 /* SyntaxKind.CommaToken */ - && nextTokenKind !== 223 /* SyntaxKind.TemplateExpression */ + && nextTokenKind !== 225 /* SyntaxKind.TemplateExpression */ && nextTokenKind !== 15 /* SyntaxKind.TemplateHead */ && nextTokenKind !== 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */ && nextTokenKind !== 24 /* SyntaxKind.DotToken */; @@ -149500,6 +150849,11 @@ var ts; function isSemicolonInsertionContext(context) { return ts.positionIsASICandidate(context.currentTokenSpan.end, context.currentTokenParent, context.sourceFile); } + function isNotPropertyAccessOnIntegerLiteral(context) { + return !ts.isPropertyAccessExpression(context.contextNode) + || !ts.isNumericLiteral(context.contextNode.expression) + || context.contextNode.expression.getText().indexOf(".") !== -1; + } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /* @internal */ @@ -149583,12 +150937,12 @@ var ts; return map; } function getRuleBucketIndex(row, column) { - ts.Debug.assert(row <= 160 /* SyntaxKind.LastKeyword */ && column <= 160 /* SyntaxKind.LastKeyword */, "Must compute formatting context from tokens"); + ts.Debug.assert(row <= 162 /* SyntaxKind.LastKeyword */ && column <= 162 /* SyntaxKind.LastKeyword */, "Must compute formatting context from tokens"); return (row * mapRowLength) + column; } var maskBitSize = 5; var mask = 31; // MaskBitSize bits - var mapRowLength = 160 /* SyntaxKind.LastToken */ + 1; + var mapRowLength = 162 /* SyntaxKind.LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["StopRulesSpecific"] = 0] = "StopRulesSpecific"; @@ -149776,17 +151130,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: var body = parent.body; - return !!body && body.kind === 262 /* SyntaxKind.ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 305 /* SyntaxKind.SourceFile */: - case 235 /* SyntaxKind.Block */: - case 262 /* SyntaxKind.ModuleBlock */: + return !!body && body.kind === 265 /* SyntaxKind.ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 308 /* SyntaxKind.SourceFile */: + case 238 /* SyntaxKind.Block */: + case 265 /* SyntaxKind.ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -150049,19 +151403,19 @@ var ts; return modifier.kind; } switch (node.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: return 84 /* SyntaxKind.ClassKeyword */; - case 258 /* SyntaxKind.InterfaceDeclaration */: return 118 /* SyntaxKind.InterfaceKeyword */; - case 256 /* SyntaxKind.FunctionDeclaration */: return 98 /* SyntaxKind.FunctionKeyword */; - case 260 /* SyntaxKind.EnumDeclaration */: return 260 /* SyntaxKind.EnumDeclaration */; - case 172 /* SyntaxKind.GetAccessor */: return 136 /* SyntaxKind.GetKeyword */; - case 173 /* SyntaxKind.SetAccessor */: return 149 /* SyntaxKind.SetKeyword */; - case 169 /* SyntaxKind.MethodDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: return 84 /* SyntaxKind.ClassKeyword */; + case 261 /* SyntaxKind.InterfaceDeclaration */: return 118 /* SyntaxKind.InterfaceKeyword */; + case 259 /* SyntaxKind.FunctionDeclaration */: return 98 /* SyntaxKind.FunctionKeyword */; + case 263 /* SyntaxKind.EnumDeclaration */: return 263 /* SyntaxKind.EnumDeclaration */; + case 174 /* SyntaxKind.GetAccessor */: return 137 /* SyntaxKind.GetKeyword */; + case 175 /* SyntaxKind.SetAccessor */: return 151 /* SyntaxKind.SetKeyword */; + case 171 /* SyntaxKind.MethodDeclaration */: if (node.asteriskToken) { return 41 /* SyntaxKind.AsteriskToken */; } // falls through - case 167 /* SyntaxKind.PropertyDeclaration */: - case 164 /* SyntaxKind.Parameter */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 166 /* SyntaxKind.Parameter */: var name = ts.getNameOfDeclaration(node); if (name) { return name.kind; @@ -150118,15 +151472,15 @@ var ts; case 43 /* SyntaxKind.SlashToken */: case 31 /* SyntaxKind.GreaterThanToken */: switch (container.kind) { - case 280 /* SyntaxKind.JsxOpeningElement */: - case 281 /* SyntaxKind.JsxClosingElement */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 284 /* SyntaxKind.JsxClosingElement */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: return false; } break; case 22 /* SyntaxKind.OpenBracketToken */: case 23 /* SyntaxKind.CloseBracketToken */: - if (container.kind !== 195 /* SyntaxKind.MappedType */) { + if (container.kind !== 197 /* SyntaxKind.MappedType */) { return false; } break; @@ -150230,11 +151584,11 @@ var ts; return inheritedIndentation; } } - var effectiveParentStartLine = child.kind === 165 /* SyntaxKind.Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 167 /* SyntaxKind.Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; - if (isFirstListItem && parent.kind === 204 /* SyntaxKind.ArrayLiteralExpression */ && inheritedIndentation === -1 /* Constants.Unknown */) { + if (isFirstListItem && parent.kind === 206 /* SyntaxKind.ArrayLiteralExpression */ && inheritedIndentation === -1 /* Constants.Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -150692,18 +152046,18 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 171 /* SyntaxKind.Constructor */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 214 /* SyntaxKind.ArrowFunction */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 173 /* SyntaxKind.Constructor */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 216 /* SyntaxKind.ArrowFunction */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: if (node.typeParameters === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -150711,8 +152065,8 @@ var ts; return 20 /* SyntaxKind.OpenParenToken */; } break; - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: if (node.typeArguments === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -150720,24 +152074,24 @@ var ts; return 20 /* SyntaxKind.OpenParenToken */; } break; - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: if (node.typeParameters === list) { return 29 /* SyntaxKind.LessThanToken */; } break; - case 178 /* SyntaxKind.TypeReference */: - case 210 /* SyntaxKind.TaggedTemplateExpression */: - case 181 /* SyntaxKind.TypeQuery */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: - case 200 /* SyntaxKind.ImportType */: + case 180 /* SyntaxKind.TypeReference */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: + case 183 /* SyntaxKind.TypeQuery */: + case 230 /* SyntaxKind.ExpressionWithTypeArguments */: + case 202 /* SyntaxKind.ImportType */: if (node.typeArguments === list) { return 29 /* SyntaxKind.LessThanToken */; } break; - case 182 /* SyntaxKind.TypeLiteral */: + case 184 /* SyntaxKind.TypeLiteral */: return 18 /* SyntaxKind.OpenBraceToken */; } return 0 /* SyntaxKind.Unknown */; @@ -150873,11 +152227,11 @@ var ts; // y: undefined, // } // ``` - var isObjectLiteral = currentToken.kind === 18 /* SyntaxKind.OpenBraceToken */ && currentToken.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */; + var isObjectLiteral = currentToken.kind === 18 /* SyntaxKind.OpenBraceToken */ && currentToken.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */; if (options.indentStyle === ts.IndentStyle.Block || isObjectLiteral) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 27 /* SyntaxKind.CommaToken */ && precedingToken.parent.kind !== 221 /* SyntaxKind.BinaryExpression */) { + if (precedingToken.kind === 27 /* SyntaxKind.CommaToken */ && precedingToken.parent.kind !== 223 /* SyntaxKind.BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Value.Unknown */) { @@ -150887,7 +152241,7 @@ var ts; var containerList = getListByPosition(position, precedingToken.parent, sourceFile); // use list position if the preceding token is before any list items if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) { - var useTheSameBaseIndentation = [213 /* SyntaxKind.FunctionExpression */, 214 /* SyntaxKind.ArrowFunction */].indexOf(currentToken.parent.kind) !== -1; + var useTheSameBaseIndentation = [215 /* SyntaxKind.FunctionExpression */, 216 /* SyntaxKind.ArrowFunction */].indexOf(currentToken.parent.kind) !== -1; var indentSize = useTheSameBaseIndentation ? 0 : options.indentSize; return getActualIndentationForListStartLine(containerList, sourceFile, options) + indentSize; // TODO: GH#18217 } @@ -151052,7 +152406,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 305 /* SyntaxKind.SourceFile */ || !parentAndChildShareLine); + (parent.kind === 308 /* SyntaxKind.SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Value.Unknown */; } @@ -151100,7 +152454,7 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 239 /* SyntaxKind.IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 242 /* SyntaxKind.IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 91 /* SyntaxKind.ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -151181,42 +152535,42 @@ var ts; } function getListByRange(start, end, node, sourceFile) { switch (node.kind) { - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return getList(node.typeArguments); - case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: return getList(node.properties); - case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: return getList(node.elements); - case 182 /* SyntaxKind.TypeLiteral */: + case 184 /* SyntaxKind.TypeLiteral */: return getList(node.members); - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 174 /* SyntaxKind.CallSignature */: - case 171 /* SyntaxKind.Constructor */: - case 180 /* SyntaxKind.ConstructorType */: - case 175 /* SyntaxKind.ConstructSignature */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 173 /* SyntaxKind.Constructor */: + case 182 /* SyntaxKind.ConstructorType */: + case 177 /* SyntaxKind.ConstructSignature */: return getList(node.typeParameters) || getList(node.parameters); - case 172 /* SyntaxKind.GetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: return getList(node.parameters); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 344 /* SyntaxKind.JSDocTemplateTag */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 347 /* SyntaxKind.JSDocTemplateTag */: return getList(node.typeParameters); - case 209 /* SyntaxKind.NewExpression */: - case 208 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: + case 210 /* SyntaxKind.CallExpression */: return getList(node.typeArguments) || getList(node.arguments); - case 255 /* SyntaxKind.VariableDeclarationList */: + case 258 /* SyntaxKind.VariableDeclarationList */: return getList(node.declarations); - case 269 /* SyntaxKind.NamedImports */: - case 273 /* SyntaxKind.NamedExports */: + case 272 /* SyntaxKind.NamedImports */: + case 276 /* SyntaxKind.NamedExports */: return getList(node.elements); - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 202 /* SyntaxKind.ArrayBindingPattern */: + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: return getList(node.elements); } function getList(list) { @@ -151239,7 +152593,7 @@ var ts; return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); } function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { - if (node.parent && node.parent.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (node.parent && node.parent.kind === 258 /* SyntaxKind.VariableDeclarationList */) { // VariableDeclarationList has no wrapping tokens return -1 /* Value.Unknown */; } @@ -151312,96 +152666,96 @@ var ts; function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* SyntaxKind.Unknown */; switch (parent.kind) { - case 238 /* SyntaxKind.ExpressionStatement */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: - case 235 /* SyntaxKind.Block */: - case 262 /* SyntaxKind.ModuleBlock */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 182 /* SyntaxKind.TypeLiteral */: - case 195 /* SyntaxKind.MappedType */: - case 184 /* SyntaxKind.TupleType */: - case 263 /* SyntaxKind.CaseBlock */: - case 290 /* SyntaxKind.DefaultClause */: - case 289 /* SyntaxKind.CaseClause */: - case 212 /* SyntaxKind.ParenthesizedExpression */: - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: - case 237 /* SyntaxKind.VariableStatement */: - case 271 /* SyntaxKind.ExportAssignment */: - case 247 /* SyntaxKind.ReturnStatement */: - case 222 /* SyntaxKind.ConditionalExpression */: - case 202 /* SyntaxKind.ArrayBindingPattern */: - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 280 /* SyntaxKind.JsxOpeningElement */: - case 283 /* SyntaxKind.JsxOpeningFragment */: - case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 288 /* SyntaxKind.JsxExpression */: - case 168 /* SyntaxKind.MethodSignature */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 164 /* SyntaxKind.Parameter */: - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 191 /* SyntaxKind.ParenthesizedType */: - case 210 /* SyntaxKind.TaggedTemplateExpression */: - case 218 /* SyntaxKind.AwaitExpression */: - case 273 /* SyntaxKind.NamedExports */: - case 269 /* SyntaxKind.NamedImports */: - case 275 /* SyntaxKind.ExportSpecifier */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 167 /* SyntaxKind.PropertyDeclaration */: + case 241 /* SyntaxKind.ExpressionStatement */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: + case 238 /* SyntaxKind.Block */: + case 265 /* SyntaxKind.ModuleBlock */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 184 /* SyntaxKind.TypeLiteral */: + case 197 /* SyntaxKind.MappedType */: + case 186 /* SyntaxKind.TupleType */: + case 266 /* SyntaxKind.CaseBlock */: + case 293 /* SyntaxKind.DefaultClause */: + case 292 /* SyntaxKind.CaseClause */: + case 214 /* SyntaxKind.ParenthesizedExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: + case 240 /* SyntaxKind.VariableStatement */: + case 274 /* SyntaxKind.ExportAssignment */: + case 250 /* SyntaxKind.ReturnStatement */: + case 224 /* SyntaxKind.ConditionalExpression */: + case 204 /* SyntaxKind.ArrayBindingPattern */: + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 283 /* SyntaxKind.JsxOpeningElement */: + case 286 /* SyntaxKind.JsxOpeningFragment */: + case 282 /* SyntaxKind.JsxSelfClosingElement */: + case 291 /* SyntaxKind.JsxExpression */: + case 170 /* SyntaxKind.MethodSignature */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 166 /* SyntaxKind.Parameter */: + case 181 /* SyntaxKind.FunctionType */: + case 182 /* SyntaxKind.ConstructorType */: + case 193 /* SyntaxKind.ParenthesizedType */: + case 212 /* SyntaxKind.TaggedTemplateExpression */: + case 220 /* SyntaxKind.AwaitExpression */: + case 276 /* SyntaxKind.NamedExports */: + case 272 /* SyntaxKind.NamedImports */: + case 278 /* SyntaxKind.ExportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 169 /* SyntaxKind.PropertyDeclaration */: return true; - case 254 /* SyntaxKind.VariableDeclaration */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 221 /* SyntaxKind.BinaryExpression */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 205 /* SyntaxKind.ObjectLiteralExpression */) { // TODO: GH#18217 + case 257 /* SyntaxKind.VariableDeclaration */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 223 /* SyntaxKind.BinaryExpression */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 207 /* SyntaxKind.ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } - if (parent.kind === 221 /* SyntaxKind.BinaryExpression */ && sourceFile && child && childKind === 278 /* SyntaxKind.JsxElement */) { + if (parent.kind === 223 /* SyntaxKind.BinaryExpression */ && sourceFile && child && childKind === 281 /* SyntaxKind.JsxElement */) { var parentStartLine = sourceFile.getLineAndCharacterOfPosition(ts.skipTrivia(sourceFile.text, parent.pos)).line; var childStartLine = sourceFile.getLineAndCharacterOfPosition(ts.skipTrivia(sourceFile.text, child.pos)).line; return parentStartLine !== childStartLine; } - if (parent.kind !== 221 /* SyntaxKind.BinaryExpression */) { + if (parent.kind !== 223 /* SyntaxKind.BinaryExpression */) { return true; } break; - case 240 /* SyntaxKind.DoStatement */: - case 241 /* SyntaxKind.WhileStatement */: - case 243 /* SyntaxKind.ForInStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 242 /* SyntaxKind.ForStatement */: - case 239 /* SyntaxKind.IfStatement */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - return childKind !== 235 /* SyntaxKind.Block */; - case 214 /* SyntaxKind.ArrowFunction */: - if (sourceFile && childKind === 212 /* SyntaxKind.ParenthesizedExpression */) { + case 243 /* SyntaxKind.DoStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 246 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 242 /* SyntaxKind.IfStatement */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + return childKind !== 238 /* SyntaxKind.Block */; + case 216 /* SyntaxKind.ArrowFunction */: + if (sourceFile && childKind === 214 /* SyntaxKind.ParenthesizedExpression */) { return rangeIsOnOneLine(sourceFile, child); } - return childKind !== 235 /* SyntaxKind.Block */; - case 272 /* SyntaxKind.ExportDeclaration */: - return childKind !== 273 /* SyntaxKind.NamedExports */; - case 266 /* SyntaxKind.ImportDeclaration */: - return childKind !== 267 /* SyntaxKind.ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 269 /* SyntaxKind.NamedImports */); - case 278 /* SyntaxKind.JsxElement */: - return childKind !== 281 /* SyntaxKind.JsxClosingElement */; - case 282 /* SyntaxKind.JsxFragment */: - return childKind !== 284 /* SyntaxKind.JsxClosingFragment */; - case 188 /* SyntaxKind.IntersectionType */: - case 187 /* SyntaxKind.UnionType */: - if (childKind === 182 /* SyntaxKind.TypeLiteral */ || childKind === 184 /* SyntaxKind.TupleType */) { + return childKind !== 238 /* SyntaxKind.Block */; + case 275 /* SyntaxKind.ExportDeclaration */: + return childKind !== 276 /* SyntaxKind.NamedExports */; + case 269 /* SyntaxKind.ImportDeclaration */: + return childKind !== 270 /* SyntaxKind.ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 272 /* SyntaxKind.NamedImports */); + case 281 /* SyntaxKind.JsxElement */: + return childKind !== 284 /* SyntaxKind.JsxClosingElement */; + case 285 /* SyntaxKind.JsxFragment */: + return childKind !== 287 /* SyntaxKind.JsxClosingFragment */; + case 190 /* SyntaxKind.IntersectionType */: + case 189 /* SyntaxKind.UnionType */: + if (childKind === 184 /* SyntaxKind.TypeLiteral */ || childKind === 186 /* SyntaxKind.TupleType */) { return false; } break; @@ -151412,11 +152766,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 247 /* SyntaxKind.ReturnStatement */: - case 251 /* SyntaxKind.ThrowStatement */: - case 245 /* SyntaxKind.ContinueStatement */: - case 246 /* SyntaxKind.BreakStatement */: - return parent.kind !== 235 /* SyntaxKind.Block */; + case 250 /* SyntaxKind.ReturnStatement */: + case 254 /* SyntaxKind.ThrowStatement */: + case 248 /* SyntaxKind.ContinueStatement */: + case 249 /* SyntaxKind.BreakStatement */: + return parent.kind !== 238 /* SyntaxKind.Block */; default: return false; } @@ -151633,7 +152987,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return !!candidate && !!node.parent && (candidate.kind === 27 /* SyntaxKind.CommaToken */ || (candidate.kind === 26 /* SyntaxKind.SemicolonToken */ && node.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */)); + return !!candidate && !!node.parent && (candidate.kind === 27 /* SyntaxKind.CommaToken */ || (candidate.kind === 26 /* SyntaxKind.SemicolonToken */ && node.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */)); } function isThisTypeAnnotatable(containingFunction) { return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction); @@ -151865,7 +153219,7 @@ var ts; } } else { - endNode = (_a = (node.kind === 254 /* SyntaxKind.VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; + endNode = (_a = (node.kind === 257 /* SyntaxKind.VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); return true; @@ -152031,18 +153385,18 @@ var ts; }; ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { switch (node.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: case 10 /* SyntaxKind.StringLiteral */: case 79 /* SyntaxKind.Identifier */: return { prefix: ", " }; - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: return { suffix: "," + this.newLineCharacter }; case 93 /* SyntaxKind.ExportKeyword */: return { prefix: " " }; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return {}; default: ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it @@ -152051,7 +153405,7 @@ var ts; }; ChangeTracker.prototype.insertName = function (sourceFile, node, name) { ts.Debug.assert(!node.name); - if (node.kind === 214 /* SyntaxKind.ArrowFunction */) { + if (node.kind === 216 /* SyntaxKind.ArrowFunction */) { var arrow = ts.findChildOfKind(node, 38 /* SyntaxKind.EqualsGreaterThanToken */, sourceFile); var lparen = ts.findChildOfKind(node, 20 /* SyntaxKind.OpenParenToken */, sourceFile); if (lparen) { @@ -152065,14 +153419,14 @@ var ts; // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` this.replaceRange(sourceFile, arrow, ts.factory.createToken(21 /* SyntaxKind.CloseParenToken */)); } - if (node.body.kind !== 235 /* SyntaxKind.Block */) { + if (node.body.kind !== 238 /* SyntaxKind.Block */) { // `() => 0` => `function f() { return 0; }` this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.factory.createToken(18 /* SyntaxKind.OpenBraceToken */), ts.factory.createToken(105 /* SyntaxKind.ReturnKeyword */)], { joiner: " ", suffix: " " }); this.insertNodesAt(sourceFile, node.body.end, [ts.factory.createToken(26 /* SyntaxKind.SemicolonToken */), ts.factory.createToken(19 /* SyntaxKind.CloseBraceToken */)], { joiner: " " }); } } else { - var pos = ts.findChildOfKind(node, node.kind === 213 /* SyntaxKind.FunctionExpression */ ? 98 /* SyntaxKind.FunctionKeyword */ : 84 /* SyntaxKind.ClassKeyword */, sourceFile).end; + var pos = ts.findChildOfKind(node, node.kind === 215 /* SyntaxKind.FunctionExpression */ ? 98 /* SyntaxKind.FunctionKeyword */ : 84 /* SyntaxKind.ClassKeyword */, sourceFile).end; this.insertNodeAt(sourceFile, pos, ts.factory.createIdentifier(name), { prefix: " " }); } }; @@ -152249,10 +153603,10 @@ var ts; }()); textChanges_3.ChangeTracker = ChangeTracker; function updateJSDocHost(parent) { - if (parent.kind !== 214 /* SyntaxKind.ArrowFunction */) { + if (parent.kind !== 216 /* SyntaxKind.ArrowFunction */) { return parent; } - var jsDocNode = parent.parent.kind === 167 /* SyntaxKind.PropertyDeclaration */ ? + var jsDocNode = parent.parent.kind === 169 /* SyntaxKind.PropertyDeclaration */ ? parent.parent : parent.parent.parent; jsDocNode.jsDoc = parent.jsDoc; @@ -152264,16 +153618,16 @@ var ts; return undefined; } switch (oldTag.kind) { - case 340 /* SyntaxKind.JSDocParameterTag */: { + case 343 /* SyntaxKind.JSDocParameterTag */: { var oldParam = oldTag; var newParam = newTag; return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? ts.factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) : undefined; } - case 341 /* SyntaxKind.JSDocReturnTag */: + case 344 /* SyntaxKind.JSDocReturnTag */: return ts.factory.createJSDocReturnTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); - case 343 /* SyntaxKind.JSDocTypeTag */: + case 346 /* SyntaxKind.JSDocTypeTag */: return ts.factory.createJSDocTypeTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); } } @@ -152281,6 +153635,26 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } + function endPositionToDeleteNodeInList(sourceFile, node, prevNode, nextNode) { + var end = startPositionToDeleteNodeInList(sourceFile, nextNode); + if (prevNode === undefined || ts.positionsAreOnSameLine(getAdjustedEndPosition(sourceFile, node, {}), end, sourceFile)) { + return end; + } + var token = ts.findPrecedingToken(nextNode.getStart(sourceFile), sourceFile); + if (isSeparator(node, token)) { + var prevToken = ts.findPrecedingToken(node.getStart(sourceFile), sourceFile); + if (isSeparator(prevNode, prevToken)) { + var pos = ts.skipTrivia(sourceFile.text, token.getEnd(), /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + if (ts.positionsAreOnSameLine(prevToken.getStart(sourceFile), token.getStart(sourceFile), sourceFile)) { + return ts.isLineBreak(sourceFile.text.charCodeAt(pos - 1)) ? pos - 1 : pos; + } + if (ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { + return pos; + } + } + } + return end; + } function getClassOrObjectBraceEnds(cls, sourceFile) { var open = ts.findChildOfKind(cls, 18 /* SyntaxKind.OpenBraceToken */, sourceFile); var close = ts.findChildOfKind(cls, 19 /* SyntaxKind.CloseBraceToken */, sourceFile); @@ -152667,14 +154041,14 @@ var ts; } textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; function needSemicolonBetween(a, b) { - return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 162 /* SyntaxKind.ComputedPropertyName */ + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 164 /* SyntaxKind.ComputedPropertyName */ || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` } var deleteDeclaration; (function (deleteDeclaration_1) { function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { switch (node.kind) { - case 164 /* SyntaxKind.Parameter */: { + case 166 /* SyntaxKind.Parameter */: { var oldFunction = node.parent; if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && @@ -152689,17 +154063,17 @@ var ts; } break; } - case 266 /* SyntaxKind.ImportDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); // For first import, leave header comment in place, otherwise only delete JSDoc comments deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine, }); break; - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: var pattern = node.parent; - var preserveComma = pattern.kind === 202 /* SyntaxKind.ArrayBindingPattern */ && node !== ts.last(pattern.elements); + var preserveComma = pattern.kind === 204 /* SyntaxKind.ArrayBindingPattern */ && node !== ts.last(pattern.elements); if (preserveComma) { deleteNode(changes, sourceFile, node); } @@ -152707,13 +154081,13 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 163 /* SyntaxKind.TypeParameter */: + case 165 /* SyntaxKind.TypeParameter */: deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 270 /* SyntaxKind.ImportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { deleteImportBinding(changes, sourceFile, namedImports); @@ -152722,7 +154096,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 268 /* SyntaxKind.NamespaceImport */: + case 271 /* SyntaxKind.NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; case 26 /* SyntaxKind.SemicolonToken */: @@ -152731,8 +154105,8 @@ var ts; case 98 /* SyntaxKind.FunctionKeyword */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude }); break; - case 257 /* SyntaxKind.ClassDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: @@ -152783,13 +154157,13 @@ var ts; // Delete the entire import declaration // |import * as ns from './file'| // |import { a } from './file'| - var importDecl = ts.getAncestor(node, 266 /* SyntaxKind.ImportDeclaration */); + var importDecl = ts.getAncestor(node, 269 /* SyntaxKind.ImportDeclaration */); deleteNode(changes, sourceFile, importDecl); } } function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { var parent = node.parent; - if (parent.kind === 292 /* SyntaxKind.CatchClause */) { + if (parent.kind === 295 /* SyntaxKind.CatchClause */) { // TODO: There's currently no unused diagnostic for this, could be a suggestion changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* SyntaxKind.OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* SyntaxKind.CloseParenToken */, sourceFile)); return; @@ -152800,14 +154174,14 @@ var ts; } var gp = parent.parent; switch (gp.kind) { - case 244 /* SyntaxKind.ForOfStatement */: - case 243 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 246 /* SyntaxKind.ForInStatement */: changes.replaceNode(sourceFile, node, ts.factory.createObjectLiteralExpression()); break; - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: deleteNode(changes, sourceFile, parent); break; - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: @@ -152838,7 +154212,7 @@ var ts; deletedNodesInLists.add(node); changes.deleteRange(sourceFile, { pos: startPositionToDeleteNodeInList(sourceFile, node), - end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : endPositionToDeleteNodeInList(sourceFile, node, containingList[index - 1], containingList[index + 1]), }); } })(textChanges = ts.textChanges || (ts.textChanges = {})); @@ -152994,8 +154368,8 @@ var ts; }); function makeChange(changeTracker, sourceFile, assertion) { var replacement = ts.isAsExpression(assertion) - ? ts.factory.createAsExpression(assertion.expression, ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */)) - : ts.factory.createTypeAssertion(ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), assertion.expression); + ? ts.factory.createAsExpression(assertion.expression, ts.factory.createKeywordTypeNode(157 /* SyntaxKind.UnknownKeyword */)) + : ts.factory.createTypeAssertion(ts.factory.createKeywordTypeNode(157 /* SyntaxKind.UnknownKeyword */), assertion.expression); changeTracker.replaceNode(sourceFile, assertion.expression, replacement); } function getAssertion(sourceFile, pos) { @@ -153079,7 +154453,7 @@ var ts; } } fixedDeclarations === null || fixedDeclarations === void 0 ? void 0 : fixedDeclarations.add(ts.getNodeId(insertionSite)); - var cloneWithModifier = ts.factory.updateModifiers(ts.getSynthesizedDeepClone(insertionSite, /*includeTrivia*/ true), ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(ts.getSyntacticModifierFlags(insertionSite) | 256 /* ModifierFlags.Async */))); + var cloneWithModifier = ts.factory.updateModifiers(ts.getSynthesizedDeepClone(insertionSite, /*includeTrivia*/ true), ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(ts.getSyntacticModifierFlags(insertionSite) | 512 /* ModifierFlags.Async */))); changeTracker.replaceNode(sourceFile, insertionSite, cloneWithModifier); } function getFixableErrorSpanDeclaration(sourceFile, span) { @@ -153125,7 +154499,7 @@ var ts; ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, - ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code, + ts.Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap.code, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, ts.Diagnostics.Type_0_is_not_an_array_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, @@ -153223,7 +154597,7 @@ var ts; } var declaration = ts.tryCast(symbol.valueDeclaration, ts.isVariableDeclaration); var variableName = declaration && ts.tryCast(declaration.name, ts.isIdentifier); - var variableStatement = ts.getAncestor(declaration, 237 /* SyntaxKind.VariableStatement */); + var variableStatement = ts.getAncestor(declaration, 240 /* SyntaxKind.VariableStatement */); if (!declaration || !variableStatement || declaration.type || !declaration.initializer || @@ -153301,13 +154675,22 @@ var ts; function isInsideAwaitableBody(node) { return node.kind & 32768 /* NodeFlags.AwaitContext */ || !!ts.findAncestor(node, function (ancestor) { return ancestor.parent && ts.isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || - ts.isBlock(ancestor) && (ancestor.parent.kind === 256 /* SyntaxKind.FunctionDeclaration */ || - ancestor.parent.kind === 213 /* SyntaxKind.FunctionExpression */ || - ancestor.parent.kind === 214 /* SyntaxKind.ArrowFunction */ || - ancestor.parent.kind === 169 /* SyntaxKind.MethodDeclaration */); + ts.isBlock(ancestor) && (ancestor.parent.kind === 259 /* SyntaxKind.FunctionDeclaration */ || + ancestor.parent.kind === 215 /* SyntaxKind.FunctionExpression */ || + ancestor.parent.kind === 216 /* SyntaxKind.ArrowFunction */ || + ancestor.parent.kind === 171 /* SyntaxKind.MethodDeclaration */); }); } function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { + if (ts.isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) { + var exprType = checker.getTypeAtLocation(insertionSite); + var asyncIter = checker.getAsyncIterableType(); + if (asyncIter && checker.isTypeAssignableTo(exprType, asyncIter)) { + var forOf = insertionSite.parent; + changeTracker.replaceNode(sourceFile, forOf, ts.factory.updateForOfStatement(forOf, ts.factory.createToken(133 /* SyntaxKind.AwaitKeyword */), forOf.initializer, forOf.expression, forOf.statement)); + return; + } + } if (ts.isBinaryExpression(insertionSite)) { for (var _i = 0, _a = [insertionSite.left, insertionSite.right]; _i < _a.length; _i++) { var side = _a[_i]; @@ -153423,10 +154806,10 @@ var ts; function isPossiblyPartOfDestructuring(node) { switch (node.kind) { case 79 /* SyntaxKind.Identifier */: - case 204 /* SyntaxKind.ArrayLiteralExpression */: - case 205 /* SyntaxKind.ObjectLiteralExpression */: - case 296 /* SyntaxKind.PropertyAssignment */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 206 /* SyntaxKind.ArrayLiteralExpression */: + case 207 /* SyntaxKind.ObjectLiteralExpression */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: return true; default: return false; @@ -153441,7 +154824,7 @@ var ts; function isPossiblyPartOfCommaSeperatedInitializer(node) { switch (node.kind) { case 79 /* SyntaxKind.Identifier */: - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: case 27 /* SyntaxKind.CommaToken */: return true; default: @@ -153490,9 +154873,9 @@ var ts; return; } var declaration = token.parent; - if (declaration.kind === 167 /* SyntaxKind.PropertyDeclaration */ && + if (declaration.kind === 169 /* SyntaxKind.PropertyDeclaration */ && (!fixedNodes || ts.tryAddToSet(fixedNodes, declaration))) { - changeTracker.insertModifierBefore(sourceFile, 135 /* SyntaxKind.DeclareKeyword */, declaration); + changeTracker.insertModifierBefore(sourceFile, 136 /* SyntaxKind.DeclareKeyword */, declaration); } } })(codefix = ts.codefix || (ts.codefix = {})); @@ -153646,7 +155029,7 @@ var ts; var add = toAdd_1[_i]; var d = add.valueDeclaration; if (d && (ts.isPropertySignature(d) || ts.isPropertyDeclaration(d)) && d.type) { - var t = ts.factory.createUnionTypeNode(__spreadArray(__spreadArray([], d.type.kind === 187 /* SyntaxKind.UnionType */ ? d.type.types : [d.type], true), [ + var t = ts.factory.createUnionTypeNode(__spreadArray(__spreadArray([], d.type.kind === 189 /* SyntaxKind.UnionType */ ? d.type.types : [d.type], true), [ ts.factory.createTypeReferenceNode("undefined") ], false)); changes.replaceNode(d.getSourceFile(), d.type, t); @@ -153726,26 +155109,26 @@ var ts; } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 254 /* SyntaxKind.VariableDeclaration */ || - node.kind === 166 /* SyntaxKind.PropertySignature */ || - node.kind === 167 /* SyntaxKind.PropertyDeclaration */; + node.kind === 257 /* SyntaxKind.VariableDeclaration */ || + node.kind === 168 /* SyntaxKind.PropertySignature */ || + node.kind === 169 /* SyntaxKind.PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 312 /* SyntaxKind.JSDocAllType */: - case 313 /* SyntaxKind.JSDocUnknownType */: + case 315 /* SyntaxKind.JSDocAllType */: + case 316 /* SyntaxKind.JSDocUnknownType */: return ts.factory.createTypeReferenceNode("any", ts.emptyArray); - case 316 /* SyntaxKind.JSDocOptionalType */: + case 319 /* SyntaxKind.JSDocOptionalType */: return transformJSDocOptionalType(node); - case 315 /* SyntaxKind.JSDocNonNullableType */: + case 318 /* SyntaxKind.JSDocNonNullableType */: return transformJSDocType(node.type); - case 314 /* SyntaxKind.JSDocNullableType */: + case 317 /* SyntaxKind.JSDocNullableType */: return transformJSDocNullableType(node); - case 318 /* SyntaxKind.JSDocVariadicType */: + case 321 /* SyntaxKind.JSDocVariadicType */: return transformJSDocVariadicType(node); - case 317 /* SyntaxKind.JSDocFunctionType */: + case 320 /* SyntaxKind.JSDocFunctionType */: return transformJSDocFunctionType(node); - case 178 /* SyntaxKind.TypeReference */: + case 180 /* SyntaxKind.TypeReference */: return transformJSDocTypeReference(node); default: var visited = ts.visitEachChild(node, transformJSDocType, ts.nullTransformationContext); @@ -153766,11 +155149,11 @@ var ts; var _a; // TODO: This does not properly handle `function(new:C, string)` per https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System#the-javascript-type-language // however we do handle it correctly in `serializeTypeForDeclaration` in checker.ts - return ts.factory.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), (_a = node.type) !== null && _a !== void 0 ? _a : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); + return ts.factory.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), (_a = node.type) !== null && _a !== void 0 ? _a : ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */)); } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 318 /* SyntaxKind.JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var isRest = node.type.kind === 321 /* SyntaxKind.JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : node.dotDotDotToken; return ts.factory.createParameterDeclaration(node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -153809,8 +155192,8 @@ var ts; function transformJSDocIndexSignature(node) { var index = ts.factory.createParameterDeclaration( /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "n" : "s", - /*questionToken*/ undefined, ts.factory.createTypeReferenceNode(node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "number" : "string", []), + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 148 /* SyntaxKind.NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.factory.createTypeReferenceNode(node.typeArguments[0].kind === 148 /* SyntaxKind.NumberKeyword */ ? "number" : "string", []), /*initializer*/ undefined); var indexSignature = ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(/*modifiers*/ undefined, [index], node.typeArguments[1])]); ts.setEmitFlags(indexSignature, 1 /* EmitFlags.SingleLine */); @@ -153845,8 +155228,8 @@ var ts; return undefined; } var ctorDeclaration = ctorSymbol.valueDeclaration; - if (ts.isFunctionDeclaration(ctorDeclaration)) { - changes.replaceNode(sourceFile, ctorDeclaration, createClassFromFunctionDeclaration(ctorDeclaration)); + if (ts.isFunctionDeclaration(ctorDeclaration) || ts.isFunctionExpression(ctorDeclaration)) { + changes.replaceNode(sourceFile, ctorDeclaration, createClassFromFunction(ctorDeclaration)); } else if (ts.isVariableDeclaration(ctorDeclaration)) { var classDeclaration = createClassFromVariableDeclaration(ctorDeclaration); @@ -153950,7 +155333,7 @@ var ts; return; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 238 /* SyntaxKind.ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 241 /* SyntaxKind.ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { @@ -154002,7 +155385,7 @@ var ts; return createArrowFunctionExpressionMember(members, expression, name); } function createFunctionExpressionMember(members, functionExpression, name) { - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 131 /* SyntaxKind.AsyncKeyword */)); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 132 /* SyntaxKind.AsyncKeyword */)); var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); @@ -154013,14 +155396,14 @@ var ts; var arrowFunctionBody = arrowFunction.body; var bodyBlock; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 235 /* SyntaxKind.Block */) { + if (arrowFunctionBody.kind === 238 /* SyntaxKind.Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] else { bodyBlock = ts.factory.createBlock([ts.factory.createReturnStatement(arrowFunctionBody)]); } - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 131 /* SyntaxKind.AsyncKeyword */)); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 132 /* SyntaxKind.AsyncKeyword */)); var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); @@ -154043,7 +155426,7 @@ var ts; // Don't call copyComments here because we'll already leave them in place return cls; } - function createClassFromFunctionDeclaration(node) { + function createClassFromFunction(node) { var memberElements = createClassElementsFromSymbol(ctorSymbol); if (node.body) { memberElements.unshift(ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, node.parameters, node.body)); @@ -154133,7 +155516,7 @@ var ts; return; } var pos = ts.skipTrivia(sourceFile.text, ts.moveRangePastModifiers(functionToConvert).pos); - changes.insertModifierAt(sourceFile, pos, 131 /* SyntaxKind.AsyncKeyword */, { suffix: " " }); + changes.insertModifierAt(sourceFile, pos, 132 /* SyntaxKind.AsyncKeyword */, { suffix: " " }); var _loop_12 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { @@ -154539,7 +155922,7 @@ var ts; case 104 /* SyntaxKind.NullKeyword */: // do not produce a transformed statement for a null argument break; - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: case 79 /* SyntaxKind.Identifier */: // identifier includes undefined if (!inputArgName) { // undefined was argument passed to promise handler @@ -154561,8 +155944,8 @@ var ts; continuationArgName.types.push(transformer.checker.getAwaitedType(returnType) || returnType); } return varDeclOrAssignment; - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: { + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: { var funcBody = func.body; var returnType_1 = (_a = getLastCallSignature(transformer.checker.getTypeAtLocation(func), transformer.checker)) === null || _a === void 0 ? void 0 : _a.getReturnType(); // Arrow functions with block bodies { } will enter this control flow @@ -154731,7 +156114,7 @@ var ts; name = getMapEntryOrDefault(funcNode.name); } // return undefined argName when arg is null or undefined - // eslint-disable-next-line no-in-operator + // eslint-disable-next-line local/no-in-operator if (!name || "identifier" in name && name.identifier.text === "undefined") { return undefined; } @@ -154840,10 +156223,10 @@ var ts; } var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - case 208 /* SyntaxKind.CallExpression */: + case 210 /* SyntaxKind.CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { changes.replaceNode(importingFile, importNode, ts.factory.createPropertyAccessExpression(ts.getSynthesizedDeepClone(importNode), "default")); } @@ -154910,20 +156293,20 @@ var ts; } function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference) { switch (statement.kind) { - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 238 /* SyntaxKind.ExpressionStatement */: { + case 241 /* SyntaxKind.ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 208 /* SyntaxKind.CallExpression */: { + case 210 /* SyntaxKind.CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 221 /* SyntaxKind.BinaryExpression */: { + case 223 /* SyntaxKind.BinaryExpression */: { var operatorToken = expression.operatorToken; return operatorToken.kind === 63 /* SyntaxKind.EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports, useSitesToUnqualify); } @@ -154972,8 +156355,8 @@ var ts; /** Converts `const name = require("moduleSpecifier").propertyName` */ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 202 /* SyntaxKind.ArrayBindingPattern */: { + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return convertedImports([ @@ -155024,16 +156407,16 @@ var ts; function tryChangeModuleExportsObject(object, useSitesToUnqualify) { var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. // falls through - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 298 /* SyntaxKind.SpreadAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 301 /* SyntaxKind.SpreadAssignment */: return undefined; - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer, useSitesToUnqualify); - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.factory.createToken(93 /* SyntaxKind.ExportKeyword */)], prop, useSitesToUnqualify); default: ts.Debug.assertNever(prop, "Convert to ES6 got invalid prop kind ".concat(prop.kind)); @@ -155097,7 +156480,7 @@ var ts; function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualify) { var modifiers = [ts.factory.createToken(93 /* SyntaxKind.ExportKeyword */)]; switch (exported.kind) { - case 213 /* SyntaxKind.FunctionExpression */: { + case 215 /* SyntaxKind.FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -155105,10 +156488,10 @@ var ts; } } // falls through - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); - case 226 /* SyntaxKind.ClassExpression */: + case 228 /* SyntaxKind.ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); default: @@ -155128,7 +156511,7 @@ var ts; : ts.getSynthesizedDeepCloneWithReplacements(nodeOrNodes, /*includeTrivia*/ true, replaceNode); function replaceNode(original) { // We are replacing `mod.SomeExport` wih `SomeExport`, so we only need to look at PropertyAccessExpressions - if (original.kind === 206 /* SyntaxKind.PropertyAccessExpression */) { + if (original.kind === 208 /* SyntaxKind.PropertyAccessExpression */) { var replacement = useSitesToUnqualify.get(original); // Remove entry from `useSitesToUnqualify` so the refactor knows it's taken care of by the parent statement we're replacing useSitesToUnqualify.delete(original); @@ -155143,7 +156526,7 @@ var ts; */ function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 201 /* SyntaxKind.ObjectBindingPattern */: { + case 203 /* SyntaxKind.ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined @@ -155154,7 +156537,7 @@ var ts; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 202 /* SyntaxKind.ArrayBindingPattern */: { + case 204 /* SyntaxKind.ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; @@ -155247,11 +156630,11 @@ var ts; function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: return parent.name !== node; - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: return parent.propertyName !== node; - case 270 /* SyntaxKind.ImportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -155362,7 +156745,7 @@ var ts; var exportDeclaration = exportClause.parent; var typeExportSpecifiers = getTypeExportSpecifiers(exportSpecifier, context); if (typeExportSpecifiers.length === exportClause.elements.length) { - changes.insertModifierBefore(context.sourceFile, 152 /* SyntaxKind.TypeKeyword */, exportClause); + changes.insertModifierBefore(context.sourceFile, 154 /* SyntaxKind.TypeKeyword */, exportClause); } else { var valueExportDeclaration = ts.factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, @@ -155598,27 +156981,29 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span, program = context.program; - var info = getFixesInfo(context, errorCode, span.start, /*useAutoImportProvider*/ true); + var info = getFixInfos(context, errorCode, span.start, /*useAutoImportProvider*/ true); if (!info) return undefined; - var fixes = info.fixes, symbolName = info.symbolName, errorIdentifierText = info.errorIdentifierText; var quotePreference = ts.getQuotePreference(sourceFile, preferences); - return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, - /*includeSymbolNameInDescription*/ symbolName !== errorIdentifierText, quotePreference, program.getCompilerOptions()); }); + return info.map(function (_a) { + var fix = _a.fix, symbolName = _a.symbolName, errorIdentifierText = _a.errorIdentifierText; + return codeActionForFix(context, sourceFile, symbolName, fix, + /*includeSymbolNameInDescription*/ symbolName !== errorIdentifierText, quotePreference, program.getCompilerOptions()); + }); }, fixIds: [importFixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences, host = context.host; - var importAdder = createImportAdderWorker(sourceFile, program, /*useAutoImportProvider*/ true, preferences, host); + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences, host = context.host, cancellationToken = context.cancellationToken; + var importAdder = createImportAdderWorker(sourceFile, program, /*useAutoImportProvider*/ true, preferences, host, cancellationToken); codefix.eachDiagnostic(context, errorCodes, function (diag) { return importAdder.addImportFromDiagnostic(diag, context); }); return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, importAdder.writeFixes)); }, }); - function createImportAdder(sourceFile, program, preferences, host) { - return createImportAdderWorker(sourceFile, program, /*useAutoImportProvider*/ false, preferences, host); + function createImportAdder(sourceFile, program, preferences, host, cancellationToken) { + return createImportAdderWorker(sourceFile, program, /*useAutoImportProvider*/ false, preferences, host, cancellationToken); } codefix.createImportAdder = createImportAdder; - function createImportAdderWorker(sourceFile, program, useAutoImportProvider, preferences, host) { + function createImportAdderWorker(sourceFile, program, useAutoImportProvider, preferences, host, cancellationToken) { var compilerOptions = program.getCompilerOptions(); // Namespace fixes don't conflict, so just build a list. var addToNamespace = []; @@ -155629,27 +157014,26 @@ var ts; var newImports = new ts.Map(); return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes, hasFixes: hasFixes }; function addImportFromDiagnostic(diagnostic, context) { - var info = getFixesInfo(context, diagnostic.code, diagnostic.start, useAutoImportProvider); - if (!info || !info.fixes.length) + var info = getFixInfos(context, diagnostic.code, diagnostic.start, useAutoImportProvider); + if (!info || !info.length) return; - addImport(info); + addImport(ts.first(info)); } function addImportFromExportedSymbol(exportedSymbol, isValidTypeOnlyUseSite) { var moduleSymbol = ts.Debug.checkDefined(exportedSymbol.parent); var symbolName = ts.getNameForExportedSymbol(exportedSymbol, ts.getEmitScriptTarget(compilerOptions)); var checker = program.getTypeChecker(); var symbol = checker.getMergedSymbol(ts.skipAlias(exportedSymbol, checker)); - var exportInfo = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, /*isJsxTagName*/ false, host, program, preferences, useAutoImportProvider); + var exportInfo = getAllExportInfoForSymbol(sourceFile, symbol, symbolName, /*isJsxTagName*/ false, program, host, preferences, cancellationToken); var useRequire = shouldUseRequire(sourceFile, program); - var fix = getImportFixForSymbol(sourceFile, exportInfo, moduleSymbol, program, /*useNamespaceInfo*/ undefined, !!isValidTypeOnlyUseSite, useRequire, host, preferences); + var fix = getImportFixForSymbol(sourceFile, ts.Debug.checkDefined(exportInfo), moduleSymbol, program, /*useNamespaceInfo*/ undefined, !!isValidTypeOnlyUseSite, useRequire, host, preferences); if (fix) { - addImport({ fixes: [fix], symbolName: symbolName, errorIdentifierText: undefined }); + addImport({ fix: fix, symbolName: symbolName, errorIdentifierText: undefined }); } } function addImport(info) { var _a, _b; - var fixes = info.fixes, symbolName = info.symbolName; - var fix = ts.first(fixes); + var fix = info.fix, symbolName = info.symbolName; switch (fix.kind) { case 0 /* ImportFixKind.UseNamespace */: addToNamespace.push(fix); @@ -155816,11 +157200,12 @@ var ts; AddAsTypeOnly[AddAsTypeOnly["Required"] = 2] = "Required"; AddAsTypeOnly[AddAsTypeOnly["NotAllowed"] = 4] = "NotAllowed"; })(AddAsTypeOnly || (AddAsTypeOnly = {})); - function getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, symbolName, isJsxTagName, host, program, formatContext, position, preferences) { + function getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, symbolName, isJsxTagName, host, program, formatContext, position, preferences, cancellationToken) { var compilerOptions = program.getCompilerOptions(); var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name)) - ? [getSymbolExportInfoForSymbol(targetSymbol, moduleSymbol, program, host)] - : getAllReExportingModules(sourceFile, targetSymbol, moduleSymbol, symbolName, isJsxTagName, host, program, preferences, /*useAutoImportProvider*/ true); + ? [getSingleExportInfoForSymbol(targetSymbol, moduleSymbol, program, host)] + : getAllExportInfoForSymbol(sourceFile, targetSymbol, symbolName, isJsxTagName, program, host, preferences, cancellationToken); + ts.Debug.assertIsDefined(exportInfos); var useRequire = shouldUseRequire(sourceFile, program); var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); var fix = ts.Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, program, { symbolName: symbolName, position: position }, isValidTypeOnlyUseSite, useRequire, host, preferences)); @@ -155833,7 +157218,7 @@ var ts; codefix.getImportCompletionAction = getImportCompletionAction; function getPromoteTypeOnlyCompletionAction(sourceFile, symbolToken, program, host, formatContext, preferences) { var compilerOptions = program.getCompilerOptions(); - var symbolName = getSymbolName(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions); + var symbolName = ts.single(getSymbolNamesToImport(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions)); var fix = getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName, program); var includeSymbolNameInDescription = symbolName !== symbolToken.text; return fix && codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, includeSymbolNameInDescription, 1 /* QuotePreference.Double */, compilerOptions)); @@ -155848,7 +157233,16 @@ var ts; var description = _a.description, changes = _a.changes, commands = _a.commands; return { description: description, changes: changes, commands: commands }; } - function getSymbolExportInfoForSymbol(symbol, moduleSymbol, program, host) { + function getAllExportInfoForSymbol(importingFile, symbol, symbolName, preferCapitalized, program, host, preferences, cancellationToken) { + var getChecker = createGetChecker(program, host); + return ts.getExportInfoMap(importingFile, host, program, preferences, cancellationToken) + .search(importingFile.path, preferCapitalized, function (name) { return name === symbolName; }, function (info) { + if (ts.skipAlias(info[0].symbol, getChecker(info[0].isFromPackageJson)) === symbol) { + return info; + } + }); + } + function getSingleExportInfoForSymbol(symbol, moduleSymbol, program, host) { var _a, _b; var compilerOptions = program.getCompilerOptions(); var mainProgramInfo = getInfoWithChecker(program.getTypeChecker(), /*isFromPackageJson*/ false); @@ -155868,35 +157262,6 @@ var ts; } } } - function getAllReExportingModules(importingFile, targetSymbol, exportingModuleSymbol, symbolName, isJsxTagName, host, program, preferences, useAutoImportProvider) { - var result = []; - var compilerOptions = program.getCompilerOptions(); - var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { - return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); - }); - ts.forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { - var checker = program.getTypeChecker(); - // Don't import from a re-export when looking "up" like to `./index` or `../index`. - if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(importingFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { - return; - } - var defaultInfo = ts.getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions), isJsxTagName) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { - result.push({ symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: defaultInfo.exportKind, targetFlags: ts.skipAlias(defaultInfo.symbol, checker).flags, isFromPackageJson: isFromPackageJson }); - } - for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { - var exported = _a[_i]; - if (exported.name === symbolName && checker.getMergedSymbol(ts.skipAlias(exported, checker)) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { - result.push({ symbol: exported, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: 0 /* ExportKind.Named */, targetFlags: ts.skipAlias(exported, checker).flags, isFromPackageJson: isFromPackageJson }); - } - } - }); - return result; - function isImportable(program, moduleFile, isFromPackageJson) { - var _a; - return !moduleFile || ts.isImportableFile(program, importingFile, moduleFile, preferences, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host)); - } - } function getImportFixes(exportInfos, useNamespaceInfo, /** undefined only for missing JSX namespace */ isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap, fromCacheOnly) { @@ -155947,11 +157312,11 @@ var ts; function getTargetModuleFromNamespaceLikeImport(declaration, checker) { var _a; switch (declaration.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return checker.resolveExternalModuleName(declaration.initializer.arguments[0]); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return checker.getAliasedSymbol(declaration.symbol); - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport); return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol); default: @@ -155961,11 +157326,11 @@ var ts; function getNamespaceLikeImportText(declaration) { var _a, _b, _c; switch (declaration.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return declaration.name.text; - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return (_c = ts.tryCast((_b = declaration.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings, ts.isNamespaceImport)) === null || _c === void 0 ? void 0 : _c.name.text; default: return ts.Debug.assertNever(declaration); @@ -155992,12 +157357,12 @@ var ts; function tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, compilerOptions) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind, symbol = _a.symbol, targetFlags = _a.targetFlags; - if (importKind === 3 /* ImportKind.CommonJS */ || importKind === 2 /* ImportKind.Namespace */ || declaration.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { + if (importKind === 3 /* ImportKind.CommonJS */ || importKind === 2 /* ImportKind.Namespace */ || declaration.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */) { // These kinds of imports are not combinable with anything return undefined; } - if (declaration.kind === 254 /* SyntaxKind.VariableDeclaration */) { - return (importKind === 0 /* ImportKind.Named */ || importKind === 1 /* ImportKind.Default */) && declaration.name.kind === 201 /* SyntaxKind.ObjectBindingPattern */ + if (declaration.kind === 257 /* SyntaxKind.VariableDeclaration */) { + return (importKind === 0 /* ImportKind.Named */ || importKind === 1 /* ImportKind.Default */) && declaration.name.kind === 203 /* SyntaxKind.ObjectBindingPattern */ ? { kind: 2 /* ImportFixKind.AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, addAsTypeOnly: 4 /* AddAsTypeOnly.NotAllowed */ } : undefined; } @@ -156018,7 +157383,7 @@ var ts; )) return undefined; if (importKind === 0 /* ImportKind.Named */ && - (namedBindings === null || namedBindings === void 0 ? void 0 : namedBindings.kind) === 268 /* SyntaxKind.NamespaceImport */ // Cannot add a named import to a declaration that has a namespace import + (namedBindings === null || namedBindings === void 0 ? void 0 : namedBindings.kind) === 271 /* SyntaxKind.NamespaceImport */ // Cannot add a named import to a declaration that has a namespace import ) return undefined; return { @@ -156041,7 +157406,7 @@ var ts; (importMap || (importMap = ts.createMultiMap())).add(ts.getSymbolId(moduleSymbol), i.parent); } } - else if (i.kind === 266 /* SyntaxKind.ImportDeclaration */ || i.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { + else if (i.kind === 269 /* SyntaxKind.ImportDeclaration */ || i.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); if (moduleSymbol) { (importMap || (importMap = ts.createMultiMap())).add(ts.getSymbolId(moduleSymbol), i); @@ -156090,11 +157455,14 @@ var ts; // 5. Literally nothing to go on return true; } + function createGetChecker(program, host) { + return ts.memoizeOne(function (isFromPackageJson) { return isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker(); }); + } function getNewImportFixes(program, sourceFile, position, isValidTypeOnlyUseSite, useRequire, exportInfo, host, preferences, fromCacheOnly) { var isJs = ts.isSourceFileJS(sourceFile); var compilerOptions = program.getCompilerOptions(); var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); - var getChecker = ts.memoizeOne(function (isFromPackageJson) { return isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker(); }); + var getChecker = createGetChecker(program, host); var rejectNodeModulesRelativePaths = ts.moduleResolutionUsesNodeModules(ts.getEmitModuleResolutionKind(compilerOptions)); var getModuleSpecifiers = fromCacheOnly ? function (moduleSymbol) { return ({ moduleSpecifiers: ts.moduleSpecifiers.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false }); } @@ -156138,7 +157506,7 @@ var ts; return { kind: 3 /* ImportFixKind.AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, addAsTypeOnly: addAsTypeOnly, useRequire: useRequire }; } } - function getFixesInfo(context, errorCode, pos, useAutoImportProvider) { + function getFixInfos(context, errorCode, pos, useAutoImportProvider) { var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); var info; if (errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { @@ -156148,19 +157516,23 @@ var ts; return undefined; } else if (errorCode === ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code) { - var symbolName_1 = getSymbolName(context.sourceFile, context.program.getTypeChecker(), symbolToken, context.program.getCompilerOptions()); + var symbolName_1 = ts.single(getSymbolNamesToImport(context.sourceFile, context.program.getTypeChecker(), symbolToken, context.program.getCompilerOptions())); var fix = getTypeOnlyPromotionFix(context.sourceFile, symbolToken, symbolName_1, context.program); - return fix && { fixes: [fix], symbolName: symbolName_1, errorIdentifierText: symbolToken.text }; + return fix && [{ fix: fix, symbolName: symbolName_1, errorIdentifierText: symbolToken.text }]; } else { info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider); } var packageJsonImportFilter = ts.createPackageJsonImportFilter(context.sourceFile, context.preferences, context.host); - return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, packageJsonImportFilter, context.host) }); + return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host); } - function sortFixes(fixes, sourceFile, program, packageJsonImportFilter, host) { + function sortFixInfo(fixes, sourceFile, program, packageJsonImportFilter, host) { var _toPath = function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), ts.hostGetCanonicalFileName(host)); }; - return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, _toPath); }); + return ts.sort(fixes, function (a, b) { + return ts.compareBooleans(!!a.isJsxNamespaceFix, !!b.isJsxNamespaceFix) || + ts.compareValues(a.fix.kind, b.fix.kind) || + compareModuleSpecifiers(a.fix, b.fix, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, _toPath); + }); } function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host) { if (!ts.some(fixes)) @@ -156211,7 +157583,6 @@ var ts; return 0 /* Comparison.EqualTo */; } function getFixesInfoForUMDImport(_a, token) { - var _b; var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; var checker = program.getTypeChecker(); var umdSymbol = getUmdSymbol(token, checker); @@ -156223,7 +157594,7 @@ var ts; var useRequire = shouldUseRequire(sourceFile, program); var position = ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined; var fixes = getImportFixes(exportInfo, position ? { position: position, symbolName: symbolName } : undefined, /*isValidTypeOnlyUseSite*/ false, useRequire, program, sourceFile, host, preferences).fixes; - return { fixes: fixes, symbolName: symbolName, errorIdentifierText: (_b = ts.tryCast(token, ts.isIdentifier)) === null || _b === void 0 ? void 0 : _b.text }; + return fixes.map(function (fix) { var _a; return ({ fix: fix, symbolName: symbolName, errorIdentifierText: (_a = ts.tryCast(token, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text }); }); } function getUmdSymbol(token, checker) { // try the identifier to see if it is the umd symbol @@ -156284,19 +157655,20 @@ var ts; var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; var checker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); - var symbolName = getSymbolName(sourceFile, checker, symbolToken, compilerOptions); - // "default" is a keyword and not a legal identifier for the import, but appears as an identifier. - if (symbolName === "default" /* InternalSymbolName.Default */) { - return undefined; - } - var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(symbolToken); - var useRequire = shouldUseRequire(sourceFile, program); - var exportInfo = getExportInfos(symbolName, ts.isJSXTagName(symbolToken), ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences); - var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfo.entries(), function (_a) { - var _ = _a[0], exportInfos = _a[1]; - return getImportFixes(exportInfos, { symbolName: symbolName, position: symbolToken.getStart(sourceFile) }, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes; - })); - return { fixes: fixes, symbolName: symbolName, errorIdentifierText: symbolToken.text }; + return ts.flatMap(getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions), function (symbolName) { + // "default" is a keyword and not a legal identifier for the import, but appears as an identifier. + if (symbolName === "default" /* InternalSymbolName.Default */) { + return undefined; + } + var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(symbolToken); + var useRequire = shouldUseRequire(sourceFile, program); + var exportInfo = getExportInfos(symbolName, ts.isJSXTagName(symbolToken), ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences); + var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfo.entries(), function (_a) { + var _ = _a[0], exportInfos = _a[1]; + return getImportFixes(exportInfos, { symbolName: symbolName, position: symbolToken.getStart(sourceFile) }, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes; + })); + return fixes.map(function (fix) { return ({ fix: fix, symbolName: symbolName, errorIdentifierText: symbolToken.text, isJsxNamespaceFix: symbolName !== symbolToken.text }); }); + }); } function getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName, program) { var checker = program.getTypeChecker(); @@ -156308,15 +157680,16 @@ var ts; return undefined; return { kind: 4 /* ImportFixKind.PromoteTypeOnly */, typeOnlyAliasDeclaration: typeOnlyAliasDeclaration }; } - function getSymbolName(sourceFile, checker, symbolToken, compilerOptions) { + function getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions) { var parent = symbolToken.parent; if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && ts.jsxModeNeedsExplicitImport(compilerOptions.jsx)) { var jsxNamespace = checker.getJsxNamespace(sourceFile); if (needsJsxNamespaceFix(jsxNamespace, symbolToken, checker)) { - return jsxNamespace; + var needsComponentNameFix = !ts.isIntrinsicJsxName(symbolToken.text) && !checker.resolveName(symbolToken.text, symbolToken, 111551 /* SymbolFlags.Value */, /*excludeGlobals*/ false); + return needsComponentNameFix ? [symbolToken.text, jsxNamespace] : [jsxNamespace]; } } - return symbolToken.text; + return [symbolToken.text]; } function needsJsxNamespaceFix(jsxNamespace, symbolToken, checker) { if (ts.isIntrinsicJsxName(symbolToken.text)) @@ -156425,7 +157798,7 @@ var ts; case 4 /* ImportFixKind.PromoteTypeOnly */: { var typeOnlyAliasDeclaration = fix.typeOnlyAliasDeclaration; var promotedDeclaration = promoteFromTypeOnly(changes, typeOnlyAliasDeclaration, compilerOptions, sourceFile); - return promotedDeclaration.kind === 270 /* SyntaxKind.ImportSpecifier */ + return promotedDeclaration.kind === 273 /* SyntaxKind.ImportSpecifier */ ? [ts.Diagnostics.Remove_type_from_import_of_0_from_1, symbolName, getModuleSpecifierText(promotedDeclaration.parent.parent)] : [ts.Diagnostics.Remove_type_from_import_declaration_from_0, getModuleSpecifierText(promotedDeclaration)]; } @@ -156435,7 +157808,7 @@ var ts; } function getModuleSpecifierText(promotedDeclaration) { var _a, _b; - return promotedDeclaration.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ + return promotedDeclaration.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ ? ((_b = ts.tryCast((_a = ts.tryCast(promotedDeclaration.moduleReference, ts.isExternalModuleReference)) === null || _a === void 0 ? void 0 : _a.expression, ts.isStringLiteralLike)) === null || _b === void 0 ? void 0 : _b.text) || promotedDeclaration.moduleReference.getText() : ts.cast(promotedDeclaration.parent.moduleSpecifier, ts.isStringLiteral).text; } @@ -156443,7 +157816,7 @@ var ts; // See comment in `doAddExistingFix` on constant with the same name. var convertExistingToTypeOnly = compilerOptions.preserveValueImports && compilerOptions.isolatedModules; switch (aliasDeclaration.kind) { - case 270 /* SyntaxKind.ImportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: if (aliasDeclaration.isTypeOnly) { if (aliasDeclaration.parent.elements.length > 1 && ts.OrganizeImports.importSpecifiersAreSorted(aliasDeclaration.parent.elements)) { changes.delete(sourceFile, aliasDeclaration); @@ -156461,13 +157834,13 @@ var ts; promoteImportClause(aliasDeclaration.parent.parent); return aliasDeclaration.parent.parent; } - case 267 /* SyntaxKind.ImportClause */: + case 270 /* SyntaxKind.ImportClause */: promoteImportClause(aliasDeclaration); return aliasDeclaration; - case 268 /* SyntaxKind.NamespaceImport */: + case 271 /* SyntaxKind.NamespaceImport */: promoteImportClause(aliasDeclaration.parent); return aliasDeclaration.parent; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: changes.deleteRange(sourceFile, aliasDeclaration.getChildAt(1)); return aliasDeclaration; default: @@ -156479,7 +157852,7 @@ var ts; var namedImports = ts.tryCast(importClause.namedBindings, ts.isNamedImports); if (namedImports && namedImports.elements.length > 1) { if (ts.OrganizeImports.importSpecifiersAreSorted(namedImports.elements) && - aliasDeclaration.kind === 270 /* SyntaxKind.ImportSpecifier */ && + aliasDeclaration.kind === 273 /* SyntaxKind.ImportSpecifier */ && namedImports.elements.indexOf(aliasDeclaration) !== 0) { // The import specifier being promoted will be the only non-type-only, // import in the NamedImports, so it should be moved to the front. @@ -156489,7 +157862,7 @@ var ts; for (var _i = 0, _a = namedImports.elements; _i < _a.length; _i++) { var element = _a[_i]; if (element !== aliasDeclaration && !element.isTypeOnly) { - changes.insertModifierBefore(sourceFile, 152 /* SyntaxKind.TypeKeyword */, element); + changes.insertModifierBefore(sourceFile, 154 /* SyntaxKind.TypeKeyword */, element); } } } @@ -156498,7 +157871,7 @@ var ts; } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, compilerOptions) { var _a; - if (clause.kind === 201 /* SyntaxKind.ObjectBindingPattern */) { + if (clause.kind === 203 /* SyntaxKind.ObjectBindingPattern */) { if (defaultImport) { addElementToBindingPattern(clause, defaultImport.name, "default"); } @@ -156559,7 +157932,7 @@ var ts; if (convertExistingToTypeOnly && existingSpecifiers) { for (var _d = 0, existingSpecifiers_1 = existingSpecifiers; _d < existingSpecifiers_1.length; _d++) { var specifier = existingSpecifiers_1[_d]; - changes.insertModifierBefore(sourceFile, 152 /* SyntaxKind.TypeKeyword */, specifier); + changes.insertModifierBefore(sourceFile, 154 /* SyntaxKind.TypeKeyword */, specifier); } } } @@ -156734,7 +158107,7 @@ var ts; var related = ts.find(diag.relatedInformation, function (related) { return related.code === ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code; }); if (related === undefined || related.file === undefined || related.start === undefined || related.length === undefined) return; - var declaration = findAncestorMatchingSpan(related.file, ts.createTextSpan(related.start, related.length)); + var declaration = codefix.findAncestorMatchingSpan(related.file, ts.createTextSpan(related.start, related.length)); if (declaration === undefined) return; if (ts.isIdentifier(declaration) && ts.isTypeParameterDeclaration(declaration.parent)) { @@ -156768,14 +158141,6 @@ var ts; } } } - function findAncestorMatchingSpan(sourceFile, span) { - var end = ts.textSpanEnd(span); - var token = ts.getTokenAtPosition(sourceFile, span.start); - while (token.end < end) { - token = token.parent; - } - return token; - } function tryGetConstraintFromDiagnosticMessage(messageText) { var _a = ts.flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || [], _ = _a[0], constraint = _a[1]; return constraint; @@ -156919,7 +158284,7 @@ var ts; accessibilityModifier ? accessibilityModifier.end : lastDecorator ? ts.skipTrivia(sourceFile.text, lastDecorator.end) : classElement.getStart(sourceFile); var options = accessibilityModifier || staticModifier || abstractModifier ? { prefix: " " } : { suffix: " " }; - changeTracker.insertModifierAt(sourceFile, modifierPos, 159 /* SyntaxKind.OverrideKeyword */, options); + changeTracker.insertModifierAt(sourceFile, modifierPos, 161 /* SyntaxKind.OverrideKeyword */, options); } function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { var classElement = findContainerClassElementLike(sourceFile, pos); @@ -156933,13 +158298,13 @@ var ts; } function isClassElementLikeHasJSDoc(node) { switch (node.kind) { - case 171 /* SyntaxKind.Constructor */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 173 /* SyntaxKind.Constructor */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return true; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return ts.isParameterPropertyDeclaration(node, node.parent); default: return false; @@ -157051,6 +158416,143 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixImportNonExportedMember"; + var errorCodes = [ + ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixId], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span, program = context.program; + var info = getInfo(sourceFile, span.start, program); + if (info === undefined) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, program, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId, ts.Diagnostics.Export_all_referenced_locals)]; + }, + getAllCodeActions: function (context) { + var program = context.program; + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var exports = new ts.Map(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, program); + if (info === undefined) + return undefined; + var exportName = info.exportName, node = info.node, moduleSourceFile = info.moduleSourceFile; + if (tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly) === undefined && ts.canHaveExportModifier(node)) { + changes.insertExportModifier(moduleSourceFile, node); + } + else { + var moduleExports = exports.get(moduleSourceFile) || { typeOnlyExports: [], exports: [] }; + if (exportName.isTypeOnly) { + moduleExports.typeOnlyExports.push(exportName); + } + else { + moduleExports.exports.push(exportName); + } + exports.set(moduleSourceFile, moduleExports); + } + }); + exports.forEach(function (moduleExports, moduleSourceFile) { + var exportDeclaration = tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ true); + if (exportDeclaration && exportDeclaration.isTypeOnly) { + doChanges(changes, program, moduleSourceFile, moduleExports.typeOnlyExports, exportDeclaration); + doChanges(changes, program, moduleSourceFile, moduleExports.exports, tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ false)); + } + else { + doChanges(changes, program, moduleSourceFile, __spreadArray(__spreadArray([], moduleExports.exports, true), moduleExports.typeOnlyExports, true), exportDeclaration); + } + }); + })); + } + }); + function getInfo(sourceFile, pos, program) { + var _a; + var token = ts.getTokenAtPosition(sourceFile, pos); + if (ts.isIdentifier(token)) { + var importDeclaration = ts.findAncestor(token, ts.isImportDeclaration); + if (importDeclaration === undefined) + return undefined; + var moduleSpecifier = ts.isStringLiteral(importDeclaration.moduleSpecifier) ? importDeclaration.moduleSpecifier.text : undefined; + if (moduleSpecifier === undefined) + return undefined; + var resolvedModule = ts.getResolvedModule(sourceFile, moduleSpecifier, /*mode*/ undefined); + if (resolvedModule === undefined) + return undefined; + var moduleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName); + if (moduleSourceFile === undefined || ts.isSourceFileFromLibrary(program, moduleSourceFile)) + return undefined; + var moduleSymbol = moduleSourceFile.symbol; + var locals = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals; + if (locals === undefined) + return undefined; + var localSymbol = locals.get(token.escapedText); + if (localSymbol === undefined) + return undefined; + var node = getNodeOfSymbol(localSymbol); + if (node === undefined) + return undefined; + var exportName = { node: token, isTypeOnly: ts.isTypeDeclaration(node) }; + return { exportName: exportName, node: node, moduleSourceFile: moduleSourceFile, moduleSpecifier: moduleSpecifier }; + } + return undefined; + } + function doChange(changes, program, _a) { + var exportName = _a.exportName, node = _a.node, moduleSourceFile = _a.moduleSourceFile; + var exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly); + if (exportDeclaration) { + updateExport(changes, program, moduleSourceFile, exportDeclaration, [exportName]); + } + else if (ts.canHaveExportModifier(node)) { + changes.insertExportModifier(moduleSourceFile, node); + } + else { + createExport(changes, program, moduleSourceFile, [exportName]); + } + } + function doChanges(changes, program, sourceFile, moduleExports, node) { + if (ts.length(moduleExports)) { + if (node) { + updateExport(changes, program, sourceFile, node, moduleExports); + } + else { + createExport(changes, program, sourceFile, moduleExports); + } + } + } + function tryGetExportDeclaration(sourceFile, isTypeOnly) { + var predicate = function (node) { + return ts.isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly); + }; + return ts.findLast(sourceFile.statements, predicate); + } + function updateExport(changes, program, sourceFile, node, names) { + var namedExports = node.exportClause && ts.isNamedExports(node.exportClause) ? node.exportClause.elements : ts.factory.createNodeArray([]); + var allowTypeModifier = !node.isTypeOnly && !!(program.getCompilerOptions().isolatedModules || ts.find(namedExports, function (e) { return e.isTypeOnly; })); + changes.replaceNode(sourceFile, node, ts.factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, ts.factory.createNamedExports(ts.factory.createNodeArray(__spreadArray(__spreadArray([], namedExports, true), createExportSpecifiers(names, allowTypeModifier), true), /*hasTrailingComma*/ namedExports.hasTrailingComma)), node.moduleSpecifier, node.assertClause)); + } + function createExport(changes, program, sourceFile, names) { + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ !!program.getCompilerOptions().isolatedModules)), /*moduleSpecifier*/ undefined, /*assertClause*/ undefined)); + } + function createExportSpecifiers(names, allowTypeModifier) { + return ts.factory.createNodeArray(ts.map(names, function (n) { return ts.factory.createExportSpecifier(allowTypeModifier && n.isTypeOnly, /*propertyName*/ undefined, n.node); })); + } + function getNodeOfSymbol(symbol) { + if (symbol.valueDeclaration === undefined) { + return ts.firstOrUndefined(symbol.declarations); + } + var declaration = symbol.valueDeclaration; + var variableStatement = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : undefined; + return variableStatement && ts.length(variableStatement.declarationList.declarations) === 1 ? variableStatement : declaration; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -157071,7 +158573,7 @@ var ts; }); function getNamedTupleMember(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - return ts.findAncestor(token, function (t) { return t.kind === 197 /* SyntaxKind.NamedTupleMember */; }); + return ts.findAncestor(token, function (t) { return t.kind === 199 /* SyntaxKind.NamedTupleMember */; }); } function doChange(changes, sourceFile, namedTupleMember) { if (!namedTupleMember) { @@ -157080,11 +158582,11 @@ var ts; var unwrappedType = namedTupleMember.type; var sawOptional = false; var sawRest = false; - while (unwrappedType.kind === 185 /* SyntaxKind.OptionalType */ || unwrappedType.kind === 186 /* SyntaxKind.RestType */ || unwrappedType.kind === 191 /* SyntaxKind.ParenthesizedType */) { - if (unwrappedType.kind === 185 /* SyntaxKind.OptionalType */) { + while (unwrappedType.kind === 187 /* SyntaxKind.OptionalType */ || unwrappedType.kind === 188 /* SyntaxKind.RestType */ || unwrappedType.kind === 193 /* SyntaxKind.ParenthesizedType */) { + if (unwrappedType.kind === 187 /* SyntaxKind.OptionalType */) { sawOptional = true; } - else if (unwrappedType.kind === 186 /* SyntaxKind.RestType */) { + else if (unwrappedType.kind === 188 /* SyntaxKind.RestType */) { sawRest = true; } unwrappedType = unwrappedType.type; @@ -157355,7 +158857,7 @@ var ts; if (isFunctionType) { var sig = checker.getSignatureFromDeclaration(declaration); if (sig) { - if (ts.hasSyntacticModifier(declaration, 256 /* ModifierFlags.Async */)) { + if (ts.hasSyntacticModifier(declaration, 512 /* ModifierFlags.Async */)) { exprType = checker.createPromiseType(exprType); } var newSig = checker.createSignature(declaration, sig.typeParameters, sig.thisParameter, sig.parameters, exprType, @@ -157399,19 +158901,19 @@ var ts; } function getVariableLikeInitializer(declaration) { switch (declaration.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: - case 164 /* SyntaxKind.Parameter */: - case 203 /* SyntaxKind.BindingElement */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 296 /* SyntaxKind.PropertyAssignment */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 166 /* SyntaxKind.Parameter */: + case 205 /* SyntaxKind.BindingElement */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 299 /* SyntaxKind.PropertyAssignment */: return declaration.initializer; - case 285 /* SyntaxKind.JsxAttribute */: + case 288 /* SyntaxKind.JsxAttribute */: return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined); - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - case 166 /* SyntaxKind.PropertySignature */: - case 299 /* SyntaxKind.EnumMember */: - case 347 /* SyntaxKind.JSDocPropertyTag */: - case 340 /* SyntaxKind.JSDocParameterTag */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: + case 168 /* SyntaxKind.PropertySignature */: + case 302 /* SyntaxKind.EnumMember */: + case 350 /* SyntaxKind.JSDocPropertyTag */: + case 343 /* SyntaxKind.JSDocParameterTag */: return undefined; } } @@ -157465,6 +158967,15 @@ var ts; ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, ts.Diagnostics.Cannot_find_name_0.code ]; + var InfoKind; + (function (InfoKind) { + InfoKind[InfoKind["TypeLikeDeclaration"] = 0] = "TypeLikeDeclaration"; + InfoKind[InfoKind["Enum"] = 1] = "Enum"; + InfoKind[InfoKind["Function"] = 2] = "Function"; + InfoKind[InfoKind["ObjectLiteral"] = 3] = "ObjectLiteral"; + InfoKind[InfoKind["JsxAttributes"] = 4] = "JsxAttributes"; + InfoKind[InfoKind["Signature"] = 5] = "Signature"; + })(InfoKind || (InfoKind = {})); codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { @@ -157473,19 +158984,19 @@ var ts; if (!info) { return undefined; } - if (info.kind === 3 /* InfoKind.ObjectLiteral */) { + if (info.kind === InfoKind.ObjectLiteral) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addObjectLiteralProperties(t, context, info); }); return [codefix.createCodeFixAction(fixMissingProperties, changes, ts.Diagnostics.Add_missing_properties, fixMissingProperties, ts.Diagnostics.Add_all_missing_properties)]; } - if (info.kind === 4 /* InfoKind.JsxAttributes */) { + if (info.kind === InfoKind.JsxAttributes) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addJsxAttributes(t, context, info); }); return [codefix.createCodeFixAction(fixMissingAttributes, changes, ts.Diagnostics.Add_missing_attributes, fixMissingAttributes, ts.Diagnostics.Add_all_missing_attributes)]; } - if (info.kind === 2 /* InfoKind.Function */) { + if (info.kind === InfoKind.Function || info.kind === InfoKind.Signature) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addFunctionDeclaration(t, context, info); }); return [codefix.createCodeFixAction(fixMissingFunctionDeclaration, changes, [ts.Diagnostics.Add_missing_function_declaration_0, info.token.text], fixMissingFunctionDeclaration, ts.Diagnostics.Add_all_missing_function_declarations)]; } - if (info.kind === 1 /* InfoKind.Enum */) { + if (info.kind === InfoKind.Enum) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), info); }); return [codefix.createCodeFixAction(fixMissingMember, changes, [ts.Diagnostics.Add_missing_enum_member_0, info.token.text], fixMissingMember, ts.Diagnostics.Add_all_missing_members)]; } @@ -157503,20 +159014,20 @@ var ts; if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) { return; } - if (fixId === fixMissingFunctionDeclaration && info.kind === 2 /* InfoKind.Function */) { + if (fixId === fixMissingFunctionDeclaration && (info.kind === InfoKind.Function || info.kind === InfoKind.Signature)) { addFunctionDeclaration(changes, context, info); } - else if (fixId === fixMissingProperties && info.kind === 3 /* InfoKind.ObjectLiteral */) { + else if (fixId === fixMissingProperties && info.kind === InfoKind.ObjectLiteral) { addObjectLiteralProperties(changes, context, info); } - else if (fixId === fixMissingAttributes && info.kind === 4 /* InfoKind.JsxAttributes */) { + else if (fixId === fixMissingAttributes && info.kind === InfoKind.JsxAttributes) { addJsxAttributes(changes, context, info); } else { - if (info.kind === 1 /* InfoKind.Enum */) { + if (info.kind === InfoKind.Enum) { addEnumMemberDeclaration(changes, checker, info); } - if (info.kind === 0 /* InfoKind.TypeLikeDeclaration */) { + if (info.kind === InfoKind.TypeLikeDeclaration) { var parentDeclaration = info.parentDeclaration, token_1 = info.token; var infos = ts.getOrUpdate(typeDeclToMembers, parentDeclaration, function () { return []; }); if (!infos.some(function (i) { return i.token.text === token_1.text; })) { @@ -157560,14 +159071,6 @@ var ts; })); }, }); - var InfoKind; - (function (InfoKind) { - InfoKind[InfoKind["TypeLikeDeclaration"] = 0] = "TypeLikeDeclaration"; - InfoKind[InfoKind["Enum"] = 1] = "Enum"; - InfoKind[InfoKind["Function"] = 2] = "Function"; - InfoKind[InfoKind["ObjectLiteral"] = 3] = "ObjectLiteral"; - InfoKind[InfoKind["JsxAttributes"] = 4] = "JsxAttributes"; - })(InfoKind || (InfoKind = {})); function getInfo(sourceFile, tokenPos, errorCode, checker, program) { // The identifier of the missing property. eg: // this.missing = 1; @@ -157580,7 +159083,7 @@ var ts; var argIndex = ts.findIndex(parent.parent.arguments, function (arg) { return arg === parent; }); if (argIndex < 0) return undefined; - var signature = ts.singleOrUndefined(checker.getSignaturesOfType(checker.getTypeAtLocation(parent.parent.expression), 0 /* SignatureKind.Call */)); + var signature = checker.getResolvedSignature(parent.parent); if (!(signature && signature.declaration && signature.parameters[argIndex])) return undefined; var param = signature.parameters[argIndex].valueDeclaration; @@ -157589,7 +159092,7 @@ var ts; var properties = ts.arrayFrom(checker.getUnmatchedProperties(checker.getTypeAtLocation(parent), checker.getParameterType(signature, argIndex), /* requireOptionalProperties */ false, /* matchDiscriminantProperties */ false)); if (!ts.length(properties)) return undefined; - return { kind: 3 /* InfoKind.ObjectLiteral */, token: param.name, properties: properties, parentDeclaration: parent }; + return { kind: InfoKind.ObjectLiteral, token: param.name, properties: properties, parentDeclaration: parent }; } if (!ts.isMemberName(token)) return undefined; @@ -157597,17 +159100,26 @@ var ts; var properties = ts.arrayFrom(checker.getUnmatchedProperties(checker.getTypeAtLocation(parent.initializer), checker.getTypeAtLocation(token), /* requireOptionalProperties */ false, /* matchDiscriminantProperties */ false)); if (!ts.length(properties)) return undefined; - return { kind: 3 /* InfoKind.ObjectLiteral */, token: token, properties: properties, parentDeclaration: parent.initializer }; + return { kind: InfoKind.ObjectLiteral, token: token, properties: properties, parentDeclaration: parent.initializer }; } if (ts.isIdentifier(token) && ts.isJsxOpeningLikeElement(token.parent)) { var target = ts.getEmitScriptTarget(program.getCompilerOptions()); var attributes = getUnmatchedAttributes(checker, target, token.parent); if (!ts.length(attributes)) return undefined; - return { kind: 4 /* InfoKind.JsxAttributes */, token: token, attributes: attributes, parentDeclaration: token.parent }; + return { kind: InfoKind.JsxAttributes, token: token, attributes: attributes, parentDeclaration: token.parent }; } - if (ts.isIdentifier(token) && ts.isCallExpression(parent) && parent.expression === token) { - return { kind: 2 /* InfoKind.Function */, token: token, call: parent, sourceFile: sourceFile, modifierFlags: 0 /* ModifierFlags.None */, parentDeclaration: sourceFile }; + if (ts.isIdentifier(token)) { + var type = checker.getContextualType(token); + if (type && ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */) { + var signature = ts.firstOrUndefined(checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */)); + if (signature === undefined) + return undefined; + return { kind: InfoKind.Signature, token: token, signature: signature, sourceFile: sourceFile, parentDeclaration: findScope(token) }; + } + if (ts.isCallExpression(parent) && parent.expression === token) { + return { kind: InfoKind.Function, token: token, call: parent, sourceFile: sourceFile, modifierFlags: 0 /* ModifierFlags.None */, parentDeclaration: findScope(token) }; + } } if (!ts.isPropertyAccessExpression(parent)) return undefined; @@ -157618,14 +159130,14 @@ var ts; if (ts.isIdentifier(token) && ts.isCallExpression(parent.parent)) { var moduleDeclaration = ts.find(symbol.declarations, ts.isModuleDeclaration); var moduleDeclarationSourceFile = moduleDeclaration === null || moduleDeclaration === void 0 ? void 0 : moduleDeclaration.getSourceFile(); - if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { - return { kind: 2 /* InfoKind.Function */, token: token, call: parent.parent, sourceFile: sourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleDeclaration }; + if (moduleDeclaration && moduleDeclarationSourceFile && !ts.isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { + return { kind: InfoKind.Function, token: token, call: parent.parent, sourceFile: sourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleDeclaration }; } var moduleSourceFile = ts.find(symbol.declarations, ts.isSourceFile); if (sourceFile.commonJsModuleIndicator) return undefined; - if (moduleSourceFile && !isSourceFileFromLibrary(program, moduleSourceFile)) { - return { kind: 2 /* InfoKind.Function */, token: token, call: parent.parent, sourceFile: moduleSourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleSourceFile }; + if (moduleSourceFile && !ts.isSourceFileFromLibrary(program, moduleSourceFile)) { + return { kind: InfoKind.Function, token: token, call: parent.parent, sourceFile: moduleSourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleSourceFile }; } } var classDeclaration = ts.find(symbol.declarations, ts.isClassLike); @@ -157634,7 +159146,7 @@ var ts; return undefined; // Prefer to change the class instead of the interface if they are merged var declaration = classDeclaration || ts.find(symbol.declarations, function (d) { return ts.isInterfaceDeclaration(d) || ts.isTypeLiteralNode(d); }); - if (declaration && !isSourceFileFromLibrary(program, declaration.getSourceFile())) { + if (declaration && !ts.isSourceFileFromLibrary(program, declaration.getSourceFile())) { var makeStatic = !ts.isTypeLiteralNode(declaration) && (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); if (makeStatic && (ts.isPrivateIdentifier(token) || ts.isInterfaceDeclaration(declaration))) return undefined; @@ -157643,17 +159155,14 @@ var ts; (makeStatic ? 32 /* ModifierFlags.Static */ : 0 /* ModifierFlags.None */) | (ts.startsWithUnderscore(token.text) ? 8 /* ModifierFlags.Private */ : 0 /* ModifierFlags.None */); var isJSFile = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); - return { kind: 0 /* InfoKind.TypeLikeDeclaration */, token: token, call: call, modifierFlags: modifierFlags, parentDeclaration: declaration, declSourceFile: declSourceFile, isJSFile: isJSFile }; + return { kind: InfoKind.TypeLikeDeclaration, token: token, call: call, modifierFlags: modifierFlags, parentDeclaration: declaration, declSourceFile: declSourceFile, isJSFile: isJSFile }; } var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); - if (enumDeclaration && !ts.isPrivateIdentifier(token) && !isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { - return { kind: 1 /* InfoKind.Enum */, token: token, parentDeclaration: enumDeclaration }; + if (enumDeclaration && !(leftExpressionType.flags & 1056 /* TypeFlags.EnumLike */) && !ts.isPrivateIdentifier(token) && !ts.isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { + return { kind: InfoKind.Enum, token: token, parentDeclaration: enumDeclaration }; } return undefined; } - function isSourceFileFromLibrary(program, node) { - return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); - } function getActionsForMissingMemberDeclaration(context, info) { return info.isJSFile ? ts.singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) : createActionsForAddMissingMemberInTypeScriptFile(context, info); @@ -157674,7 +159183,7 @@ var ts; function addMissingMemberInJs(changeTracker, sourceFile, classDeclaration, token, makeStatic) { var tokenName = token.text; if (makeStatic) { - if (classDeclaration.kind === 226 /* SyntaxKind.ClassExpression */) { + if (classDeclaration.kind === 228 /* SyntaxKind.ClassExpression */) { return; } var className = classDeclaration.name.getText(); @@ -157725,7 +159234,7 @@ var ts; } function getTypeNode(checker, node, token) { var typeNode; - if (token.parent.parent.kind === 221 /* SyntaxKind.BinaryExpression */) { + if (token.parent.parent.kind === 223 /* SyntaxKind.BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); @@ -157735,7 +159244,7 @@ var ts; var contextualType = checker.getContextualType(token.parent); typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, 1 /* NodeBuilderFlags.NoTruncation */) : undefined; } - return typeNode || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */); + return typeNode || ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */); } function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, typeNode, modifierFlags) { var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; @@ -157763,7 +159272,7 @@ var ts; } function createAddIndexSignatureAction(context, sourceFile, node, tokenName, typeNode) { // Index signatures cannot have the static modifier. - var stringTypeNode = ts.factory.createKeywordTypeNode(150 /* SyntaxKind.StringKeyword */); + var stringTypeNode = ts.factory.createKeywordTypeNode(152 /* SyntaxKind.StringKeyword */); var indexingParameter = ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "x", @@ -157794,7 +159303,7 @@ var ts; } function addMethodDeclaration(context, changes, callExpression, name, modifierFlags, parentDeclaration, sourceFile) { var importAdder = codefix.createImportAdder(sourceFile, context.program, context.preferences, context.host); - var kind = ts.isClassLike(parentDeclaration) ? 169 /* SyntaxKind.MethodDeclaration */ : 168 /* SyntaxKind.MethodSignature */; + var kind = ts.isClassLike(parentDeclaration) ? 171 /* SyntaxKind.MethodDeclaration */ : 170 /* SyntaxKind.MethodSignature */; var signatureDeclaration = codefix.createSignatureDeclarationFromCallExpression(kind, context, importAdder, callExpression, name, modifierFlags, parentDeclaration); var containingMethodDeclaration = tryGetContainingMethodDeclaration(parentDeclaration, callExpression); if (containingMethodDeclaration) { @@ -157823,9 +159332,17 @@ var ts; }); } function addFunctionDeclaration(changes, context, info) { + var quotePreference = ts.getQuotePreference(context.sourceFile, context.preferences); var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); - var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(256 /* SyntaxKind.FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration); - changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); + var functionDeclaration = info.kind === InfoKind.Function + ? codefix.createSignatureDeclarationFromCallExpression(259 /* SyntaxKind.FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration) + : codefix.createSignatureDeclarationFromSignature(259 /* SyntaxKind.FunctionDeclaration */, context, quotePreference, info.signature, codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), info.token, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ undefined, importAdder); + if (functionDeclaration === undefined) { + ts.Debug.fail("fixMissingFunctionDeclaration codefix got unexpected error."); + } + ts.isReturnStatement(info.parentDeclaration) + ? changes.insertNodeBefore(info.sourceFile, info.parentDeclaration, functionDeclaration, /*blankLineBetween*/ true) + : changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); importAdder.writeFixes(changes); } function addJsxAttributes(changes, context, info) { @@ -157921,7 +159438,7 @@ var ts; var signature = checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (signature === undefined) return createUndefined(); - var func = codefix.createSignatureDeclarationFromSignature(213 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ enclosingDeclaration, importAdder); + var func = codefix.createSignatureDeclarationFromSignature(215 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ enclosingDeclaration, importAdder); return func !== null && func !== void 0 ? func : createUndefined(); } if (ts.getObjectFlags(type) & 1 /* ObjectFlags.Class */) { @@ -157975,14 +159492,21 @@ var ts; return declaration && declaration.parent === node ? declaration : undefined; } function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) { - if (ts.isTransientSymbol(symbol) && symbol.nameType && symbol.nameType.flags & 8192 /* TypeFlags.UniqueESSymbol */) { - var expression = checker.symbolToExpression(symbol.nameType.symbol, 111551 /* SymbolFlags.Value */, symbol.valueDeclaration, 1048576 /* NodeBuilderFlags.AllowUniqueESSymbolType */); - if (expression) { - return ts.factory.createComputedPropertyName(expression); - } + if (ts.isTransientSymbol(symbol)) { + var prop = checker.symbolToNode(symbol, 111551 /* SymbolFlags.Value */, /*enclosingDeclaration*/ undefined, 1073741824 /* NodeBuilderFlags.WriteComputedProps */); + if (prop && ts.isComputedPropertyName(prop)) + return prop; } return ts.createPropertyNameNodeForIdentifierOrLiteral(symbol.name, target, quotePreference === 0 /* QuotePreference.Single */); } + function findScope(node) { + if (ts.findAncestor(node, ts.isJsxExpression)) { + var returnStatement = ts.findAncestor(node.parent, ts.isReturnStatement); + if (returnStatement) + return returnStatement; + } + return ts.getSourceFileOfNode(node); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -158133,7 +159657,7 @@ var ts; // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files // (now named `codeFixClassExtendAbstractPrivateProperty.ts`) var flags = ts.getSyntacticModifierFlags(ts.first(symbol.getDeclarations())); - return !(flags & 8 /* ModifierFlags.Private */) && !!(flags & 128 /* ModifierFlags.Abstract */); + return !(flags & 8 /* ModifierFlags.Private */) && !!(flags & 256 /* ModifierFlags.Abstract */); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -158296,6 +159820,63 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixNaNEquality"; + var errorCodes = [ + ts.Diagnostics.This_condition_will_always_return_0.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span, program = context.program; + var info = getInfo(program, sourceFile, span); + if (info === undefined) + return; + var suggestion = info.suggestion, expression = info.expression, arg = info.arg; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, arg, expression); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Use_0, suggestion], fixId, ts.Diagnostics.Use_Number_isNaN_in_all_conditions)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(context.program, diag.file, ts.createTextSpan(diag.start, diag.length)); + if (info) { + doChange(changes, diag.file, info.arg, info.expression); + } + }); + } + }); + function getInfo(program, sourceFile, span) { + var diag = ts.find(program.getSemanticDiagnostics(sourceFile), function (diag) { return diag.start === span.start && diag.length === span.length; }); + if (diag === undefined || diag.relatedInformation === undefined) + return; + var related = ts.find(diag.relatedInformation, function (related) { return related.code === ts.Diagnostics.Did_you_mean_0.code; }); + if (related === undefined || related.file === undefined || related.start === undefined || related.length === undefined) + return; + var token = codefix.findAncestorMatchingSpan(related.file, ts.createTextSpan(related.start, related.length)); + if (token === undefined) + return; + if (ts.isExpression(token) && ts.isBinaryExpression(token.parent)) { + return { suggestion: getSuggestion(related.messageText), expression: token.parent, arg: token }; + } + return undefined; + } + function doChange(changes, sourceFile, arg, expression) { + var callExpression = ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("Number"), ts.factory.createIdentifier("isNaN")), /*typeArguments*/ undefined, [arg]); + var operator = expression.operatorToken.kind; + changes.replaceNode(sourceFile, expression, operator === 37 /* SyntaxKind.ExclamationEqualsEqualsToken */ || operator === 35 /* SyntaxKind.ExclamationEqualsToken */ + ? ts.factory.createPrefixUnaryExpression(53 /* SyntaxKind.ExclamationToken */, callExpression) : callExpression); + } + function getSuggestion(messageText) { + var _a = ts.flattenDiagnosticMessageText(messageText, "\n", 0).match(/\'(.*)\'/) || [], _ = _a[0], suggestion = _a[1]; + return suggestion; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -158613,7 +160194,7 @@ var ts; var importDeclaration = getImportDeclaration(context.sourceFile, context.program, context.span.start); if (!importDeclaration) return; - var namespaceChanges = ts.textChanges.ChangeTracker.with(context, function (t) { return importDeclaration.kind === 270 /* SyntaxKind.ImportSpecifier */ && doNamespaceImportChange(t, context.sourceFile, importDeclaration, context.program); }); + var namespaceChanges = ts.textChanges.ChangeTracker.with(context, function (t) { return importDeclaration.kind === 273 /* SyntaxKind.ImportSpecifier */ && doNamespaceImportChange(t, context.sourceFile, importDeclaration, context.program); }); var typeOnlyChanges = ts.textChanges.ChangeTracker.with(context, function (t) { return doTypeOnlyImportChange(t, context.sourceFile, importDeclaration, context.program); }); var actions; if (namespaceChanges.length) { @@ -158628,7 +160209,7 @@ var ts; }); function getImportDeclaration(sourceFile, program, start) { var identifier = ts.tryCast(ts.getTokenAtPosition(sourceFile, start), ts.isIdentifier); - if (!identifier || identifier.parent.kind !== 178 /* SyntaxKind.TypeReference */) + if (!identifier || identifier.parent.kind !== 180 /* SyntaxKind.TypeReference */) return; var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(identifier); @@ -158640,11 +160221,11 @@ var ts; // new type-only import declaration, but honestly I doubt anyone will ever use this // codefix at all, so it's probably not worth the lines of code. function doTypeOnlyImportChange(changes, sourceFile, importDeclaration, program) { - if (importDeclaration.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { - changes.insertModifierBefore(sourceFile, 152 /* SyntaxKind.TypeKeyword */, importDeclaration.name); + if (importDeclaration.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */) { + changes.insertModifierBefore(sourceFile, 154 /* SyntaxKind.TypeKeyword */, importDeclaration.name); return; } - var importClause = importDeclaration.kind === 267 /* SyntaxKind.ImportClause */ ? importDeclaration : importDeclaration.parent.parent; + var importClause = importDeclaration.kind === 270 /* SyntaxKind.ImportClause */ ? importDeclaration : importDeclaration.parent.parent; if (importClause.name && importClause.namedBindings) { // Cannot convert an import with a default import and named bindings to type-only // (it's a grammar error). @@ -158661,7 +160242,7 @@ var ts; // Don't convert it to type-only. return; } - changes.insertModifierBefore(sourceFile, 152 /* SyntaxKind.TypeKeyword */, importClause); + changes.insertModifierBefore(sourceFile, 154 /* SyntaxKind.TypeKeyword */, importClause); } function doNamespaceImportChange(changes, sourceFile, importDeclaration, program) { ts.refactor.doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, importDeclaration.parent); @@ -158739,7 +160320,7 @@ var ts; ]; } var result = []; - if (token.kind === 137 /* SyntaxKind.InferKeyword */) { + if (token.kind === 138 /* SyntaxKind.InferKeyword */) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); @@ -158781,7 +160362,7 @@ var ts; break; } case fixIdDelete: { - if (token.kind === 137 /* SyntaxKind.InferKeyword */ || isImport(token)) { + if (token.kind === 138 /* SyntaxKind.InferKeyword */ || isImport(token)) { break; // Can't delete } else if (ts.isJSDocTemplateTag(token)) { @@ -158810,7 +160391,7 @@ var ts; break; } case fixIdInfer: - if (token.kind === 137 /* SyntaxKind.InferKeyword */) { + if (token.kind === 138 /* SyntaxKind.InferKeyword */) { changeInferToUnknown(changes, sourceFile, token); } break; @@ -158821,7 +160402,7 @@ var ts; }, }); function changeInferToUnknown(changes, sourceFile, token) { - changes.replaceNode(sourceFile, token.parent, ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */)); + changes.replaceNode(sourceFile, token.parent, ts.factory.createKeywordTypeNode(157 /* SyntaxKind.UnknownKeyword */)); } function createDeleteFix(changes, diag) { return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); @@ -158831,7 +160412,7 @@ var ts; } function isImport(token) { return token.kind === 100 /* SyntaxKind.ImportKeyword */ - || token.kind === 79 /* SyntaxKind.Identifier */ && (token.parent.kind === 270 /* SyntaxKind.ImportSpecifier */ || token.parent.kind === 267 /* SyntaxKind.ImportClause */); + || token.kind === 79 /* SyntaxKind.Identifier */ && (token.parent.kind === 273 /* SyntaxKind.ImportSpecifier */ || token.parent.kind === 270 /* SyntaxKind.ImportClause */); } /** Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. */ function tryGetFullImport(token) { @@ -158841,7 +160422,7 @@ var ts; return ts.isVariableDeclarationList(token.parent) && ts.first(token.parent.getChildren(sourceFile)) === token; } function deleteEntireVariableStatement(changes, sourceFile, node) { - changes.delete(sourceFile, node.parent.kind === 237 /* SyntaxKind.VariableStatement */ ? node.parent : node); + changes.delete(sourceFile, node.parent.kind === 240 /* SyntaxKind.VariableStatement */ ? node.parent : node); } function deleteDestructuringElements(changes, sourceFile, node) { ts.forEach(node.elements, function (n) { return changes.delete(sourceFile, n); }); @@ -158850,7 +160431,7 @@ var ts; // Don't offer to prefix a property. if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) return; - if (token.kind === 137 /* SyntaxKind.InferKeyword */) { + if (token.kind === 138 /* SyntaxKind.InferKeyword */) { token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; } if (ts.isIdentifier(token) && canPrefix(token)) { @@ -158866,14 +160447,14 @@ var ts; } function canPrefix(token) { switch (token.parent.kind) { - case 164 /* SyntaxKind.Parameter */: - case 163 /* SyntaxKind.TypeParameter */: + case 166 /* SyntaxKind.Parameter */: + case 165 /* SyntaxKind.TypeParameter */: return true; - case 254 /* SyntaxKind.VariableDeclaration */: { + case 257 /* SyntaxKind.VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 244 /* SyntaxKind.ForOfStatement */: - case 243 /* SyntaxKind.ForInStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 246 /* SyntaxKind.ForInStatement */: return true; } } @@ -158928,8 +160509,8 @@ var ts; function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll) { var parent = parameter.parent; switch (parent.kind) { - case 169 /* SyntaxKind.MethodDeclaration */: - case 171 /* SyntaxKind.Constructor */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 173 /* SyntaxKind.Constructor */: var index = parent.parameters.indexOf(parameter); var referent = ts.isMethodDeclaration(parent) ? parent.name : parent; var entries = ts.FindAllReferences.Core.getReferencedSymbolsForNode(parent.pos, referent, program, sourceFiles, cancellationToken); @@ -158959,20 +160540,20 @@ var ts; } } return true; - case 256 /* SyntaxKind.FunctionDeclaration */: { + case 259 /* SyntaxKind.FunctionDeclaration */: { if (parent.name && isCallbackLike(checker, sourceFile, parent.name)) { return isLastParameter(parent, parameter, isFixAll); } return true; } - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. return isLastParameter(parent, parameter, isFixAll); - case 173 /* SyntaxKind.SetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: // Setter must have a parameter return false; - case 172 /* SyntaxKind.GetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: // Getter cannot have parameters return true; default: @@ -159033,7 +160614,7 @@ var ts; var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { switch (container.kind) { - case 239 /* SyntaxKind.IfStatement */: + case 242 /* SyntaxKind.IfStatement */: if (container.elseStatement) { if (ts.isBlock(statement.parent)) { break; @@ -159044,8 +160625,8 @@ var ts; return; } // falls through - case 241 /* SyntaxKind.WhileStatement */: - case 242 /* SyntaxKind.ForStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 245 /* SyntaxKind.ForStatement */: changes.delete(sourceFile, container); return; } @@ -159118,7 +160699,7 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 314 /* SyntaxKind.JSDocNullableType */) { + if (typeNode.kind === 317 /* SyntaxKind.JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` actions.push(fix(checker.getNullableType(type, 32768 /* TypeFlags.Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); @@ -159138,7 +160719,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 314 /* SyntaxKind.JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* TypeFlags.Undefined */) : type; + var fixedType = typeNode.kind === 317 /* SyntaxKind.JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* TypeFlags.Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -159155,22 +160736,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 229 /* SyntaxKind.AsExpression */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 172 /* SyntaxKind.GetAccessor */: - case 176 /* SyntaxKind.IndexSignature */: - case 195 /* SyntaxKind.MappedType */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 164 /* SyntaxKind.Parameter */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: - case 173 /* SyntaxKind.SetAccessor */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 211 /* SyntaxKind.TypeAssertionExpression */: - case 254 /* SyntaxKind.VariableDeclaration */: + case 231 /* SyntaxKind.AsExpression */: + case 176 /* SyntaxKind.CallSignature */: + case 177 /* SyntaxKind.ConstructSignature */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 174 /* SyntaxKind.GetAccessor */: + case 178 /* SyntaxKind.IndexSignature */: + case 197 /* SyntaxKind.MappedType */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 166 /* SyntaxKind.Parameter */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: + case 175 /* SyntaxKind.SetAccessor */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 213 /* SyntaxKind.TypeAssertionExpression */: + case 257 /* SyntaxKind.VariableDeclaration */: return true; default: return false; @@ -159273,14 +160854,14 @@ var ts; } var insertBefore; switch (containingFunction.kind) { - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: insertBefore = containingFunction.name; break; - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: insertBefore = ts.findChildOfKind(containingFunction, 98 /* SyntaxKind.FunctionKeyword */, sourceFile); break; - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: var kind = containingFunction.typeParameters ? 29 /* SyntaxKind.LessThanToken */ : 20 /* SyntaxKind.OpenParenToken */; insertBefore = ts.findChildOfKind(containingFunction, kind, sourceFile) || ts.first(containingFunction.parameters); break; @@ -159300,7 +160881,7 @@ var ts; changes.replaceNode(sourceFile, returnType, ts.factory.createTypeReferenceNode("Promise", ts.factory.createNodeArray([returnType]))); } } - changes.insertModifierBefore(sourceFile, 131 /* SyntaxKind.AsyncKeyword */, insertBefore); + changes.insertModifierBefore(sourceFile, 132 /* SyntaxKind.AsyncKeyword */, insertBefore); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -159616,7 +161197,7 @@ var ts; function annotate(changes, importAdder, sourceFile, declaration, type, program, host) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { - if (ts.isInJSFile(sourceFile) && declaration.kind !== 166 /* SyntaxKind.PropertySignature */) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 168 /* SyntaxKind.PropertySignature */) { var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; if (!parent) { return; @@ -159703,19 +161284,19 @@ var ts; function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) { var searchToken; switch (containingFunction.kind) { - case 171 /* SyntaxKind.Constructor */: - searchToken = ts.findChildOfKind(containingFunction, 134 /* SyntaxKind.ConstructorKeyword */, sourceFile); + case 173 /* SyntaxKind.Constructor */: + searchToken = ts.findChildOfKind(containingFunction, 135 /* SyntaxKind.ConstructorKeyword */, sourceFile); break; - case 214 /* SyntaxKind.ArrowFunction */: - case 213 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: var parent = containingFunction.parent; searchToken = (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent)) && ts.isIdentifier(parent.name) ? parent.name : containingFunction.name; break; - case 256 /* SyntaxKind.FunctionDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: searchToken = containingFunction.name; break; } @@ -159857,24 +161438,24 @@ var ts; node = node.parent; } switch (node.parent.kind) { - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: inferTypeFromExpressionStatement(node, usage); break; - case 220 /* SyntaxKind.PostfixUnaryExpression */: + case 222 /* SyntaxKind.PostfixUnaryExpression */: usage.isNumber = true; break; - case 219 /* SyntaxKind.PrefixUnaryExpression */: + case 221 /* SyntaxKind.PrefixUnaryExpression */: inferTypeFromPrefixUnaryExpression(node.parent, usage); break; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: inferTypeFromBinaryExpression(node, node.parent, usage); break; - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: inferTypeFromSwitchStatementLabel(node.parent, usage); break; - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: if (node.parent.expression === node) { inferTypeFromCallExpression(node.parent, usage); } @@ -159882,20 +161463,20 @@ var ts; inferTypeFromContextualType(node, usage); } break; - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: inferTypeFromPropertyAccessExpression(node.parent, usage); break; - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: inferTypeFromPropertyElementExpression(node.parent, node, usage); break; - case 296 /* SyntaxKind.PropertyAssignment */: - case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: + case 300 /* SyntaxKind.ShorthandPropertyAssignment */: inferTypeFromPropertyAssignment(node.parent, usage); break; - case 167 /* SyntaxKind.PropertyDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: inferTypeFromPropertyDeclaration(node.parent, usage); break; - case 254 /* SyntaxKind.VariableDeclaration */: { + case 257 /* SyntaxKind.VariableDeclaration */: { var _a = node.parent, name = _a.name, initializer = _a.initializer; if (node === name) { if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. @@ -160017,7 +161598,7 @@ var ts; case 56 /* SyntaxKind.BarBarToken */: case 60 /* SyntaxKind.QuestionQuestionToken */: if (node === parent.left && - (node.parent.parent.kind === 254 /* SyntaxKind.VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + (node.parent.parent.kind === 257 /* SyntaxKind.VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { // var x = x || {}; // TODO: use getFalsyflagsOfType addCandidateType(usage, checker.getTypeAtLocation(parent.right)); @@ -160045,7 +161626,7 @@ var ts; } } calculateUsageOfNode(parent, call.return_); - if (parent.kind === 208 /* SyntaxKind.CallExpression */) { + if (parent.kind === 210 /* SyntaxKind.CallExpression */) { (usage.calls || (usage.calls = [])).push(call); } else { @@ -160499,25 +162080,44 @@ var ts; * @param body If defined, this will be the body of the member node passed to `addClassElement`. Otherwise, the body will default to a stub. */ function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional, isAmbient) { + var _a; if (preserveOptional === void 0) { preserveOptional = 3 /* PreserveOptionalFlags.All */; } if (isAmbient === void 0) { isAmbient = false; } var declarations = symbol.getDeclarations(); - if (!(declarations && declarations.length)) { - return undefined; - } + var declaration = declarations === null || declarations === void 0 ? void 0 : declarations[0]; var checker = context.program.getTypeChecker(); var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); - var declaration = declarations[0]; - var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); - var visibilityModifier = createVisibilityModifier(ts.getEffectiveModifierFlags(declaration)); - var modifiers = visibilityModifier ? ts.factory.createNodeArray([visibilityModifier]) : undefined; + /** + * (#49811) + * Note that there are cases in which the symbol declaration is not present. For example, in the code below both + * `MappedIndirect.ax` and `MappedIndirect.ay` have no declaration node attached (due to their mapped-type + * parent): + * + * ```ts + * type Base = { ax: number; ay: string }; + * type BaseKeys = keyof Base; + * type MappedIndirect = { [K in BaseKeys]: boolean }; + * ``` + * + * In such cases, we assume the declaration to be a `PropertySignature`. + */ + var kind = (_a = declaration === null || declaration === void 0 ? void 0 : declaration.kind) !== null && _a !== void 0 ? _a : 168 /* SyntaxKind.PropertySignature */; + var declarationName = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); + var effectiveModifierFlags = declaration ? ts.getEffectiveModifierFlags(declaration) : 0 /* ModifierFlags.None */; + var modifierFlags = effectiveModifierFlags & 4 /* ModifierFlags.Public */ ? 4 /* ModifierFlags.Public */ : + effectiveModifierFlags & 16 /* ModifierFlags.Protected */ ? 16 /* ModifierFlags.Protected */ : + 0 /* ModifierFlags.None */; + if (declaration && ts.isAutoAccessorPropertyDeclaration(declaration)) { + modifierFlags |= 128 /* ModifierFlags.Accessor */; + } + var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* SymbolFlags.Optional */); var ambient = !!(enclosingDeclaration.flags & 16777216 /* NodeFlags.Ambient */) || isAmbient; var quotePreference = ts.getQuotePreference(sourceFile, preferences); - switch (declaration.kind) { - case 166 /* SyntaxKind.PropertySignature */: - case 167 /* SyntaxKind.PropertyDeclaration */: + switch (kind) { + case 168 /* SyntaxKind.PropertySignature */: + case 169 /* SyntaxKind.PropertyDeclaration */: var flags = quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : undefined; var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); if (importAdder) { @@ -160527,11 +162127,12 @@ var ts; importSymbols(importAdder, importableReference.symbols); } } - addClassElement(ts.factory.createPropertyDeclaration(modifiers, name, optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, + addClassElement(ts.factory.createPropertyDeclaration(modifiers, declaration ? createName(declarationName) : symbol.getName(), optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: { + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: { + ts.Debug.assertIsDefined(declarations); var typeNode_1 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); var allAccessors = ts.getAllAccessorDeclarations(declarations, declaration); var orderedAccessors = allAccessors.secondAccessor @@ -160547,19 +162148,19 @@ var ts; for (var _i = 0, orderedAccessors_1 = orderedAccessors; _i < orderedAccessors_1.length; _i++) { var accessor = orderedAccessors_1[_i]; if (ts.isGetAccessorDeclaration(accessor)) { - addClassElement(ts.factory.createGetAccessorDeclaration(modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createGetAccessorDeclaration(modifiers, createName(declarationName), ts.emptyArray, createTypeNode(typeNode_1), createBody(body, quotePreference, ambient))); } else { ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); var parameter = ts.getSetAccessorValueParameter(accessor); var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined; - addClassElement(ts.factory.createSetAccessorDeclaration(modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createSetAccessorDeclaration(modifiers, createName(declarationName), createDummyParameters(1, [parameterName], [createTypeNode(typeNode_1)], 1, /*inJs*/ false), createBody(body, quotePreference, ambient))); } } break; } - case 168 /* SyntaxKind.MethodSignature */: - case 169 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -160567,6 +162168,7 @@ var ts; // If there is more than one overload but no implementation signature // (eg: an abstract method or interface declaration), there is a 1-1 // correspondence of declarations and signatures. + ts.Debug.assertIsDefined(declarations); var signatures = type.isUnion() ? ts.flatMap(type.types, function (t) { return t.getCallSignatures(); }) : type.getCallSignatures(); if (!ts.some(signatures)) { break; @@ -160574,31 +162176,41 @@ var ts; if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1, "One declaration implies one signature"); var signature = signatures[0]; - outputMethod(quotePreference, signature, modifiers, name, ambient ? undefined : body || createStubbedMethodBody(quotePreference)); + outputMethod(quotePreference, signature, modifiers, createName(declarationName), createBody(body, quotePreference, ambient)); break; } - for (var _a = 0, signatures_1 = signatures; _a < signatures_1.length; _a++) { - var signature = signatures_1[_a]; + for (var _b = 0, signatures_1 = signatures; _b < signatures_1.length; _b++) { + var signature = signatures_1[_b]; // Ensure nodes are fresh so they can have different positions when going through formatting. - outputMethod(quotePreference, signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); + outputMethod(quotePreference, signature, modifiers, createName(declarationName)); } if (!ambient) { if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(quotePreference, signature, modifiers, name, body || createStubbedMethodBody(quotePreference)); + outputMethod(quotePreference, signature, modifiers, createName(declarationName), createBody(body, quotePreference)); } else { ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional && !!(preserveOptional & 1 /* PreserveOptionalFlags.Method */), modifiers, quotePreference, body)); + addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, createName(declarationName), optional && !!(preserveOptional & 1 /* PreserveOptionalFlags.Method */), modifiers, quotePreference, body)); } } break; } function outputMethod(quotePreference, signature, modifiers, name, body) { - var method = createSignatureDeclarationFromSignature(169 /* SyntaxKind.MethodDeclaration */, context, quotePreference, signature, body, name, modifiers, optional && !!(preserveOptional & 1 /* PreserveOptionalFlags.Method */), enclosingDeclaration, importAdder); + var method = createSignatureDeclarationFromSignature(171 /* SyntaxKind.MethodDeclaration */, context, quotePreference, signature, body, name, modifiers, optional && !!(preserveOptional & 1 /* PreserveOptionalFlags.Method */), enclosingDeclaration, importAdder); if (method) addClassElement(method); } + function createName(node) { + return ts.getSynthesizedDeepClone(node, /*includeTrivia*/ false); + } + function createBody(block, quotePreference, ambient) { + return ambient ? undefined : + ts.getSynthesizedDeepClone(block, /*includeTrivia*/ false) || createStubbedMethodBody(quotePreference); + } + function createTypeNode(typeNode) { + return ts.getSynthesizedDeepClone(typeNode, /*includeTrivia*/ false); + } } codefix.addNewNodeForMemberSymbol = addNewNodeForMemberSymbol; function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) { @@ -160672,6 +162284,9 @@ var ts; if (ts.isMethodDeclaration(signatureDeclaration)) { return ts.factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name !== null && name !== void 0 ? name : ts.factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); } + if (ts.isFunctionDeclaration(signatureDeclaration)) { + return ts.factory.updateFunctionDeclaration(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, ts.tryCast(name, ts.isIdentifier), typeParameters, parameters, type, body !== null && body !== void 0 ? body : signatureDeclaration.body); + } return undefined; } codefix.createSignatureDeclarationFromSignature = createSignatureDeclarationFromSignature; @@ -160700,13 +162315,13 @@ var ts; ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); switch (kind) { - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: return ts.factory.createMethodDeclaration(modifiers, asteriskToken, name, /*questionToken*/ undefined, typeParameters, parameters, type, createStubbedMethodBody(quotePreference)); - case 168 /* SyntaxKind.MethodSignature */: + case 170 /* SyntaxKind.MethodSignature */: return ts.factory.createMethodSignature(modifiers, name, - /*questionToken*/ undefined, typeParameters, parameters, type === undefined ? ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */) : type); - case 256 /* SyntaxKind.FunctionDeclaration */: + /*questionToken*/ undefined, typeParameters, parameters, type === undefined ? ts.factory.createKeywordTypeNode(157 /* SyntaxKind.UnknownKeyword */) : type); + case 259 /* SyntaxKind.FunctionDeclaration */: return ts.factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference)); default: ts.Debug.fail("Unexpected kind"); @@ -160843,7 +162458,7 @@ var ts; /*dotDotDotToken*/ undefined, /*name*/ parameterName + (parameterNameCount || ""), /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, - /*type*/ inJs ? undefined : (types === null || types === void 0 ? void 0 : types[i]) || ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), + /*type*/ inJs ? undefined : (types === null || types === void 0 ? void 0 : types[i]) || ts.factory.createKeywordTypeNode(157 /* SyntaxKind.UnknownKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -160873,7 +162488,7 @@ var ts; if (someSigHasRestParameter) { var restParameter = ts.factory.createParameterDeclaration( /*modifiers*/ undefined, ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", - /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, ts.factory.createArrayTypeNode(ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */)), + /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, ts.factory.createArrayTypeNode(ts.factory.createKeywordTypeNode(157 /* SyntaxKind.UnknownKeyword */)), /*initializer*/ undefined); parameters.push(restParameter); } @@ -160901,15 +162516,6 @@ var ts; /*multiline*/ true); } codefix.createStubbedBody = createStubbedBody; - function createVisibilityModifier(flags) { - if (flags & 4 /* ModifierFlags.Public */) { - return ts.factory.createToken(123 /* SyntaxKind.PublicKeyword */); - } - else if (flags & 16 /* ModifierFlags.Protected */) { - return ts.factory.createToken(122 /* SyntaxKind.ProtectedKeyword */); - } - return undefined; - } function setJsonCompilerOptionValues(changeTracker, configFile, options) { var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); if (!tsconfigObjectLiteral) @@ -160988,6 +162594,15 @@ var ts; symbols.forEach(function (s) { return importAdder.addImportFromExportedSymbol(s, /*isValidTypeOnlyUseSite*/ true); }); } codefix.importSymbols = importSymbols; + function findAncestorMatchingSpan(sourceFile, span) { + var end = ts.textSpanEnd(span); + var token = ts.getTokenAtPosition(sourceFile, span.start); + while (token.end < end) { + token = token.parent; + } + return token; + } + codefix.findAncestorMatchingSpan = findAncestorMatchingSpan; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -161010,13 +162625,13 @@ var ts; if (ts.isClassLike(container)) { var modifierFlags = ts.getEffectiveModifierFlags(declaration); if (ts.isSourceFileJS(file)) { - var modifiers = ts.createModifiers(modifierFlags); + var modifiers = ts.factory.createModifiersFromModifierFlags(modifierFlags); accessorModifiers = modifiers; fieldModifiers = modifiers; } else { - accessorModifiers = ts.createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); - fieldModifiers = ts.createModifiers(prepareModifierFlagsForField(modifierFlags)); + accessorModifiers = ts.factory.createModifiersFromModifierFlags(prepareModifierFlagsForAccessor(modifierFlags)); + fieldModifiers = ts.factory.createModifiersFromModifierFlags(prepareModifierFlagsForField(modifierFlags)); } if (ts.canHaveDecorators(declaration)) { fieldModifiers = ts.concatenate(ts.getDecorators(declaration), fieldModifiers); @@ -161085,7 +162700,7 @@ var ts; error: ts.getLocaleSpecificMessage(ts.Diagnostics.Name_is_not_valid) }; } - if (((ts.getEffectiveModifierFlags(declaration) & 125951 /* ModifierFlags.Modifier */) | meaning) !== meaning) { + if (((ts.getEffectiveModifierFlags(declaration) & 126975 /* ModifierFlags.Modifier */) | meaning) !== meaning) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_property_with_modifier) }; @@ -161098,7 +162713,7 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasEffectiveReadonlyModifier(declaration), type: getDeclarationType(declaration, program), - container: declaration.kind === 164 /* SyntaxKind.Parameter */ ? declaration.parent.parent : declaration.parent, + container: declaration.kind === 166 /* SyntaxKind.Parameter */ ? declaration.parent.parent : declaration.parent, originalName: declaration.name.text, declaration: declaration, fieldName: fieldName, @@ -161172,7 +162787,7 @@ var ts; var type = typeChecker.getTypeFromTypeNode(typeNode); if (!typeChecker.isTypeAssignableTo(typeChecker.getUndefinedType(), type)) { var types = ts.isUnionTypeNode(typeNode) ? typeNode.types : [typeNode]; - return ts.factory.createUnionTypeNode(__spreadArray(__spreadArray([], types, true), [ts.factory.createKeywordTypeNode(153 /* SyntaxKind.UndefinedKeyword */)], false)); + return ts.factory.createUnionTypeNode(__spreadArray(__spreadArray([], types, true), [ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UndefinedKeyword */)], false)); } } return typeNode; @@ -161230,7 +162845,7 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 208 /* SyntaxKind.CallExpression */ : 209 /* SyntaxKind.NewExpression */; + var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 210 /* SyntaxKind.CallExpression */ : 211 /* SyntaxKind.NewExpression */; var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind; }); if (!node) { return []; @@ -161356,7 +162971,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, info.prop.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); } function addUndefinedType(changeTracker, sourceFile, info) { - var undefinedTypeNode = ts.factory.createKeywordTypeNode(153 /* SyntaxKind.UndefinedKeyword */); + var undefinedTypeNode = ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UndefinedKeyword */); var types = ts.isUnionTypeNode(info.type) ? info.type.types.concat(undefinedTypeNode) : [info.type, undefinedTypeNode]; var unionTypeNode = ts.factory.createUnionTypeNode(types); if (info.isJs) { @@ -161402,7 +163017,7 @@ var ts; } else if (type.isClass()) { var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); - if (!classDeclaration || ts.hasSyntacticModifier(classDeclaration, 128 /* ModifierFlags.Abstract */)) + if (!classDeclaration || ts.hasSyntacticModifier(classDeclaration, 256 /* ModifierFlags.Abstract */)) return undefined; var constructorDeclaration = ts.getFirstConstructorWithBody(classDeclaration); if (constructorDeclaration && constructorDeclaration.parameters.length) @@ -161579,7 +163194,7 @@ var ts; function getImportTypeNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); ts.Debug.assert(token.kind === 100 /* SyntaxKind.ImportKeyword */, "This token should be an ImportKeyword"); - ts.Debug.assert(token.parent.kind === 200 /* SyntaxKind.ImportType */, "Token parent should be an ImportType"); + ts.Debug.assert(token.parent.kind === 202 /* SyntaxKind.ImportType */, "Token parent should be an ImportType"); return token.parent; } function doChange(changes, sourceFile, importType) { @@ -161708,7 +163323,7 @@ var ts; var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); var parameter = ts.first(indexSignature.parameters); var mappedTypeParameter = ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.cast(parameter.name, ts.isIdentifier), parameter.type); - var mappedIntersectionType = ts.factory.createMappedTypeNode(ts.hasEffectiveReadonlyModifier(indexSignature) ? ts.factory.createModifier(145 /* SyntaxKind.ReadonlyKeyword */) : undefined, mappedTypeParameter, + var mappedIntersectionType = ts.factory.createMappedTypeNode(ts.hasEffectiveReadonlyModifier(indexSignature) ? ts.factory.createModifier(146 /* SyntaxKind.ReadonlyKeyword */) : undefined, mappedTypeParameter, /*nameType*/ undefined, indexSignature.questionToken, indexSignature.type, /*members*/ undefined); var intersectionType = ts.factory.createIntersectionTypeNode(__spreadArray(__spreadArray(__spreadArray([], ts.getAllSuperTypeNodes(container), true), [ @@ -161766,7 +163381,7 @@ var ts; }, }); function makeChange(changeTracker, sourceFile, span) { - var awaitKeyword = ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start), function (node) { return node.kind === 132 /* SyntaxKind.AwaitKeyword */; }); + var awaitKeyword = ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start), function (node) { return node.kind === 133 /* SyntaxKind.AwaitKeyword */; }); var awaitExpression = awaitKeyword && ts.tryCast(awaitKeyword.parent, ts.isAwaitExpression); if (!awaitExpression) { return; @@ -161833,28 +163448,45 @@ var ts; errorCodes: errorCodes, getCodeActions: function getCodeActionsToConvertConstToLet(context) { var sourceFile = context.sourceFile, span = context.span, program = context.program; - var range = getConstTokenRange(sourceFile, span.start, program); - if (range === undefined) + var info = getInfo(sourceFile, span.start, program); + if (info === undefined) return; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, range); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_const_to_let, fixId, ts.Diagnostics.Convert_const_to_let)]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info.token); }); + return [codefix.createCodeFixActionMaybeFixAll(fixId, changes, ts.Diagnostics.Convert_const_to_let, fixId, ts.Diagnostics.Convert_all_const_to_let)]; + }, + getAllCodeActions: function (context) { + var program = context.program; + var seen = new ts.Map(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, program); + if (info) { + if (ts.addToSeen(seen, ts.getSymbolId(info.symbol))) { + return doChange(changes, diag.file, info.token); + } + } + return undefined; + }); + })); }, fixIds: [fixId] }); - function getConstTokenRange(sourceFile, pos, program) { + function getInfo(sourceFile, pos, program) { var _a; var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, pos)); + if (symbol === undefined) + return; var declaration = ts.tryCast((_a = symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.parent, ts.isVariableDeclarationList); if (declaration === undefined) return; var constToken = ts.findChildOfKind(declaration, 85 /* SyntaxKind.ConstKeyword */, sourceFile); if (constToken === undefined) return; - return ts.createRange(constToken.pos, constToken.end); + return { symbol: symbol, token: constToken }; } - function doChange(changes, sourceFile, range) { - changes.replaceRangeWithText(sourceFile, range, "let"); + function doChange(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token, ts.factory.createToken(119 /* SyntaxKind.LetKeyword */)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -162029,7 +163661,6 @@ var ts; return { edits: edits, renameFilename: undefined, renameLocation: undefined }; }, }); - ; function getInfo(context, considerPartialSpans) { if (considerPartialSpans === void 0) { considerPartialSpans = true; } var file = context.file, program = context.program; @@ -162041,8 +163672,8 @@ var ts; } var checker = program.getTypeChecker(); var exportingModuleSymbol = getExportingModuleSymbol(exportNode, checker); - var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ModifierFlags.ExportDefault */ : 0 /* ModifierFlags.None */); - var wasDefault = !!(flags & 512 /* ModifierFlags.Default */); + var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 1025 /* ModifierFlags.ExportDefault */ : 0 /* ModifierFlags.None */); + var wasDefault = !!(flags & 1024 /* ModifierFlags.Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* ModifierFlags.Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* InternalSymbolName.Default */)) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.This_file_already_has_a_default_export) }; @@ -162052,19 +163683,19 @@ var ts; : { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_named_export) }; }; switch (exportNode.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: { + case 259 /* SyntaxKind.FunctionDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: { var node = exportNode; if (!node.name) return undefined; return noSymbolError(node.name) || { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol }; } - case 237 /* SyntaxKind.VariableStatement */: { + case 240 /* SyntaxKind.VariableStatement */: { var vs = exportNode; // Must be `export const x = something;`. if (!(vs.declarationList.flags & 2 /* NodeFlags.Const */) || vs.declarationList.declarations.length !== 1) { @@ -162077,7 +163708,7 @@ var ts; return noSymbolError(decl.name) || { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol }; } - case 271 /* SyntaxKind.ExportAssignment */: { + case 274 /* SyntaxKind.ExportAssignment */: { var node = exportNode; if (node.isExportEquals) return undefined; @@ -162107,12 +163738,12 @@ var ts; else { var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 93 /* SyntaxKind.ExportKeyword */), "Should find an export keyword in modifier list"); switch (exportNode.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.factory.createToken(88 /* SyntaxKind.DefaultKeyword */)); break; - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: // If 'x' isn't used in this file and doesn't have type definition, `export const x = 0;` --> `export default 0;` var decl = ts.first(exportNode.declarationList.declarations); if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { @@ -162121,9 +163752,9 @@ var ts; break; } // falls through - case 260 /* SyntaxKind.EnumDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: // `export type T = number;` -> `type T = number; export default T;` changes.deleteModifier(exportingSourceFile, exportKeyword); changes.insertNodeAfter(exportingSourceFile, exportNode, ts.factory.createExportDefault(ts.factory.createIdentifier(exportName.text))); @@ -162152,18 +163783,18 @@ var ts; function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { var parent = ref.parent; switch (parent.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: // `a.default` --> `a.foo` changes.replaceNode(importingSourceFile, ref, ts.factory.createIdentifier(exportName)); break; - case 270 /* SyntaxKind.ImportSpecifier */: - case 275 /* SyntaxKind.ExportSpecifier */: { + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: { var spec = parent; // `default as foo` --> `foo`, `default as bar` --> `foo as bar` changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); break; } - case 267 /* SyntaxKind.ImportClause */: { + case 270 /* SyntaxKind.ImportClause */: { var clause = parent; ts.Debug.assert(clause.name === ref, "Import clause name should match provided ref"); var spec = makeImportSpecifier(exportName, ref.text); @@ -162172,7 +163803,7 @@ var ts; // `import foo from "./a";` --> `import { foo } from "./a";` changes.replaceNode(importingSourceFile, ref, ts.factory.createNamedImports([spec])); } - else if (namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { + else if (namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */) { // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* QuotePreference.Double */; @@ -162186,7 +163817,7 @@ var ts; } break; } - case 200 /* SyntaxKind.ImportType */: + case 202 /* SyntaxKind.ImportType */: var importTypeNode = parent; changes.replaceNode(importingSourceFile, parent, ts.factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, ts.factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); break; @@ -162197,11 +163828,11 @@ var ts; function changeNamedToDefaultImport(importingSourceFile, ref, changes) { var parent = ref.parent; switch (parent.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: // `a.foo` --> `a.default` changes.replaceNode(importingSourceFile, ref, ts.factory.createIdentifier("default")); break; - case 270 /* SyntaxKind.ImportSpecifier */: { + case 273 /* SyntaxKind.ImportSpecifier */: { // `import { foo } from "./a";` --> `import foo from "./a";` // `import { foo as bar } from "./a";` --> `import bar from "./a";` var defaultImport = ts.factory.createIdentifier(parent.name.text); @@ -162214,7 +163845,7 @@ var ts; } break; } - case 275 /* SyntaxKind.ExportSpecifier */: { + case 278 /* SyntaxKind.ExportSpecifier */: { // `export { foo } from "./a";` --> `export { default as foo } from "./a";` // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` // `export { foo as default } from "./a";` --> `export { default } from "./a";` @@ -162315,7 +163946,7 @@ var ts; if (!importClause.namedBindings) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_namespace_import_or_named_imports) }; } - if (importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { + if (importClause.namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */) { return { convertTo: 0 /* ImportKind.Named */, import: importClause.namedBindings }; } var shouldUseDefault = getShouldUseDefault(context.program, importClause); @@ -162506,7 +164137,6 @@ var ts; }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } - ; function isValidExpression(node) { return ts.isBinaryExpression(node) || ts.isConditionalExpression(node); } @@ -162554,7 +164184,6 @@ var ts; if (expression.operatorToken.kind !== 55 /* SyntaxKind.AmpersandAmpersandToken */) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_logical_AND_access_chains) }; } - ; var finalExpression = getFinalExpressionInChain(expression.right); if (!finalExpression) return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_convertible_access_expression) }; @@ -162764,27 +164393,27 @@ var ts; var lastDeclaration = signatureDecls[signatureDecls.length - 1]; var updated = lastDeclaration; switch (lastDeclaration.kind) { - case 168 /* SyntaxKind.MethodSignature */: { + case 170 /* SyntaxKind.MethodSignature */: { updated = ts.factory.updateMethodSignature(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 169 /* SyntaxKind.MethodDeclaration */: { + case 171 /* SyntaxKind.MethodDeclaration */: { updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } - case 174 /* SyntaxKind.CallSignature */: { + case 176 /* SyntaxKind.CallSignature */: { updated = ts.factory.updateCallSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 171 /* SyntaxKind.Constructor */: { + case 173 /* SyntaxKind.Constructor */: { updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); break; } - case 175 /* SyntaxKind.ConstructSignature */: { + case 177 /* SyntaxKind.ConstructSignature */: { updated = ts.factory.updateConstructSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 256 /* SyntaxKind.FunctionDeclaration */: { + case 259 /* SyntaxKind.FunctionDeclaration */: { updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } @@ -162815,7 +164444,7 @@ var ts; } function convertParameterToNamedTupleMember(p) { ts.Debug.assert(ts.isIdentifier(p.name)); // This is checked during refactoring applicability checking - var result = ts.setTextRange(ts.factory.createNamedTupleMember(p.dotDotDotToken, p.name, p.questionToken, p.type || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)), p); + var result = ts.setTextRange(ts.factory.createNamedTupleMember(p.dotDotDotToken, p.name, p.questionToken, p.type || ts.factory.createKeywordTypeNode(131 /* SyntaxKind.AnyKeyword */)), p); var parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); if (parameterDocComment) { var newComment = ts.displayPartsToString(parameterDocComment); @@ -162835,12 +164464,12 @@ var ts; } function isConvertableSignatureDeclaration(d) { switch (d.kind) { - case 168 /* SyntaxKind.MethodSignature */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 174 /* SyntaxKind.CallSignature */: - case 171 /* SyntaxKind.Constructor */: - case 175 /* SyntaxKind.ConstructSignature */: - case 256 /* SyntaxKind.FunctionDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 176 /* SyntaxKind.CallSignature */: + case 173 /* SyntaxKind.Constructor */: + case 177 /* SyntaxKind.ConstructSignature */: + case 259 /* SyntaxKind.FunctionDeclaration */: return true; } return false; @@ -162959,8 +164588,8 @@ var ts; var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; - var description = functionExtraction.description; if (refactor.refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + var description = functionExtraction.description; if (functionExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will @@ -162984,15 +164613,15 @@ var ts; } } if (refactor.refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + var description = constantExtraction.description; if (constantExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will // preferentially go into nearer scopes - var description_1 = constantExtraction.description; - if (!usedConstantNames.has(description_1)) { - usedConstantNames.set(description_1, true); + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); constantActions.push({ - description: description_1, + description: description, name: "constant_scope_".concat(i), kind: extractConstantAction.kind }); @@ -163137,7 +164766,6 @@ var ts; var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, adjustedSpan); // Do the same for the ending position var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, adjustedSpan); - var declarations = []; // We'll modify these flags as we walk the tree to collect data // about what things need to be done as part of the extraction. var rangeFacts = RangeFacts.None; @@ -163180,7 +164808,7 @@ var ts; // the expression. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } - return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations, thisNode: thisNode } }; + return { targetRange: { range: statements, facts: rangeFacts, thisNode: thisNode } }; } if (ts.isReturnStatement(start) && !start.expression) { // Makes no sense to extract an expression-less return statement. @@ -163192,7 +164820,7 @@ var ts; if (errors) { return { errors: errors }; } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations, thisNode: thisNode } }; // TODO: GH#18217 + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode: thisNode } }; // TODO: GH#18217 /** * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. * @param node The unrefined extraction node. @@ -163204,10 +164832,10 @@ var ts; } } else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { - var declarations_6 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; + var declarations = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, declarations_5 = declarations_6; _i < declarations_5.length; _i++) { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; if (declaration.initializer) { numInitializers++; @@ -163235,20 +164863,20 @@ var ts; function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 167 /* SyntaxKind.PropertyDeclaration */) { + if (current.kind === 169 /* SyntaxKind.PropertyDeclaration */) { if (ts.isStatic(current)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 164 /* SyntaxKind.Parameter */) { + else if (current.kind === 166 /* SyntaxKind.Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 171 /* SyntaxKind.Constructor */) { + if (ctorOrMethod.kind === 173 /* SyntaxKind.Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 169 /* SyntaxKind.MethodDeclaration */) { + else if (current.kind === 171 /* SyntaxKind.MethodDeclaration */) { if (ts.isStatic(current)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -163286,9 +164914,9 @@ var ts; visit(nodeToCheck); if (rangeFacts & RangeFacts.UsesThis) { var container = ts.getThisContainer(nodeToCheck, /** includeArrowFunctions */ false); - if (container.kind === 256 /* SyntaxKind.FunctionDeclaration */ || - (container.kind === 169 /* SyntaxKind.MethodDeclaration */ && container.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) || - container.kind === 213 /* SyntaxKind.FunctionExpression */) { + if (container.kind === 259 /* SyntaxKind.FunctionDeclaration */ || + (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && container.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */) || + container.kind === 215 /* SyntaxKind.FunctionExpression */) { rangeFacts |= RangeFacts.UsesThisInFunction; } } @@ -163299,7 +164927,7 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 254 /* SyntaxKind.VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 257 /* SyntaxKind.VariableDeclaration */) ? node.parent.parent : node; if (ts.hasSyntacticModifier(declaringNode, 1 /* ModifierFlags.Export */)) { // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! @@ -163307,20 +164935,19 @@ var ts; (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } - declarations.push(node.symbol); } // Some things can't be extracted in certain situations switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; case 106 /* SyntaxKind.SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 208 /* SyntaxKind.CallExpression */) { + if (node.parent.kind === 210 /* SyntaxKind.CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); if (containingClass_1 === undefined || containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { @@ -163333,7 +164960,7 @@ var ts; thisNode = node; } break; - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: // check if arrow function uses this ts.forEachChild(node, function check(n) { if (ts.isThis(n)) { @@ -163348,39 +164975,39 @@ var ts; } }); // falls through - case 257 /* SyntaxKind.ClassDeclaration */: - case 256 /* SyntaxKind.FunctionDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } // falls through - case 226 /* SyntaxKind.ClassExpression */: - case 213 /* SyntaxKind.FunctionExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 171 /* SyntaxKind.Constructor */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: + case 228 /* SyntaxKind.ClassExpression */: + case 215 /* SyntaxKind.FunctionExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 173 /* SyntaxKind.Constructor */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: // do not dive into functions or classes return false; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 239 /* SyntaxKind.IfStatement */: + case 242 /* SyntaxKind.IfStatement */: permittedJumps &= ~4 /* PermittedJumps.Return */; break; - case 252 /* SyntaxKind.TryStatement */: + case 255 /* SyntaxKind.TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* PermittedJumps.None */; break; - case 235 /* SyntaxKind.Block */: - if (node.parent && node.parent.kind === 252 /* SyntaxKind.TryStatement */ && node.parent.finallyBlock === node) { + case 238 /* SyntaxKind.Block */: + if (node.parent && node.parent.kind === 255 /* SyntaxKind.TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* PermittedJumps.Return */; } break; - case 290 /* SyntaxKind.DefaultClause */: - case 289 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: + case 292 /* SyntaxKind.CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* PermittedJumps.Break */; break; @@ -163392,20 +165019,20 @@ var ts; break; } switch (node.kind) { - case 192 /* SyntaxKind.ThisType */: + case 194 /* SyntaxKind.ThisType */: case 108 /* SyntaxKind.ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; thisNode = node; break; - case 250 /* SyntaxKind.LabeledStatement */: { + case 253 /* SyntaxKind.LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); ts.forEachChild(node, visit); seenLabels.pop(); break; } - case 246 /* SyntaxKind.BreakStatement */: - case 245 /* SyntaxKind.ContinueStatement */: { + case 249 /* SyntaxKind.BreakStatement */: + case 248 /* SyntaxKind.ContinueStatement */: { var label = node.label; if (label) { if (!ts.contains(seenLabels, label.escapedText)) { @@ -163414,20 +165041,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 246 /* SyntaxKind.BreakStatement */ ? 1 /* PermittedJumps.Break */ : 2 /* PermittedJumps.Continue */))) { + if (!(permittedJumps & (node.kind === 249 /* SyntaxKind.BreakStatement */ ? 1 /* PermittedJumps.Break */ : 2 /* PermittedJumps.Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 218 /* SyntaxKind.AwaitExpression */: + case 220 /* SyntaxKind.AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 224 /* SyntaxKind.YieldExpression */: + case 226 /* SyntaxKind.YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 247 /* SyntaxKind.ReturnStatement */: + case 250 /* SyntaxKind.ReturnStatement */: if (permittedJumps & 4 /* PermittedJumps.Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -163497,7 +165124,7 @@ var ts; while (true) { current = current.parent; // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current.kind === 164 /* SyntaxKind.Parameter */) { + if (current.kind === 166 /* SyntaxKind.Parameter */) { // Skip all the way to the outer scope of the function that declared this parameter current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } @@ -163508,7 +165135,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 305 /* SyntaxKind.SourceFile */) { + if (current.kind === 308 /* SyntaxKind.SourceFile */) { return scopes; } } @@ -163598,32 +165225,32 @@ var ts; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: return "constructor"; - case 213 /* SyntaxKind.FunctionExpression */: - case 256 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: return scope.name ? "function '".concat(scope.name.text, "'") : ts.ANONYMOUS; - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return "arrow function"; - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: return "method '".concat(scope.name.getText(), "'"); - case 172 /* SyntaxKind.GetAccessor */: + case 174 /* SyntaxKind.GetAccessor */: return "'get ".concat(scope.name.getText(), "'"); - case 173 /* SyntaxKind.SetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: return "'set ".concat(scope.name.getText(), "'"); default: throw ts.Debug.assertNever(scope, "Unexpected scope kind ".concat(scope.kind)); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 257 /* SyntaxKind.ClassDeclaration */ + return scope.kind === 260 /* SyntaxKind.ClassDeclaration */ ? scope.name ? "class '".concat(scope.name.text, "'") : "anonymous class declaration" : scope.name ? "class expression '".concat(scope.name.text, "'") : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 262 /* SyntaxKind.ModuleBlock */ + return scope.kind === 265 /* SyntaxKind.ModuleBlock */ ? "namespace '".concat(scope.parent.name.getText(), "'") : scope.externalModuleIndicator ? 0 /* SpecialScope.Module */ : 1 /* SpecialScope.Global */; } @@ -163696,7 +165323,7 @@ var ts; modifiers.push(ts.factory.createModifier(124 /* SyntaxKind.StaticKeyword */)); } if (range.facts & RangeFacts.IsAsyncFunction) { - modifiers.push(ts.factory.createModifier(131 /* SyntaxKind.AsyncKeyword */)); + modifiers.push(ts.factory.createModifier(132 /* SyntaxKind.AsyncKeyword */)); } newFunction = ts.factory.createMethodDeclaration(modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, /*questionToken*/ undefined, typeParameters, parameters, returnType, body); @@ -163710,7 +165337,7 @@ var ts; /*questionToken*/ undefined, checker.typeToTypeNode(checker.getTypeAtLocation(range.thisNode), scope, 1 /* NodeBuilderFlags.NoTruncation */), /*initializer*/ undefined)); } - newFunction = ts.factory.createFunctionDeclaration(range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(131 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + newFunction = ts.factory.createFunctionDeclaration(range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(132 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; @@ -163858,9 +165485,9 @@ var ts; while (ts.isParenthesizedTypeNode(withoutParens)) { withoutParens = withoutParens.type; } - return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 153 /* SyntaxKind.UndefinedKeyword */; }) + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 155 /* SyntaxKind.UndefinedKeyword */; }) ? clone - : ts.factory.createUnionTypeNode([clone, ts.factory.createKeywordTypeNode(153 /* SyntaxKind.UndefinedKeyword */)]); + : ts.factory.createUnionTypeNode([clone, ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UndefinedKeyword */)]); } } /** @@ -163891,7 +165518,7 @@ var ts; if (rangeFacts & RangeFacts.InStaticRegion) { modifiers.push(ts.factory.createModifier(124 /* SyntaxKind.StaticKeyword */)); } - modifiers.push(ts.factory.createModifier(145 /* SyntaxKind.ReadonlyKeyword */)); + modifiers.push(ts.factory.createModifier(146 /* SyntaxKind.ReadonlyKeyword */)); var newVariable = ts.factory.createPropertyDeclaration(modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); var localReference = ts.factory.createPropertyAccessExpression(rangeFacts & RangeFacts.InStaticRegion @@ -163922,7 +165549,7 @@ var ts; var localReference = ts.factory.createIdentifier(localNameText); changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 238 /* SyntaxKind.ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 241 /* SyntaxKind.ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.factory.createVariableStatement( @@ -163941,7 +165568,7 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 238 /* SyntaxKind.ExpressionStatement */) { + if (node.parent.kind === 241 /* SyntaxKind.ExpressionStatement */) { // If the parent is an expression statement, delete it. changeTracker.delete(context.file, node.parent); } @@ -164587,30 +166214,30 @@ var ts; function isExtractableExpression(node) { var parent = node.parent; switch (parent.kind) { - case 299 /* SyntaxKind.EnumMember */: + case 302 /* SyntaxKind.EnumMember */: return false; } switch (node.kind) { case 10 /* SyntaxKind.StringLiteral */: - return parent.kind !== 266 /* SyntaxKind.ImportDeclaration */ && - parent.kind !== 270 /* SyntaxKind.ImportSpecifier */; - case 225 /* SyntaxKind.SpreadElement */: - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 203 /* SyntaxKind.BindingElement */: + return parent.kind !== 269 /* SyntaxKind.ImportDeclaration */ && + parent.kind !== 273 /* SyntaxKind.ImportSpecifier */; + case 227 /* SyntaxKind.SpreadElement */: + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 205 /* SyntaxKind.BindingElement */: return false; case 79 /* SyntaxKind.Identifier */: - return parent.kind !== 203 /* SyntaxKind.BindingElement */ && - parent.kind !== 270 /* SyntaxKind.ImportSpecifier */ && - parent.kind !== 275 /* SyntaxKind.ExportSpecifier */; + return parent.kind !== 205 /* SyntaxKind.BindingElement */ && + parent.kind !== 273 /* SyntaxKind.ImportSpecifier */ && + parent.kind !== 278 /* SyntaxKind.ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 235 /* SyntaxKind.Block */: - case 305 /* SyntaxKind.SourceFile */: - case 262 /* SyntaxKind.ModuleBlock */: - case 289 /* SyntaxKind.CaseClause */: + case 238 /* SyntaxKind.Block */: + case 308 /* SyntaxKind.SourceFile */: + case 265 /* SyntaxKind.ModuleBlock */: + case 292 /* SyntaxKind.CaseClause */: return true; default: return false; @@ -164898,7 +166525,6 @@ var ts; (function (ts) { var refactor; (function (refactor) { - ; /** * Checks if some refactor info has refactor error info. */ @@ -165003,15 +166629,14 @@ var ts; // Imports will be copied to the new file anyway, and may still be needed in the old file. // Prologue directives will be copied to the new file and should be left in the old file. return !isPureImport(statement) && !ts.isPrologueDirective(statement); - ; } function isPureImport(node) { switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return true; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return !ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */); - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; @@ -165034,7 +166659,7 @@ var ts; function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); var prologueDirectives = ts.takeWhile(oldFile.statements, ts.isPrologueDirective); - if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + if (oldFile.externalModuleIndicator === undefined && oldFile.commonJsModuleIndicator === undefined && usage.oldImportsNeededByNewFile.size() === 0) { deleteMovedStatements(oldFile, toMove.ranges, changes); return __spreadArray(__spreadArray([], prologueDirectives, true), toMove.all, true); } @@ -165107,12 +166732,12 @@ var ts; } function getNamespaceLikeImport(node) { switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */ ? + case 269 /* SyntaxKind.ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */ ? node.importClause.namedBindings.name : undefined; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return node.name; - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return ts.tryCast(node.name, ts.isIdentifier); default: return ts.Debug.assertNever(node, "Unexpected node kind ".concat(node.kind)); @@ -165143,21 +166768,21 @@ var ts; var newNamespaceId = ts.factory.createIdentifier(newNamespaceName); var newModuleString = ts.factory.createStringLiteral(newModuleSpecifier); switch (node.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: return ts.factory.createImportDeclaration( /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString, /*assertClause*/ undefined); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return ts.factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString)); default: return ts.Debug.assertNever(node, "Unexpected node kind ".concat(node.kind)); } } function moduleSpecifierFromImport(i) { - return (i.kind === 266 /* SyntaxKind.ImportDeclaration */ ? i.moduleSpecifier - : i.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ ? i.moduleReference.expression + return (i.kind === 269 /* SyntaxKind.ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 268 /* SyntaxKind.ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]); } function forEachImportInStatement(statement, cb) { @@ -165227,15 +166852,15 @@ var ts; } function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { switch (importDecl.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); break; - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: if (isUnused(importDecl.name)) { changes.delete(sourceFile, importDecl); } break; - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); break; default: @@ -165248,7 +166873,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -165260,7 +166885,7 @@ var ts; if (namedBindingsUnused) { changes.replaceNode(sourceFile, importDecl.importClause, ts.factory.updateImportClause(importDecl.importClause, importDecl.importClause.isTypeOnly, name, /*namedBindings*/ undefined)); } - else if (namedBindings.kind === 269 /* SyntaxKind.NamedImports */) { + else if (namedBindings.kind === 272 /* SyntaxKind.NamedImports */) { for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { var element = _b[_i]; if (isUnused(element.name)) @@ -165275,12 +166900,17 @@ var ts; switch (name.kind) { case 79 /* SyntaxKind.Identifier */: if (isUnused(name)) { - changes.delete(sourceFile, name); + if (varDecl.initializer && ts.isRequireCall(varDecl.initializer, /*requireStringLiteralLikeArgument*/ true)) { + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && ts.length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl); + } + else { + changes.delete(sourceFile, name); + } } break; - case 202 /* SyntaxKind.ArrayBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: break; - case 201 /* SyntaxKind.ObjectBindingPattern */: + case 203 /* SyntaxKind.ObjectBindingPattern */: if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } @@ -165322,7 +166952,7 @@ var ts; if (markSeenTop(top)) { addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); } - if (ts.hasSyntacticModifier(decl, 512 /* ModifierFlags.Default */)) { + if (ts.hasSyntacticModifier(decl, 1024 /* ModifierFlags.Default */)) { oldFileDefault = name; } else { @@ -165410,14 +167040,14 @@ var ts; // Below should all be utilities function isInImport(decl) { switch (decl.kind) { - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 267 /* SyntaxKind.ImportClause */: - case 268 /* SyntaxKind.NamespaceImport */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 270 /* SyntaxKind.ImportClause */: + case 271 /* SyntaxKind.NamespaceImport */: return true; - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return isVariableDeclarationInImport(decl); - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); default: return false; @@ -165429,7 +167059,7 @@ var ts; } function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { - case 266 /* SyntaxKind.ImportDeclaration */: { + case 269 /* SyntaxKind.ImportDeclaration */: { var clause = i.importClause; if (!clause) return undefined; @@ -165439,9 +167069,9 @@ var ts; ? ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined) : undefined; } - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return keep(i.name) ? i : undefined; - case 254 /* SyntaxKind.VariableDeclaration */: { + case 257 /* SyntaxKind.VariableDeclaration */: { var name = filterBindingName(i.name, keep); return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; } @@ -165450,7 +167080,7 @@ var ts; } } function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { + if (namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */) { return keep(namedBindings.name) ? namedBindings : undefined; } else { @@ -165462,9 +167092,9 @@ var ts; switch (name.kind) { case 79 /* SyntaxKind.Identifier */: return keep(name) ? name : undefined; - case 202 /* SyntaxKind.ArrayBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: return name; - case 201 /* SyntaxKind.ObjectBindingPattern */: { + case 203 /* SyntaxKind.ObjectBindingPattern */: { // We can't handle nested destructurings or property names well here, so just copy them all. var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); return newElements.length ? ts.factory.createObjectBindingPattern(newElements) : undefined; @@ -165507,6 +167137,9 @@ var ts; ts.copyEntries(this.map, clone.map); return clone; }; + SymbolSet.prototype.size = function () { + return this.map.size; + }; return SymbolSet; }()); function isTopLevelDeclaration(node) { @@ -165521,13 +167154,13 @@ var ts; } function isNonVariableTopLevelDeclaration(node) { switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return true; default: return false; @@ -165535,17 +167168,17 @@ var ts; } function forEachTopLevelDeclaration(statement, cb) { switch (statement.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return cb(statement); - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); - case 238 /* SyntaxKind.ExpressionStatement */: { + case 241 /* SyntaxKind.ExpressionStatement */: { var expression = statement.expression; return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* AssignmentDeclarationKind.ExportsProperty */ ? cb(statement) @@ -165557,8 +167190,8 @@ var ts; switch (name.kind) { case 79 /* SyntaxKind.Identifier */: return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); - case 202 /* SyntaxKind.ArrayBindingPattern */: - case 201 /* SyntaxKind.ObjectBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: + case 203 /* SyntaxKind.ObjectBindingPattern */: return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); default: return ts.Debug.assertNever(name, "Unexpected name kind ".concat(name.kind)); @@ -165569,9 +167202,9 @@ var ts; } function getTopLevelDeclarationStatement(d) { switch (d.kind) { - case 254 /* SyntaxKind.VariableDeclaration */: + case 257 /* SyntaxKind.VariableDeclaration */: return d.parent.parent; - case 203 /* SyntaxKind.BindingElement */: + case 205 /* SyntaxKind.BindingElement */: return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); default: return d; @@ -165595,7 +167228,8 @@ var ts; if (useEs6Exports) { return !ts.isExpressionStatement(decl) && ts.hasSyntacticModifier(decl, 1 /* ModifierFlags.Export */) || !!(name && ((_a = sourceFile.symbol.exports) === null || _a === void 0 ? void 0 : _a.has(name.escapedText))); } - return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + return !!sourceFile.symbol && !!sourceFile.symbol.exports && + getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); } function addExport(decl, useEs6Exports) { return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); @@ -165603,24 +167237,24 @@ var ts; function addEs6Export(d) { var modifiers = ts.canHaveModifiers(d) ? ts.concatenate([ts.factory.createModifier(93 /* SyntaxKind.ExportKeyword */)], ts.getModifiers(d)) : undefined; switch (d.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return ts.factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: var decorators = ts.canHaveDecorators(d) ? ts.getDecorators(d) : undefined; return ts.factory.updateClassDeclaration(d, ts.concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return ts.factory.updateVariableStatement(d, modifiers, d.declarationList); - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: return ts.factory.updateModuleDeclaration(d, modifiers, d.name, d.body); - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: return ts.factory.updateEnumDeclaration(d, modifiers, d.name, d.members); - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return ts.factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); - case 258 /* SyntaxKind.InterfaceDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: return ts.factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return ts.factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(d, "Unexpected declaration kind ".concat(d.kind)); @@ -165631,18 +167265,18 @@ var ts; } function getNamesToExportInCommonJS(decl) { switch (decl.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: return [decl.name.text]; // TODO: GH#18217 - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); - case 261 /* SyntaxKind.ModuleDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: return ts.emptyArray; - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: return ts.Debug.fail("Can't export an ExpressionStatement"); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(decl, "Unexpected decl kind ".concat(decl.kind)); @@ -165983,15 +167617,15 @@ var ts; var parent = functionReference.parent; switch (parent.kind) { // foo(...) or super(...) or new Foo(...) - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: var callOrNewExpression = ts.tryCast(parent, ts.isCallOrNewExpression); if (callOrNewExpression && callOrNewExpression.expression === functionReference) { return callOrNewExpression; } break; // x.foo(...) - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { var callOrNewExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallOrNewExpression); @@ -166001,7 +167635,7 @@ var ts; } break; // x["foo"](...) - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { var callOrNewExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallOrNewExpression); @@ -166020,14 +167654,14 @@ var ts; var parent = reference.parent; switch (parent.kind) { // `C.foo` - case 206 /* SyntaxKind.PropertyAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.expression === reference) { return propertyAccessExpression; } break; // `C["foo"]` - case 207 /* SyntaxKind.ElementAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.expression === reference) { return elementAccessExpression; @@ -166073,16 +167707,16 @@ var ts; if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; switch (functionDeclaration.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: if (ts.isObjectLiteralExpression(functionDeclaration.parent)) { var contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); // don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change return ((_a = contextualSymbol === null || contextualSymbol === void 0 ? void 0 : contextualSymbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); } return isSingleImplementation(functionDeclaration, checker); - case 171 /* SyntaxKind.Constructor */: + case 173 /* SyntaxKind.Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); } @@ -166090,8 +167724,8 @@ var ts; return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); } - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: return isValidVariableDeclaration(functionDeclaration.parent); } return false; @@ -166239,7 +167873,7 @@ var ts; } function getClassNames(constructorDeclaration) { switch (constructorDeclaration.parent.kind) { - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: var classDeclaration = constructorDeclaration.parent; if (classDeclaration.name) return [classDeclaration.name]; @@ -166247,7 +167881,7 @@ var ts; // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` var defaultModifier = ts.Debug.checkDefined(ts.findModifier(classDeclaration, 88 /* SyntaxKind.DefaultKeyword */), "Nameless class declaration should be a default export"); return [defaultModifier]; - case 226 /* SyntaxKind.ClassExpression */: + case 228 /* SyntaxKind.ClassExpression */: var classExpression = constructorDeclaration.parent; var variableDeclaration = constructorDeclaration.parent.parent; var className = classExpression.name; @@ -166258,25 +167892,25 @@ var ts; } function getFunctionNames(functionDeclaration) { switch (functionDeclaration.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: if (functionDeclaration.name) return [functionDeclaration.name]; // If the function declaration doesn't have a name, it should have a default modifier. // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` var defaultModifier = ts.Debug.checkDefined(ts.findModifier(functionDeclaration, 88 /* SyntaxKind.DefaultKeyword */), "Nameless function declaration should be a default export"); return [defaultModifier]; - case 169 /* SyntaxKind.MethodDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: return [functionDeclaration.name]; - case 171 /* SyntaxKind.Constructor */: - var ctrKeyword = ts.Debug.checkDefined(ts.findChildOfKind(functionDeclaration, 134 /* SyntaxKind.ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword"); - if (functionDeclaration.parent.kind === 226 /* SyntaxKind.ClassExpression */) { + case 173 /* SyntaxKind.Constructor */: + var ctrKeyword = ts.Debug.checkDefined(ts.findChildOfKind(functionDeclaration, 135 /* SyntaxKind.ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword"); + if (functionDeclaration.parent.kind === 228 /* SyntaxKind.ClassExpression */) { var variableDeclaration = functionDeclaration.parent.parent; return [variableDeclaration.name, ctrKeyword]; } return [ctrKeyword]; - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: return [functionDeclaration.parent.name]; - case 213 /* SyntaxKind.FunctionExpression */: + case 215 /* SyntaxKind.FunctionExpression */: if (functionDeclaration.name) return [functionDeclaration.name, functionDeclaration.parent.name]; return [functionDeclaration.parent.name]; @@ -166367,11 +168001,11 @@ var ts; function getParentBinaryExpression(expr) { var container = ts.findAncestor(expr.parent, function (n) { switch (n.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 207 /* SyntaxKind.ElementAccessExpression */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 209 /* SyntaxKind.ElementAccessExpression */: return false; - case 223 /* SyntaxKind.TemplateExpression */: - case 221 /* SyntaxKind.BinaryExpression */: + case 225 /* SyntaxKind.TemplateExpression */: + case 223 /* SyntaxKind.BinaryExpression */: return !(ts.isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); default: return "quit"; @@ -166819,10 +168453,10 @@ var ts; } function isConvertibleDeclaration(node) { switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: - case 169 /* SyntaxKind.MethodDeclaration */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: + case 171 /* SyntaxKind.MethodDeclaration */: return true; default: return false; @@ -166867,7 +168501,7 @@ var ts; this.kind = kind; } NodeObject.prototype.assertHasRealPosition = function (message) { - // eslint-disable-next-line debug-assert + // eslint-disable-next-line local/debug-assert ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); }; NodeObject.prototype.getSourceFile = function () { @@ -166924,8 +168558,8 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 309 /* SyntaxKind.FirstJSDocNode */ || kid.kind > 347 /* SyntaxKind.LastJSDocNode */; }); - return child.kind < 161 /* SyntaxKind.FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 312 /* SyntaxKind.FirstJSDocNode */ || kid.kind > 350 /* SyntaxKind.LastJSDocNode */; }); + return child.kind < 163 /* SyntaxKind.FirstNode */ ? child : child.getFirstToken(sourceFile); }; @@ -166936,7 +168570,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 161 /* SyntaxKind.FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 163 /* SyntaxKind.FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -166996,7 +168630,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(348 /* SyntaxKind.SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(351 /* SyntaxKind.SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { @@ -167345,7 +168979,7 @@ var ts; var _a; if (!seenSymbols_1.has(symbol)) { seenSymbols_1.add(symbol); - if (declaration.kind === 172 /* SyntaxKind.GetAccessor */ || declaration.kind === 173 /* SyntaxKind.SetAccessor */) { + if (declaration.kind === 174 /* SyntaxKind.GetAccessor */ || declaration.kind === 175 /* SyntaxKind.SetAccessor */) { return symbol.getContextualJsDocTags(declaration, checker); } return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 ? symbol.getJsDocTags() : undefined; @@ -167355,8 +168989,8 @@ var ts; tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); } }; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; _loop_20(declaration); } } @@ -167372,7 +169006,7 @@ var ts; var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { if (!seenSymbols_2.has(symbol)) { seenSymbols_2.add(symbol); - if (declaration.kind === 172 /* SyntaxKind.GetAccessor */ || declaration.kind === 173 /* SyntaxKind.SetAccessor */) { + if (declaration.kind === 174 /* SyntaxKind.GetAccessor */ || declaration.kind === 175 /* SyntaxKind.SetAccessor */) { return symbol.getContextualDocumentationComment(declaration, checker); } return symbol.getDocumentationComment(checker); @@ -167382,8 +169016,8 @@ var ts; if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); }; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; _loop_21(declaration); } } @@ -167391,7 +169025,7 @@ var ts; } function findBaseOfDeclaration(checker, declaration, cb) { var _a; - var classOrInterfaceDeclaration = ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.kind) === 171 /* SyntaxKind.Constructor */ ? declaration.parent.parent : declaration.parent; + var classOrInterfaceDeclaration = ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.kind) === 173 /* SyntaxKind.Constructor */ ? declaration.parent.parent : declaration.parent; if (!classOrInterfaceDeclaration) return; var isStaticMember = ts.hasStaticModifier(declaration); @@ -167406,7 +169040,7 @@ var ts; __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { var _this = _super.call(this, kind, pos, end) || this; - _this.kind = 305 /* SyntaxKind.SourceFile */; + _this.kind = 308 /* SyntaxKind.SourceFile */; return _this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { @@ -167465,10 +169099,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 256 /* SyntaxKind.FunctionDeclaration */: - case 213 /* SyntaxKind.FunctionExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 215 /* SyntaxKind.FunctionExpression */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -167488,31 +169122,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 261 /* SyntaxKind.ModuleDeclaration */: - case 265 /* SyntaxKind.ImportEqualsDeclaration */: - case 275 /* SyntaxKind.ExportSpecifier */: - case 270 /* SyntaxKind.ImportSpecifier */: - case 267 /* SyntaxKind.ImportClause */: - case 268 /* SyntaxKind.NamespaceImport */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 182 /* SyntaxKind.TypeLiteral */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 228 /* SyntaxKind.ClassExpression */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: + case 278 /* SyntaxKind.ExportSpecifier */: + case 273 /* SyntaxKind.ImportSpecifier */: + case 270 /* SyntaxKind.ImportClause */: + case 271 /* SyntaxKind.NamespaceImport */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 184 /* SyntaxKind.TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: // Only consider parameter properties if (!ts.hasSyntacticModifier(node, 16476 /* ModifierFlags.ParameterPropertyModifier */)) { break; } // falls through - case 254 /* SyntaxKind.VariableDeclaration */: - case 203 /* SyntaxKind.BindingElement */: { + case 257 /* SyntaxKind.VariableDeclaration */: + case 205 /* SyntaxKind.BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -167523,12 +169157,12 @@ var ts; } } // falls through - case 299 /* SyntaxKind.EnumMember */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: + case 302 /* SyntaxKind.EnumMember */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: addDeclaration(node); break; - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; var exportDeclaration = node; @@ -167541,7 +169175,7 @@ var ts; } } break; - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -167553,7 +169187,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { + if (importClause.namedBindings.kind === 271 /* SyntaxKind.NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -167562,7 +169196,7 @@ var ts; } } break; - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: if (ts.getAssignmentDeclarationKind(node) !== 0 /* AssignmentDeclarationKind.None */) { addDeclaration(node); } @@ -167908,7 +169542,7 @@ var ts; var rootFileNames = host.getScriptFileNames().slice(); // Get a fresh cache of the host information var newSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); - var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var hasInvalidatedResolutions = host.hasInvalidatedResolutions || ts.returnFalse; var hasChangedAutomaticTypeDirectiveNames = ts.maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); var projectReferences = (_b = host.getProjectReferences) === null || _b === void 0 ? void 0 : _b.call(host); var parsedCommandLines; @@ -167939,7 +169573,7 @@ var ts; }, onReleaseOldSourceFile: onReleaseOldSourceFile, onReleaseParsedCommandLine: onReleaseParsedCommandLine, - hasInvalidatedResolution: hasInvalidatedResolution, + hasInvalidatedResolutions: hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, trace: ts.maybeBind(host, host.trace), resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), @@ -167974,8 +169608,12 @@ var ts; getCurrentDirectory: compilerHost.getCurrentDirectory, onUnRecoverableConfigFileDiagnostic: ts.noop, }; + // The call to isProgramUptoDate below may refer back to documentRegistryBucketKey; + // calculate this early so it's not undefined if downleveled to a var (or, if emitted + // as a const variable without downleveling, doesn't crash). + var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, function (fileName) { return compilerHost.fileExists(fileName); }, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, function (fileName) { return compilerHost.fileExists(fileName); }, hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -167983,7 +169621,6 @@ var ts; // instance. If we cancel midway through, we may end up in an inconsistent state where // the program points to old source files that have been invalidated because of // incremental parsing. - var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); var options = { rootNames: rootFileNames, options: newSettings, @@ -168279,16 +169916,16 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: return !ts.isLabelName(node) && !ts.isTagName(node) && !ts.isConstTypeReference(node.parent); - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 161 /* SyntaxKind.QualifiedName */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 163 /* SyntaxKind.QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` return !ts.isInComment(sourceFile, position); case 108 /* SyntaxKind.ThisKeyword */: - case 192 /* SyntaxKind.ThisType */: + case 194 /* SyntaxKind.ThisType */: case 106 /* SyntaxKind.SuperKeyword */: - case 197 /* SyntaxKind.NamedTupleMember */: + case 199 /* SyntaxKind.NamedTupleMember */: return true; - case 231 /* SyntaxKind.MetaProperty */: + case 233 /* SyntaxKind.MetaProperty */: return ts.isImportMeta(node); default: return false; @@ -168395,15 +170032,15 @@ var ts; return undefined; } switch (node.kind) { - case 206 /* SyntaxKind.PropertyAccessExpression */: - case 161 /* SyntaxKind.QualifiedName */: + case 208 /* SyntaxKind.PropertyAccessExpression */: + case 163 /* SyntaxKind.QualifiedName */: case 10 /* SyntaxKind.StringLiteral */: case 95 /* SyntaxKind.FalseKeyword */: case 110 /* SyntaxKind.TrueKeyword */: case 104 /* SyntaxKind.NullKeyword */: case 106 /* SyntaxKind.SuperKeyword */: case 108 /* SyntaxKind.ThisKeyword */: - case 192 /* SyntaxKind.ThisType */: + case 194 /* SyntaxKind.ThisType */: case 79 /* SyntaxKind.Identifier */: break; // Cant create the text span @@ -168420,7 +170057,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 261 /* SyntaxKind.ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 264 /* SyntaxKind.ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -168550,12 +170187,14 @@ var ts; return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } function organizeImports(args, formatOptions, preferences) { + var _a; if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); ts.Debug.assert(args.type === "file"); var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); + var mode = (_a = args.mode) !== null && _a !== void 0 ? _a : (args.skipDestructiveCodeActions ? "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ : "All" /* OrganizeImportsMode.All */); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, mode); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } @@ -169169,7 +170808,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 277 /* SyntaxKind.ExternalModuleReference */ || + node.parent.kind === 280 /* SyntaxKind.ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -169187,13 +170826,13 @@ var ts; case 10 /* SyntaxKind.StringLiteral */: case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: case 8 /* SyntaxKind.NumericLiteral */: - if (node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) { + if (node.parent.kind === 164 /* SyntaxKind.ComputedPropertyName */) { return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 79 /* SyntaxKind.Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 205 /* SyntaxKind.ObjectLiteralExpression */ || node.parent.parent.kind === 286 /* SyntaxKind.JsxAttributes */) && + (node.parent.parent.kind === 207 /* SyntaxKind.ObjectLiteralExpression */ || node.parent.parent.kind === 289 /* SyntaxKind.JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -169235,7 +170874,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 207 /* SyntaxKind.ElementAccessExpression */ && + node.parent.kind === 209 /* SyntaxKind.ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -169328,114 +170967,114 @@ var ts; if (node) { var parent = node.parent; switch (node.kind) { - case 237 /* SyntaxKind.VariableStatement */: + case 240 /* SyntaxKind.VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 254 /* SyntaxKind.VariableDeclaration */: - case 167 /* SyntaxKind.PropertyDeclaration */: - case 166 /* SyntaxKind.PropertySignature */: + case 257 /* SyntaxKind.VariableDeclaration */: + case 169 /* SyntaxKind.PropertyDeclaration */: + case 168 /* SyntaxKind.PropertySignature */: return spanInVariableDeclaration(node); - case 164 /* SyntaxKind.Parameter */: + case 166 /* SyntaxKind.Parameter */: return spanInParameterDeclaration(node); - case 256 /* SyntaxKind.FunctionDeclaration */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 171 /* SyntaxKind.Constructor */: - case 213 /* SyntaxKind.FunctionExpression */: - case 214 /* SyntaxKind.ArrowFunction */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 173 /* SyntaxKind.Constructor */: + case 215 /* SyntaxKind.FunctionExpression */: + case 216 /* SyntaxKind.ArrowFunction */: return spanInFunctionDeclaration(node); - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 262 /* SyntaxKind.ModuleBlock */: + case 265 /* SyntaxKind.ModuleBlock */: return spanInBlock(node); - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return spanInBlock(node.block); - case 238 /* SyntaxKind.ExpressionStatement */: + case 241 /* SyntaxKind.ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 247 /* SyntaxKind.ReturnStatement */: + case 250 /* SyntaxKind.ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 241 /* SyntaxKind.WhileStatement */: + case 244 /* SyntaxKind.WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 240 /* SyntaxKind.DoStatement */: + case 243 /* SyntaxKind.DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 253 /* SyntaxKind.DebuggerStatement */: + case 256 /* SyntaxKind.DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 239 /* SyntaxKind.IfStatement */: + case 242 /* SyntaxKind.IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 250 /* SyntaxKind.LabeledStatement */: + case 253 /* SyntaxKind.LabeledStatement */: // span in statement return spanInNode(node.statement); - case 246 /* SyntaxKind.BreakStatement */: - case 245 /* SyntaxKind.ContinueStatement */: + case 249 /* SyntaxKind.BreakStatement */: + case 248 /* SyntaxKind.ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 242 /* SyntaxKind.ForStatement */: + case 245 /* SyntaxKind.ForStatement */: return spanInForStatement(node); - case 243 /* SyntaxKind.ForInStatement */: + case 246 /* SyntaxKind.ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 244 /* SyntaxKind.ForOfStatement */: + case 247 /* SyntaxKind.ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 249 /* SyntaxKind.SwitchStatement */: + case 252 /* SyntaxKind.SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 289 /* SyntaxKind.CaseClause */: - case 290 /* SyntaxKind.DefaultClause */: + case 292 /* SyntaxKind.CaseClause */: + case 293 /* SyntaxKind.DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 252 /* SyntaxKind.TryStatement */: + case 255 /* SyntaxKind.TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 251 /* SyntaxKind.ThrowStatement */: + case 254 /* SyntaxKind.ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 271 /* SyntaxKind.ExportAssignment */: + case 274 /* SyntaxKind.ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 265 /* SyntaxKind.ImportEqualsDeclaration */: + case 268 /* SyntaxKind.ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 266 /* SyntaxKind.ImportDeclaration */: + case 269 /* SyntaxKind.ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 272 /* SyntaxKind.ExportDeclaration */: + case 275 /* SyntaxKind.ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* ModuleInstanceState.Instantiated */) { return undefined; } // falls through - case 257 /* SyntaxKind.ClassDeclaration */: - case 260 /* SyntaxKind.EnumDeclaration */: - case 299 /* SyntaxKind.EnumMember */: - case 203 /* SyntaxKind.BindingElement */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 302 /* SyntaxKind.EnumMember */: + case 205 /* SyntaxKind.BindingElement */: // span on complete node return textSpan(node); - case 248 /* SyntaxKind.WithStatement */: + case 251 /* SyntaxKind.WithStatement */: // span in statement return spanInNode(node.statement); - case 165 /* SyntaxKind.Decorator */: + case 167 /* SyntaxKind.Decorator */: return spanInNodeArray(parent.modifiers, node, ts.isDecorator); - case 201 /* SyntaxKind.ObjectBindingPattern */: - case 202 /* SyntaxKind.ArrayBindingPattern */: + case 203 /* SyntaxKind.ObjectBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 258 /* SyntaxKind.InterfaceDeclaration */: - case 259 /* SyntaxKind.TypeAliasDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: return undefined; // Tokens: case 26 /* SyntaxKind.SemicolonToken */: @@ -169465,7 +171104,7 @@ var ts; case 83 /* SyntaxKind.CatchKeyword */: case 96 /* SyntaxKind.FinallyKeyword */: return spanInNextNode(node); - case 160 /* SyntaxKind.OfKeyword */: + case 162 /* SyntaxKind.OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -169478,13 +171117,13 @@ var ts; // `a` or `...c` or `d: x` from // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 79 /* SyntaxKind.Identifier */ || - node.kind === 225 /* SyntaxKind.SpreadElement */ || - node.kind === 296 /* SyntaxKind.PropertyAssignment */ || - node.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */) && + node.kind === 227 /* SyntaxKind.SpreadElement */ || + node.kind === 299 /* SyntaxKind.PropertyAssignment */ || + node.kind === 300 /* SyntaxKind.ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 221 /* SyntaxKind.BinaryExpression */) { + if (node.kind === 223 /* SyntaxKind.BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -169506,22 +171145,22 @@ var ts; } if (ts.isExpressionNode(node)) { switch (parent.kind) { - case 240 /* SyntaxKind.DoStatement */: + case 243 /* SyntaxKind.DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 165 /* SyntaxKind.Decorator */: + case 167 /* SyntaxKind.Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 242 /* SyntaxKind.ForStatement */: - case 244 /* SyntaxKind.ForOfStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return textSpan(node); - case 221 /* SyntaxKind.BinaryExpression */: + case 223 /* SyntaxKind.BinaryExpression */: if (node.parent.operatorToken.kind === 27 /* SyntaxKind.CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 214 /* SyntaxKind.ArrowFunction */: + case 216 /* SyntaxKind.ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -169530,21 +171169,21 @@ var ts; } } switch (node.parent.kind) { - case 296 /* SyntaxKind.PropertyAssignment */: + case 299 /* SyntaxKind.PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 211 /* SyntaxKind.TypeAssertionExpression */: + case 213 /* SyntaxKind.TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 254 /* SyntaxKind.VariableDeclaration */: - case 164 /* SyntaxKind.Parameter */: { + case 257 /* SyntaxKind.VariableDeclaration */: + case 166 /* SyntaxKind.Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { @@ -169552,7 +171191,7 @@ var ts; } break; } - case 221 /* SyntaxKind.BinaryExpression */: { + case 223 /* SyntaxKind.BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -169582,7 +171221,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 243 /* SyntaxKind.ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 246 /* SyntaxKind.ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } var parent = variableDeclaration.parent; @@ -169594,7 +171233,7 @@ var ts; // or its declaration from 'for of' if ((ts.hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer) || ts.hasSyntacticModifier(variableDeclaration, 1 /* ModifierFlags.Export */) || - parent.parent.kind === 244 /* SyntaxKind.ForOfStatement */) { + parent.parent.kind === 247 /* SyntaxKind.ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -169635,7 +171274,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasSyntacticModifier(functionDeclaration, 1 /* ModifierFlags.Export */) || - (functionDeclaration.parent.kind === 257 /* SyntaxKind.ClassDeclaration */ && functionDeclaration.kind !== 171 /* SyntaxKind.Constructor */); + (functionDeclaration.parent.kind === 260 /* SyntaxKind.ClassDeclaration */ && functionDeclaration.kind !== 173 /* SyntaxKind.Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -169658,26 +171297,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 261 /* SyntaxKind.ModuleDeclaration */: + case 264 /* SyntaxKind.ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* ModuleInstanceState.Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement // falls through - case 241 /* SyntaxKind.WhileStatement */: - case 239 /* SyntaxKind.IfStatement */: - case 243 /* SyntaxKind.ForInStatement */: + case 244 /* SyntaxKind.WhileStatement */: + case 242 /* SyntaxKind.IfStatement */: + case 246 /* SyntaxKind.ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 242 /* SyntaxKind.ForStatement */: - case 244 /* SyntaxKind.ForOfStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 247 /* SyntaxKind.ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 255 /* SyntaxKind.VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 258 /* SyntaxKind.VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -169702,21 +171341,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 227 /* SyntaxKind.OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 229 /* SyntaxKind.OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 203 /* SyntaxKind.BindingElement */) { + if (bindingPattern.parent.kind === 205 /* SyntaxKind.BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 202 /* SyntaxKind.ArrayBindingPattern */ && node.kind !== 201 /* SyntaxKind.ObjectBindingPattern */); - var elements = node.kind === 204 /* SyntaxKind.ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 227 /* SyntaxKind.OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 204 /* SyntaxKind.ArrayBindingPattern */ && node.kind !== 203 /* SyntaxKind.ObjectBindingPattern */); + var elements = node.kind === 206 /* SyntaxKind.ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 229 /* SyntaxKind.OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -169724,18 +171363,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 221 /* SyntaxKind.BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 223 /* SyntaxKind.BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 260 /* SyntaxKind.EnumDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 257 /* SyntaxKind.ClassDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 263 /* SyntaxKind.CaseBlock */: + case 266 /* SyntaxKind.CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -169743,25 +171382,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 262 /* SyntaxKind.ModuleBlock */: + case 265 /* SyntaxKind.ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* ModuleInstanceState.Instantiated */) { return undefined; } // falls through - case 260 /* SyntaxKind.EnumDeclaration */: - case 257 /* SyntaxKind.ClassDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 260 /* SyntaxKind.ClassDeclaration */: // Span on close brace token return textSpan(node); - case 235 /* SyntaxKind.Block */: + case 238 /* SyntaxKind.Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 292 /* SyntaxKind.CatchClause */: + case 295 /* SyntaxKind.CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 263 /* SyntaxKind.CaseBlock */: + case 266 /* SyntaxKind.CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -169769,7 +171408,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 201 /* SyntaxKind.ObjectBindingPattern */: + case 203 /* SyntaxKind.ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -169785,7 +171424,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 202 /* SyntaxKind.ArrayBindingPattern */: + case 204 /* SyntaxKind.ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -169800,12 +171439,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 240 /* SyntaxKind.DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 208 /* SyntaxKind.CallExpression */ || - node.parent.kind === 209 /* SyntaxKind.NewExpression */) { + if (node.parent.kind === 243 /* SyntaxKind.DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 210 /* SyntaxKind.CallExpression */ || + node.parent.kind === 211 /* SyntaxKind.NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */) { + if (node.parent.kind === 214 /* SyntaxKind.ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -169814,21 +171453,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 213 /* SyntaxKind.FunctionExpression */: - case 256 /* SyntaxKind.FunctionDeclaration */: - case 214 /* SyntaxKind.ArrowFunction */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 168 /* SyntaxKind.MethodSignature */: - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 171 /* SyntaxKind.Constructor */: - case 241 /* SyntaxKind.WhileStatement */: - case 240 /* SyntaxKind.DoStatement */: - case 242 /* SyntaxKind.ForStatement */: - case 244 /* SyntaxKind.ForOfStatement */: - case 208 /* SyntaxKind.CallExpression */: - case 209 /* SyntaxKind.NewExpression */: - case 212 /* SyntaxKind.ParenthesizedExpression */: + case 215 /* SyntaxKind.FunctionExpression */: + case 259 /* SyntaxKind.FunctionDeclaration */: + case 216 /* SyntaxKind.ArrowFunction */: + case 171 /* SyntaxKind.MethodDeclaration */: + case 170 /* SyntaxKind.MethodSignature */: + case 174 /* SyntaxKind.GetAccessor */: + case 175 /* SyntaxKind.SetAccessor */: + case 173 /* SyntaxKind.Constructor */: + case 244 /* SyntaxKind.WhileStatement */: + case 243 /* SyntaxKind.DoStatement */: + case 245 /* SyntaxKind.ForStatement */: + case 247 /* SyntaxKind.ForOfStatement */: + case 210 /* SyntaxKind.CallExpression */: + case 211 /* SyntaxKind.NewExpression */: + case 214 /* SyntaxKind.ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -169838,20 +171477,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 296 /* SyntaxKind.PropertyAssignment */ || - node.parent.kind === 164 /* SyntaxKind.Parameter */) { + node.parent.kind === 299 /* SyntaxKind.PropertyAssignment */ || + node.parent.kind === 166 /* SyntaxKind.Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 211 /* SyntaxKind.TypeAssertionExpression */) { + if (node.parent.kind === 213 /* SyntaxKind.TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 240 /* SyntaxKind.DoStatement */) { + if (node.parent.kind === 243 /* SyntaxKind.DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -169859,7 +171498,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 244 /* SyntaxKind.ForOfStatement */) { + if (node.parent.kind === 247 /* SyntaxKind.ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -169908,7 +171547,7 @@ var debugObjectHost = (function () { return this; })(); // We need to use 'null' to interface with the managed side. -/* eslint-disable no-in-operator */ +/* eslint-disable local/no-in-operator */ /* @internal */ var ts; (function (ts) { @@ -170708,7 +172347,7 @@ var ts; }()); ts.TypeScriptServicesFactory = TypeScriptServicesFactory; })(ts || (ts = {})); -/* eslint-enable no-in-operator */ +/* eslint-enable local/no-in-operator */ // We polyfill `globalThis` here so re can reliably patch the global scope // in the contexts we want to in the same way across script and module formats /* eslint-enable no-var */ @@ -171478,7 +173117,7 @@ var ts; if (typeof value === "number") { return ts.factory.createNumericLiteral(value); } - // eslint-disable-next-line no-in-operator + // eslint-disable-next-line local/no-in-operator if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt return ts.factory.createBigIntLiteral(value); } @@ -171506,7 +173145,7 @@ var ts; } else { type = operatorOrType; - operator = 140 /* SyntaxKind.KeyOfKeyword */; + operator = 141 /* SyntaxKind.KeyOfKeyword */; } return ts.factory.createTypeOperatorNode(operator, type); }, factoryDeprecation); @@ -171684,7 +173323,7 @@ var ts; ts.createNode = ts.Debug.deprecate(function createNode(kind, pos, end) { if (pos === void 0) { pos = 0; } if (end === void 0) { end = 0; } - return ts.setTextRangePosEnd(kind === 305 /* SyntaxKind.SourceFile */ ? ts.parseBaseNodeFactory.createBaseSourceFileNode(kind) : + return ts.setTextRangePosEnd(kind === 308 /* SyntaxKind.SourceFile */ ? ts.parseBaseNodeFactory.createBaseSourceFileNode(kind) : kind === 79 /* SyntaxKind.Identifier */ ? ts.parseBaseNodeFactory.createBaseIdentifierNode(kind) : kind === 80 /* SyntaxKind.PrivateIdentifier */ ? ts.parseBaseNodeFactory.createBasePrivateIdentifierNode(kind) : !ts.isNodeKind(kind) ? ts.parseBaseNodeFactory.createBaseTokenNode(kind) : @@ -171714,7 +173353,7 @@ var ts; (function (ts) { /** @deprecated Use `isTypeAssertionExpression` instead. */ ts.isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node) { - return node.kind === 211 /* SyntaxKind.TypeAssertionExpression */; + return node.kind === 213 /* SyntaxKind.TypeAssertionExpression */; }, { since: "4.0", warnAfter: "4.1", diff --git a/cli/tsc/README.md b/cli/tsc/README.md index 657aa2b5a4..f6d98abe7d 100644 --- a/cli/tsc/README.md +++ b/cli/tsc/README.md @@ -16,6 +16,7 @@ It works like this currently: 1. This commit has a "deno.ts" file in it. Read the instructions in it. 1. Copy typescript.js into Deno repo. 1. Copy d.ts files into dts directory. +1. Review the copied files, removing and reverting what's necessary So that might look something like this: @@ -29,6 +30,6 @@ git checkout -b branch_v3.9.7 git cherry pick npm install gulp local -rsync lib/typescript.js ~/src/deno/cli/tsc/00_typescript.js -rsync --exclude=protocol.d.ts --exclude=tsserverlibrary.d.ts --exclude=typescriptServices.d.ts lib/*.d.ts ~/src/deno/cli/tsc/dts/ +rsync built/local/typescript.js ~/src/deno/cli/tsc/00_typescript.js +rsync --exclude=protocol.d.ts --exclude=tsserverlibrary.d.ts --exclude=typescriptServices.d.ts built/local/*.d.ts ~/src/deno/cli/tsc/dts/ ``` diff --git a/cli/tsc/diagnostics.rs b/cli/tsc/diagnostics.rs index 05502dca46..4413398c24 100644 --- a/cli/tsc/diagnostics.rs +++ b/cli/tsc/diagnostics.rs @@ -31,6 +31,7 @@ const UNSTABLE_DENO_PROPS: &[&str] = &[ "umask", "spawnChild", "Child", + "ChildProcess", "spawn", "spawnSync", "SpawnOptions", diff --git a/cli/tsc/dts/lib.deno.unstable.d.ts b/cli/tsc/dts/lib.deno.unstable.d.ts index eaa40abc56..9e91c88004 100644 --- a/cli/tsc/dts/lib.deno.unstable.d.ts +++ b/cli/tsc/dts/lib.deno.unstable.d.ts @@ -443,7 +443,7 @@ declare namespace Deno { /** The definition of the function. */ definition: Fn; - constructor(pointer: PointerValue, definition: Fn); + constructor(pointer: PointerValue, definition: Const); /** Call the foreign function. */ call: FromForeignFunction; @@ -494,7 +494,7 @@ declare namespace Deno { Definition extends UnsafeCallbackDefinition = UnsafeCallbackDefinition, > { constructor( - definition: Definition, + definition: Const, callback: UnsafeCallbackFunction< Definition["parameters"], Definition["result"] @@ -562,6 +562,17 @@ declare namespace Deno { close(): void; } + /** + * This magic code used to implement better type hints for {@linkcode Deno.dlopen} + */ + type Cast = A extends B ? A : B; + type Const = Cast< + T, + | (T extends string | number | bigint | boolean ? T : never) + | { [K in keyof T]: Const } + | [] + >; + /** **UNSTABLE**: New API, yet to be vetted. * * Opens an external dynamic library and registers symbols, making foreign @@ -611,7 +622,7 @@ declare namespace Deno { */ export function dlopen( filename: string | URL, - symbols: S, + symbols: Const, ): DynamicLibrary; /** **UNSTABLE**: New API, yet to be vetted. @@ -1639,14 +1650,14 @@ declare namespace Deno { * ], * stdin: "piped", * }); - * command.spawn(); + * const child = command.spawn(); * * // open a file and pipe the subprocess output to it. - * command.stdout.pipeTo(Deno.openSync("output").writable); + * child.stdout.pipeTo(Deno.openSync("output").writable); * * // manually close stdin - * command.stdin.close(); - * const status = await command.status; + * child.stdin.close(); + * const status = await child.status; * ``` * * ```ts @@ -1678,13 +1689,6 @@ declare namespace Deno { * @category Sub Process */ export class Command { - get stdin(): WritableStream; - get stdout(): ReadableStream; - get stderr(): ReadableStream; - readonly pid: number; - /** Get the status of the child process. */ - readonly status: Promise; - constructor(command: string | URL, options?: CommandOptions); /** * Executes the {@linkcode Deno.Command}, waiting for it to finish and @@ -1711,8 +1715,27 @@ declare namespace Deno { /** * Spawns a streamable subprocess, allowing to use the other methods. */ - spawn(): void; + spawn(): ChildProcess; + } + /** **UNSTABLE**: New API, yet to be vetted. + * + * The interface for handling a child process returned from + * {@linkcode Deno.Command.spawn}. + * + * @category Sub Process + */ + export class ChildProcess { + get stdin(): WritableStream; + get stdout(): ReadableStream; + get stderr(): ReadableStream; + readonly pid: number; + /** Get the status of the child. */ + readonly status: Promise; + + /** Waits for the child to exit completely, returning all its output and + * status. */ + output(): Promise; /** Kills the process with given {@linkcode Deno.Signal}. Defaults to * `"SIGTERM"`. */ kill(signo?: Signal): void; diff --git a/cli/tsc/dts/lib.dom.d.ts b/cli/tsc/dts/lib.dom.d.ts index 6f9964efc7..7bdf13e8e7 100644 --- a/cli/tsc/dts/lib.dom.d.ts +++ b/cli/tsc/dts/lib.dom.d.ts @@ -137,15 +137,14 @@ interface AudioWorkletNodeOptions extends AudioNodeOptions { interface AuthenticationExtensionsClientInputs { appid?: string; - appidExclude?: string; credProps?: boolean; - uvm?: boolean; + hmacCreateSecret?: boolean; } interface AuthenticationExtensionsClientOutputs { appid?: boolean; credProps?: CredentialPropertiesOutput; - uvm?: UvmEntries; + hmacCreateSecret?: boolean; } interface AuthenticatorSelectionCriteria { @@ -374,7 +373,7 @@ interface DeviceOrientationEventInit extends EventInit { gamma?: number | null; } -interface DisplayMediaStreamConstraints { +interface DisplayMediaStreamOptions { audio?: boolean | MediaTrackConstraints; video?: boolean | MediaTrackConstraints; } @@ -807,10 +806,6 @@ interface MediaQueryListEventInit extends EventInit { media?: string; } -interface MediaRecorderErrorEventInit extends EventInit { - error: DOMException; -} - interface MediaRecorderOptions { audioBitsPerSecond?: number; bitsPerSecond?: number; @@ -820,9 +815,9 @@ interface MediaRecorderOptions { interface MediaSessionActionDetails { action: MediaSessionAction; - fastSeek?: boolean | null; - seekOffset?: number | null; - seekTime?: number | null; + fastSeek?: boolean; + seekOffset?: number; + seekTime?: number; } interface MediaStreamAudioSourceOptions { @@ -1122,6 +1117,10 @@ interface PermissionDescriptor { name: PermissionName; } +interface PictureInPictureEventInit extends EventInit { + pictureInPictureWindow: PictureInPictureWindow; +} + interface PointerEventInit extends MouseEventInit { coalescedEvents?: PointerEvent[]; height?: number; @@ -1315,6 +1314,8 @@ interface RTCIceCandidatePairStats extends RTCStats { bytesReceived?: number; bytesSent?: number; currentRoundTripTime?: number; + lastPacketReceivedTimestamp?: DOMHighResTimeStamp; + lastPacketSentTimestamp?: DOMHighResTimeStamp; localCandidateId: string; nominated?: boolean; remoteCandidateId: string; @@ -1329,18 +1330,47 @@ interface RTCIceCandidatePairStats extends RTCStats { interface RTCIceServer { credential?: string; - credentialType?: RTCIceCredentialType; urls: string | string[]; username?: string; } interface RTCInboundRtpStreamStats extends RTCReceivedRtpStreamStats { + audioLevel?: number; + bytesReceived?: number; + concealedSamples?: number; + concealmentEvents?: number; + decoderImplementation?: string; + estimatedPlayoutTimestamp?: DOMHighResTimeStamp; + fecPacketsDiscarded?: number; + fecPacketsReceived?: number; firCount?: number; + frameHeight?: number; + frameWidth?: number; framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + headerBytesReceived?: number; + insertedSamplesForDeceleration?: number; + jitterBufferDelay?: number; + jitterBufferEmittedCount?: number; + keyFramesDecoded?: number; + kind: string; + lastPacketReceivedTimestamp?: DOMHighResTimeStamp; nackCount?: number; + packetsDiscarded?: number; pliCount?: number; qpSum?: number; remoteId?: string; + removedSamplesForAcceleration?: number; + silentConcealedSamples?: number; + totalAudioEnergy?: number; + totalDecodeTime?: number; + totalInterFrameDelay?: number; + totalProcessingDelay?: number; + totalSamplesDuration?: number; + totalSamplesReceived?: number; + totalSquaredInterFrameDelay?: number; } interface RTCLocalSessionDescriptionInit { @@ -1359,11 +1389,27 @@ interface RTCOfferOptions extends RTCOfferAnswerOptions { interface RTCOutboundRtpStreamStats extends RTCSentRtpStreamStats { firCount?: number; + frameHeight?: number; + frameWidth?: number; framesEncoded?: number; + framesPerSecond?: number; + framesSent?: number; + headerBytesSent?: number; + hugeFramesSent?: number; + keyFramesEncoded?: number; + mediaSourceId?: string; nackCount?: number; pliCount?: number; qpSum?: number; + qualityLimitationResolutionChanges?: number; remoteId?: string; + retransmittedBytesSent?: number; + retransmittedPacketsSent?: number; + rid?: string; + targetBitrate?: number; + totalEncodeTime?: number; + totalEncodedBytesTarget?: number; + totalPacketSendDelay?: number; } interface RTCPeerConnectionIceErrorEventInit extends EventInit { @@ -1381,7 +1427,6 @@ interface RTCPeerConnectionIceEventInit extends EventInit { interface RTCReceivedRtpStreamStats extends RTCRtpStreamStats { jitter?: number; - packetsDiscarded?: number; packetsLost?: number; packetsReceived?: number; } @@ -1425,6 +1470,8 @@ interface RTCRtpContributingSource { interface RTCRtpEncodingParameters extends RTCRtpCodingParameters { active?: boolean; maxBitrate?: number; + maxFramerate?: number; + networkPriority?: RTCPriorityType; priority?: RTCPriorityType; scaleResolutionDownBy?: number; } @@ -1500,15 +1547,23 @@ interface RTCTransportStats extends RTCStats { dtlsState: RTCDtlsTransportState; localCertificateId?: string; remoteCertificateId?: string; - rtcpTransportStatsId?: string; selectedCandidatePairId?: string; srtpCipher?: string; tlsVersion?: string; } -interface ReadableStreamReadDoneResult { +interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode?: ReadableStreamReaderMode; +} + +interface ReadableStreamReadDoneResult { done: true; - value?: undefined; + value?: T; } interface ReadableStreamReadValueResult { @@ -1792,6 +1847,21 @@ interface ULongRange { min?: number; } +interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: UnderlyingSourceCancelCallback; + pull?: (controller: ReadableByteStreamController) => void | PromiseLike; + start?: (controller: ReadableByteStreamController) => any; + type: "bytes"; +} + +interface UnderlyingDefaultSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: (controller: ReadableStreamDefaultController) => void | PromiseLike; + start?: (controller: ReadableStreamDefaultController) => any; + type?: undefined; +} + interface UnderlyingSink { abort?: UnderlyingSinkAbortCallback; close?: UnderlyingSinkCloseCallback; @@ -1801,10 +1871,11 @@ interface UnderlyingSink { } interface UnderlyingSource { + autoAllocateChunkSize?: number; cancel?: UnderlyingSourceCancelCallback; pull?: UnderlyingSourcePullCallback; start?: UnderlyingSourceStartCallback; - type?: undefined; + type?: ReadableStreamType; } interface ValidityStateFlags { @@ -1821,10 +1892,10 @@ interface ValidityStateFlags { } interface VideoColorSpaceInit { - fullRange?: boolean; - matrix?: VideoMatrixCoefficients; - primaries?: VideoColorPrimaries; - transfer?: VideoTransferCharacteristics; + fullRange?: boolean | null; + matrix?: VideoMatrixCoefficients | null; + primaries?: VideoColorPrimaries | null; + transfer?: VideoTransferCharacteristics | null; } interface VideoConfiguration { @@ -1839,7 +1910,7 @@ interface VideoConfiguration { width: number; } -interface VideoFrameMetadata { +interface VideoFrameCallbackMetadata { captureTime?: DOMHighResTimeStamp; expectedDisplayTime: DOMHighResTimeStamp; height: number; @@ -1932,12 +2003,14 @@ interface ARIAMixin { ariaChecked: string | null; ariaColCount: string | null; ariaColIndex: string | null; + ariaColIndexText: string | null; ariaColSpan: string | null; ariaCurrent: string | null; ariaDisabled: string | null; ariaExpanded: string | null; ariaHasPopup: string | null; ariaHidden: string | null; + ariaInvalid: string | null; ariaKeyShortcuts: string | null; ariaLabel: string | null; ariaLevel: string | null; @@ -1954,6 +2027,7 @@ interface ARIAMixin { ariaRoleDescription: string | null; ariaRowCount: string | null; ariaRowIndex: string | null; + ariaRowIndexText: string | null; ariaRowSpan: string | null; ariaSelected: string | null; ariaSetSize: string | null; @@ -1962,6 +2036,7 @@ interface ARIAMixin { ariaValueMin: string | null; ariaValueNow: string | null; ariaValueText: string | null; + role: string | null; } /** A controller object that allows you to abort one or more DOM requests as and when desired. */ @@ -1997,7 +2072,8 @@ interface AbortSignal extends EventTarget { declare var AbortSignal: { prototype: AbortSignal; new(): AbortSignal; - // abort(): AbortSignal; - To be re-added in the future + abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; }; interface AbstractRange { @@ -2132,7 +2208,7 @@ declare var AnimationPlaybackEvent: { }; interface AnimationTimeline { - readonly currentTime: number | null; + readonly currentTime: CSSNumberish | null; } declare var AnimationTimeline: { @@ -2148,6 +2224,7 @@ interface Attr extends Node { readonly ownerDocument: Document; readonly ownerElement: Element | null; readonly prefix: string | null; + /** @deprecated */ readonly specified: boolean; value: string; } @@ -2383,6 +2460,10 @@ declare var AuthenticatorAssertionResponse: { /** Available only in secure contexts. */ interface AuthenticatorAttestationResponse extends AuthenticatorResponse { readonly attestationObject: ArrayBuffer; + getAuthenticatorData(): ArrayBuffer; + getPublicKey(): ArrayBuffer | null; + getPublicKeyAlgorithm(): COSEAlgorithmIdentifier; + getTransports(): string[]; } declare var AuthenticatorAttestationResponse: { @@ -2581,6 +2662,14 @@ declare var CSSConditionRule: { new(): CSSConditionRule; }; +interface CSSContainerRule extends CSSConditionRule { +} + +declare var CSSContainerRule: { + prototype: CSSContainerRule; + new(): CSSContainerRule; +}; + interface CSSCounterStyleRule extends CSSRule { additiveSymbols: string; fallback: string; @@ -2609,6 +2698,18 @@ declare var CSSFontFaceRule: { new(): CSSFontFaceRule; }; +interface CSSFontPaletteValuesRule extends CSSRule { + readonly basePalette: string; + readonly fontFamily: string; + readonly name: string; + readonly overrideColors: string; +} + +declare var CSSFontPaletteValuesRule: { + prototype: CSSFontPaletteValuesRule; + new(): CSSFontPaletteValuesRule; +}; + /** Any CSS at-rule that contains other rules nested within it. */ interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -2623,6 +2724,7 @@ declare var CSSGroupingRule: { interface CSSImportRule extends CSSRule { readonly href: string; + readonly layerName: string | null; readonly media: MediaList; readonly styleSheet: CSSStyleSheet; } @@ -2657,6 +2759,24 @@ declare var CSSKeyframesRule: { new(): CSSKeyframesRule; }; +interface CSSLayerBlockRule extends CSSGroupingRule { + readonly name: string; +} + +declare var CSSLayerBlockRule: { + prototype: CSSLayerBlockRule; + new(): CSSLayerBlockRule; +}; + +interface CSSLayerStatementRule extends CSSRule { + readonly nameList: ReadonlyArray; +} + +declare var CSSLayerStatementRule: { + prototype: CSSLayerStatementRule; + new(): CSSLayerStatementRule; +}; + /** A single CSS @media rule. It implements the CSSConditionRule interface, and therefore the CSSGroupingRule and the CSSRule interface with a type value of 4 (CSSRule.MEDIA_RULE). */ interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -2754,6 +2874,7 @@ interface CSSStyleDeclaration { animationTimingFunction: string; appearance: string; aspectRatio: string; + backdropFilter: string; backfaceVisibility: string; background: string; backgroundAttachment: string; @@ -2858,6 +2979,9 @@ interface CSSStyleDeclaration { columnWidth: string; columns: string; contain: string; + container: string; + containerName: string; + containerType: string; content: string; counterIncrement: string; counterReset: string; @@ -2888,6 +3012,7 @@ interface CSSStyleDeclaration { fontFeatureSettings: string; fontKerning: string; fontOpticalSizing: string; + fontPalette: string; fontSize: string; fontSizeAdjust: string; fontStretch: string; @@ -2925,6 +3050,7 @@ interface CSSStyleDeclaration { gridTemplateColumns: string; gridTemplateRows: string; height: string; + hyphenateCharacter: string; hyphens: string; /** @deprecated */ imageOrientation: string; @@ -3001,6 +3127,7 @@ interface CSSStyleDeclaration { outlineWidth: string; overflow: string; overflowAnchor: string; + overflowClipMargin: string; overflowWrap: string; overflowX: string; overflowY: string; @@ -3458,6 +3585,7 @@ interface CanvasPath { moveTo(x: number, y: number): void; quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; rect(x: number, y: number, w: number, h: number): void; + roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | (number | DOMPointInit)[]): void; } interface CanvasPathDrawingStyles { @@ -3519,6 +3647,7 @@ interface CanvasText { interface CanvasTextDrawingStyles { direction: CanvasDirection; font: string; + fontKerning: CanvasFontKerning; textAlign: CanvasTextAlign; textBaseline: CanvasTextBaseline; } @@ -4380,7 +4509,10 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad readonly documentElement: HTMLElement; /** Returns document's URL. */ readonly documentURI: string; - /** Sets or gets the security domain of the document. */ + /** + * Sets or gets the security domain of the document. + * @deprecated + */ domain: string; /** Retrieves a collection of all embed objects in the document. */ readonly embeds: HTMLCollectionOf; @@ -4534,7 +4666,6 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; createEvent(eventInterface: "MediaQueryListEvent"): MediaQueryListEvent; - createEvent(eventInterface: "MediaRecorderErrorEvent"): MediaRecorderErrorEvent; createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; createEvent(eventInterface: "MessageEvent"): MessageEvent; createEvent(eventInterface: "MouseEvent"): MouseEvent; @@ -4545,6 +4676,7 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; createEvent(eventInterface: "PaymentMethodChangeEvent"): PaymentMethodChangeEvent; createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PictureInPictureEvent"): PictureInPictureEvent; createEvent(eventInterface: "PointerEvent"): PointerEvent; createEvent(eventInterface: "PopStateEvent"): PopStateEvent; createEvent(eventInterface: "ProgressEvent"): ProgressEvent; @@ -4663,6 +4795,7 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad /** * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. * @param commandId String that specifies a command identifier. + * @deprecated */ queryCommandIndeterm(commandId: string): boolean; /** @@ -4680,6 +4813,7 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad /** * Returns the current value of the document, range, or current selection for the given command. * @param commandId String that specifies a command identifier. + * @deprecated */ queryCommandValue(commandId: string): string; /** @deprecated */ @@ -4838,6 +4972,13 @@ interface EXT_sRGB { interface EXT_shader_texture_lod { } +interface EXT_texture_compression_bptc { + readonly COMPRESSED_RGBA_BPTC_UNORM_EXT: GLenum; + readonly COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT: GLenum; + readonly COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT: GLenum; +} + interface EXT_texture_compression_rgtc { readonly COMPRESSED_RED_GREEN_RGTC2_EXT: GLenum; readonly COMPRESSED_RED_RGTC1_EXT: GLenum; @@ -4851,6 +4992,17 @@ interface EXT_texture_filter_anisotropic { readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum; } +interface EXT_texture_norm16 { + readonly R16_EXT: GLenum; + readonly R16_SNORM_EXT: GLenum; + readonly RG16_EXT: GLenum; + readonly RG16_SNORM_EXT: GLenum; + readonly RGB16_EXT: GLenum; + readonly RGB16_SNORM_EXT: GLenum; + readonly RGBA16_EXT: GLenum; + readonly RGBA16_SNORM_EXT: GLenum; +} + interface ElementEventMap { "fullscreenchange": Event; "fullscreenerror": Event; @@ -5033,6 +5185,7 @@ declare var ErrorEvent: { interface Event { /** Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. */ readonly bubbles: boolean; + /** @deprecated */ cancelBubble: boolean; /** Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */ readonly cancelable: boolean; @@ -5569,6 +5722,7 @@ interface GlobalEventHandlersEventMap { "auxclick": MouseEvent; "beforeinput": InputEvent; "blur": FocusEvent; + "cancel": Event; "canplay": Event; "canplaythrough": Event; "change": Event; @@ -5669,11 +5823,13 @@ interface GlobalEventHandlers { onanimationiteration: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; onanimationstart: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; onauxclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + onbeforeinput: ((this: GlobalEventHandlers, ev: InputEvent) => any) | null; /** * Fires when the object loses the input focus. * @param ev The focus event. */ onblur: ((this: GlobalEventHandlers, ev: FocusEvent) => any) | null; + oncancel: ((this: GlobalEventHandlers, ev: Event) => any) | null; /** * Occurs when playback is possible, but would require further buffering. * @param ev The event. @@ -6187,6 +6343,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, quality?: any): string; + transferControlToOffscreen(): OffscreenCanvas; addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -8770,13 +8927,13 @@ declare var IDBObjectStore: { }; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { - "blocked": Event; + "blocked": IDBVersionChangeEvent; "upgradeneeded": IDBVersionChangeEvent; } /** Also inherits methods from its parents IDBRequest and EventTarget. */ interface IDBOpenDBRequest extends IDBRequest { - onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onblocked: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -8901,7 +9058,7 @@ declare var ImageBitmap: { interface ImageBitmapRenderingContext { /** Returns the canvas element that the context is bound to. */ - readonly canvas: HTMLCanvasElement; + readonly canvas: HTMLCanvasElement | OffscreenCanvas; /** Transfers the underlying bitmap data from imageBitmap to context, and the bitmap becomes the contents of the canvas element to which context is bound. */ transferFromImageBitmap(bitmap: ImageBitmap | null): void; } @@ -8932,6 +9089,7 @@ interface InnerHTML { innerHTML: string; } +/** Available only in secure contexts. */ interface InputDeviceInfo extends MediaDeviceInfo { } @@ -9185,7 +9343,7 @@ interface MediaDevicesEventMap { interface MediaDevices extends EventTarget { ondevicechange: ((this: MediaDevices, ev: Event) => any) | null; enumerateDevices(): Promise; - getDisplayMedia(constraints?: DisplayMediaStreamConstraints): Promise; + getDisplayMedia(options?: DisplayMediaStreamOptions): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints?: MediaStreamConstraints): Promise; addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -9392,7 +9550,7 @@ declare var MediaQueryListEvent: { interface MediaRecorderEventMap { "dataavailable": BlobEvent; - "error": MediaRecorderErrorEvent; + "error": Event; "pause": Event; "resume": Event; "start": Event; @@ -9403,7 +9561,7 @@ interface MediaRecorder extends EventTarget { readonly audioBitsPerSecond: number; readonly mimeType: string; ondataavailable: ((this: MediaRecorder, ev: BlobEvent) => any) | null; - onerror: ((this: MediaRecorder, ev: MediaRecorderErrorEvent) => any) | null; + onerror: ((this: MediaRecorder, ev: Event) => any) | null; onpause: ((this: MediaRecorder, ev: Event) => any) | null; onresume: ((this: MediaRecorder, ev: Event) => any) | null; onstart: ((this: MediaRecorder, ev: Event) => any) | null; @@ -9428,15 +9586,6 @@ declare var MediaRecorder: { isTypeSupported(type: string): boolean; }; -interface MediaRecorderErrorEvent extends Event { - readonly error: DOMException; -} - -declare var MediaRecorderErrorEvent: { - prototype: MediaRecorderErrorEvent; - new(type: string, eventInitDict: MediaRecorderErrorEventInit): MediaRecorderErrorEvent; -}; - interface MediaSession { metadata: MediaMetadata | null; playbackState: MediaSessionPlaybackState; @@ -9889,12 +10038,14 @@ interface NavigatorID { readonly appName: string; /** @deprecated */ readonly appVersion: string; + /** @deprecated */ readonly platform: string; /** @deprecated */ readonly product: string; /** @deprecated */ readonly productSub: string; readonly userAgent: string; + /** @deprecated */ readonly vendor: string; /** @deprecated */ readonly vendorSub: string; @@ -10143,6 +10294,16 @@ declare var Notification: { requestPermission(deprecatedCallback?: NotificationPermissionCallback): Promise; }; +interface OES_draw_buffers_indexed { + blendEquationSeparateiOES(buf: GLuint, modeRGB: GLenum, modeAlpha: GLenum): void; + blendEquationiOES(buf: GLuint, mode: GLenum): void; + blendFuncSeparateiOES(buf: GLuint, srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum): void; + blendFunciOES(buf: GLuint, src: GLenum, dst: GLenum): void; + colorMaskiOES(buf: GLuint, r: GLboolean, g: GLboolean, b: GLboolean, a: GLboolean): void; + disableiOES(target: GLenum, index: GLuint): void; + enableiOES(target: GLenum, index: GLuint): void; +} + /** The OES_element_index_uint extension is part of the WebGL API and adds support for gl.UNSIGNED_INT types to WebGLRenderingContext.drawElements(). */ interface OES_element_index_uint { } @@ -10221,6 +10382,57 @@ declare var OfflineAudioContext: { new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; }; +interface OffscreenCanvasEventMap { + "contextlost": Event; + "contextrestored": Event; +} + +interface OffscreenCanvas extends EventTarget { + /** + * These attributes return the dimensions of the OffscreenCanvas object's bitmap. + * + * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). + */ + height: number; + oncontextlost: ((this: OffscreenCanvas, ev: Event) => any) | null; + oncontextrestored: ((this: OffscreenCanvas, ev: Event) => any) | null; + /** + * These attributes return the dimensions of the OffscreenCanvas object's bitmap. + * + * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). + */ + width: number; + /** + * Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API. + * + * This specification defines the "2d" context below, which is similar but distinct from the "2d" context that is created from a canvas element. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL] + * + * Returns null if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context). + */ + getContext(contextId: OffscreenRenderingContextId, options?: any): OffscreenRenderingContext | null; + /** Returns a newly created ImageBitmap object with the image in the OffscreenCanvas object. The image in the OffscreenCanvas object is replaced with a new blank image. */ + transferToImageBitmap(): ImageBitmap; + addEventListener(type: K, listener: (this: OffscreenCanvas, ev: OffscreenCanvasEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OffscreenCanvas, ev: OffscreenCanvasEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var OffscreenCanvas: { + prototype: OffscreenCanvas; + new(width: number, height: number): OffscreenCanvas; +}; + +interface OffscreenCanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform { + readonly canvas: OffscreenCanvas; + commit(): void; +} + +declare var OffscreenCanvasRenderingContext2D: { + prototype: OffscreenCanvasRenderingContext2D; + new(): OffscreenCanvasRenderingContext2D; +}; + /** The OscillatorNode interface represents a periodic waveform, such as a sine wave. It is an AudioScheduledSourceNode audio-processing module that causes a specified frequency of a given wave to be created—in effect, a constant tone. */ interface OscillatorNode extends AudioScheduledSourceNode { readonly detune: AudioParam; @@ -10681,6 +10893,7 @@ interface PermissionStatusEventMap { } interface PermissionStatus extends EventTarget { + readonly name: string; onchange: ((this: PermissionStatus, ev: Event) => any) | null; readonly state: PermissionState; addEventListener(type: K, listener: (this: PermissionStatus, ev: PermissionStatusEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -10703,6 +10916,15 @@ declare var Permissions: { new(): Permissions; }; +interface PictureInPictureEvent extends Event { + readonly pictureInPictureWindow: PictureInPictureWindow; +} + +declare var PictureInPictureEvent: { + prototype: PictureInPictureEvent; + new(type: string, eventInitDict: PictureInPictureEventInit): PictureInPictureEvent; +}; + interface PictureInPictureWindowEventMap { "resize": Event; } @@ -10854,6 +11076,7 @@ declare var PromiseRejectionEvent: { /** Available only in secure contexts. */ interface PublicKeyCredential extends Credential { + readonly authenticatorAttachment: string | null; readonly rawId: ArrayBuffer; readonly response: AuthenticatorResponse; getClientExtensionResults(): AuthenticationExtensionsClientOutputs; @@ -10902,6 +11125,7 @@ declare var PushSubscription: { /** Available only in secure contexts. */ interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; + readonly userVisibleOnly: boolean; } declare var PushSubscriptionOptions: { @@ -11386,7 +11610,9 @@ declare var ReadableByteStreamController: { interface ReadableStream { readonly locked: boolean; cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; tee(): [ReadableStream, ReadableStream]; @@ -11394,11 +11620,13 @@ interface ReadableStream { declare var ReadableStream: { prototype: ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number }): ReadableStream; + new(underlyingSource: UnderlyingDefaultSource, strategy?: QueuingStrategy): ReadableStream; new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; }; interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { - read(view: ArrayBufferView): Promise>; + read(view: T): Promise>; releaseLock(): void; } @@ -11555,7 +11783,6 @@ interface Response extends Body { declare var Response: { prototype: Response; new(body?: BodyInit | null, init?: ResponseInit): Response; - json(data: unknown, init?: ResponseInit): Response; error(): Response; redirect(url: string | URL, status?: number): Response; }; @@ -13020,6 +13247,7 @@ interface SVGStyleElement extends SVGElement, LinkStyle { disabled: boolean; media: string; title: string; + /** @deprecated */ type: string; addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -13382,6 +13610,7 @@ interface Selection { empty(): void; extend(node: Node, offset?: number): void; getRangeAt(index: number): Range; + modify(alter?: string, direction?: string, granularity?: string): void; removeAllRanges(): void; removeRange(range: Range): void; selectAllChildren(node: Node): void; @@ -13780,6 +14009,7 @@ interface StorageEvent extends Event { readonly storageArea: Storage | null; /** Returns the URL of the document whose storage item changed. */ readonly url: string; + /** @deprecated */ initStorageEvent(type: string, bubbles?: boolean, cancelable?: boolean, key?: string | null, oldValue?: string | null, newValue?: string | null, url?: string | URL, storageArea?: Storage | null): void; } @@ -14562,8 +14792,8 @@ interface WEBGL_lose_context { interface WEBGL_multi_draw { multiDrawArraysInstancedWEBGL(mode: GLenum, firstsList: Int32Array | GLint[], firstsOffset: GLuint, countsList: Int32Array | GLsizei[], countsOffset: GLuint, instanceCountsList: Int32Array | GLsizei[], instanceCountsOffset: GLuint, drawcount: GLsizei): void; multiDrawArraysWEBGL(mode: GLenum, firstsList: Int32Array | GLint[], firstsOffset: GLuint, countsList: Int32Array | GLsizei[], countsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | GLint[], countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | GLsizei[], offsetsOffset: GLuint, instanceCountsList: Int32Array | GLsizei[], instanceCountsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | GLint[], countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | GLsizei[], offsetsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | GLsizei[], countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | GLsizei[], offsetsOffset: GLuint, instanceCountsList: Int32Array | GLsizei[], instanceCountsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | GLsizei[], countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | GLsizei[], offsetsOffset: GLuint, drawcount: GLsizei): void; } /** A WaveShaperNode always has exactly one input and one output. */ @@ -15913,7 +16143,7 @@ declare var WebGLRenderingContext: { }; interface WebGLRenderingContextBase { - readonly canvas: HTMLCanvasElement; + readonly canvas: HTMLCanvasElement | OffscreenCanvas; readonly drawingBufferHeight: GLsizei; readonly drawingBufferWidth: GLsizei; activeTexture(texture: GLenum): void; @@ -15973,35 +16203,39 @@ interface WebGLRenderingContextBase { getBufferParameter(target: GLenum, pname: GLenum): any; getContextAttributes(): WebGLContextAttributes | null; getError(): GLenum; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; getExtension(extensionName: "EXT_color_buffer_float"): EXT_color_buffer_float | null; getExtension(extensionName: "EXT_color_buffer_half_float"): EXT_color_buffer_half_float | null; getExtension(extensionName: "EXT_float_blend"): EXT_float_blend | null; - getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; - getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_texture_compression_bptc"): EXT_texture_compression_bptc | null; + getExtension(extensionName: "EXT_texture_compression_rgtc"): EXT_texture_compression_rgtc | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; getExtension(extensionName: "KHR_parallel_shader_compile"): KHR_parallel_shader_compile | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "OES_fbo_render_mipmap"): OES_fbo_render_mipmap | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; getExtension(extensionName: "OVR_multiview2"): OVR_multiview2 | null; getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; getExtension(extensionName: "WEBGL_compressed_texture_etc"): WEBGL_compressed_texture_etc | null; getExtension(extensionName: "WEBGL_compressed_texture_etc1"): WEBGL_compressed_texture_etc1 | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; - getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; - getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; - getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; - getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; - getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; - getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; - getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; - getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; - getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; - getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: "WEBGL_multi_draw"): WEBGL_multi_draw | null; getExtension(name: string): any; getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum): any; getParameter(pname: GLenum): any; @@ -17387,7 +17621,7 @@ interface UnderlyingSourceStartCallback { } interface VideoFrameRequestCallback { - (now: DOMHighResTimeStamp, metadata: VideoFrameMetadata): void; + (now: DOMHighResTimeStamp, metadata: VideoFrameCallbackMetadata): void; } interface VoidFunction { @@ -17746,11 +17980,13 @@ declare var onanimationend: ((this: Window, ev: AnimationEvent) => any) | null; declare var onanimationiteration: ((this: Window, ev: AnimationEvent) => any) | null; declare var onanimationstart: ((this: Window, ev: AnimationEvent) => any) | null; declare var onauxclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var onbeforeinput: ((this: Window, ev: InputEvent) => any) | null; /** * Fires when the object loses the input focus. * @param ev The focus event. */ declare var onblur: ((this: Window, ev: FocusEvent) => any) | null; +declare var oncancel: ((this: Window, ev: Event) => any) | null; /** * Occurs when playback is possible, but would require further buffering. * @param ev The event. @@ -18062,7 +18298,7 @@ type BodyInit = ReadableStream | XMLHttpRequestBodyInit; type BufferSource = ArrayBufferView | ArrayBuffer; type COSEAlgorithmIdentifier = number; type CSSNumberish = number; -type CanvasImageSource = HTMLOrSVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap; +type CanvasImageSource = HTMLOrSVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas; type ClipboardItemData = Promise; type ClipboardItems = ClipboardItem[]; type ConstrainBoolean = boolean | ConstrainBooleanParameters; @@ -18099,20 +18335,19 @@ type MediaProvider = MediaStream | MediaSource | Blob; type MessageEventSource = WindowProxy | MessagePort | ServiceWorker; type MutationRecordType = "attributes" | "characterData" | "childList"; type NamedCurve = string; +type OffscreenRenderingContext = OffscreenCanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext; type OnBeforeUnloadEventHandler = OnBeforeUnloadEventHandlerNonNull | null; type OnErrorEventHandler = OnErrorEventHandlerNonNull | null; type PerformanceEntryList = PerformanceEntry[]; -type ReadableStreamController = ReadableStreamDefaultController; -type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; -type ReadableStreamReader = ReadableStreamDefaultReader; +type ReadableStreamController = ReadableStreamDefaultController | ReadableByteStreamController; +type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; +type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; type RenderingContext = CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext; type RequestInfo = Request | string; -type TexImageSource = ImageBitmap | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; +type TexImageSource = ImageBitmap | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | OffscreenCanvas; type TimerHandler = string | Function; -type Transferable = ArrayBuffer | MessagePort | ImageBitmap; +type Transferable = OffscreenCanvas | ImageBitmap | MessagePort | ReadableStream | WritableStream | TransformStream | ArrayBuffer; type Uint32List = Uint32Array | GLuint[]; -type UvmEntries = UvmEntry[]; -type UvmEntry = number[]; type VibratePattern = number | number[]; type WindowProxy = Window; type XMLHttpRequestBodyInit = Blob | BufferSource | FormData | URLSearchParams | string; @@ -18124,7 +18359,7 @@ type AttestationConveyancePreference = "direct" | "enterprise" | "indirect" | "n type AudioContextLatencyCategory = "balanced" | "interactive" | "playback"; type AudioContextState = "closed" | "running" | "suspended"; type AuthenticatorAttachment = "cross-platform" | "platform"; -type AuthenticatorTransport = "ble" | "internal" | "nfc" | "usb"; +type AuthenticatorTransport = "ble" | "hybrid" | "internal" | "nfc" | "usb"; type AutoKeyword = "auto"; type AutomationRate = "a-rate" | "k-rate"; type BinaryType = "arraybuffer" | "blob"; @@ -18185,12 +18420,13 @@ type MediaKeySessionClosedReason = "closed-by-application" | "hardware-context-r type MediaKeySessionType = "persistent-license" | "temporary"; type MediaKeyStatus = "expired" | "internal-error" | "output-downscaled" | "output-restricted" | "released" | "status-pending" | "usable" | "usable-in-future"; type MediaKeysRequirement = "not-allowed" | "optional" | "required"; -type MediaSessionAction = "hangup" | "nexttrack" | "pause" | "play" | "previoustrack" | "seekbackward" | "seekforward" | "seekto" | "skipad" | "stop" | "togglecamera" | "togglemicrophone"; +type MediaSessionAction = "nexttrack" | "pause" | "play" | "previoustrack" | "seekbackward" | "seekforward" | "seekto" | "skipad" | "stop"; type MediaSessionPlaybackState = "none" | "paused" | "playing"; type MediaStreamTrackState = "ended" | "live"; type NavigationTimingType = "back_forward" | "navigate" | "prerender" | "reload"; type NotificationDirection = "auto" | "ltr" | "rtl"; type NotificationPermission = "default" | "denied" | "granted"; +type OffscreenRenderingContextId = "2d" | "bitmaprenderer" | "webgl" | "webgl2" | "webgpu"; type OrientationLockType = "any" | "landscape" | "landscape-primary" | "landscape-secondary" | "natural" | "portrait" | "portrait-primary" | "portrait-secondary"; type OrientationType = "landscape-primary" | "landscape-secondary" | "portrait-primary" | "portrait-secondary"; type OscillatorType = "custom" | "sawtooth" | "sine" | "square" | "triangle"; @@ -18215,7 +18451,6 @@ type RTCErrorDetailType = "data-channel-failure" | "dtls-failure" | "fingerprint type RTCIceCandidateType = "host" | "prflx" | "relay" | "srflx"; type RTCIceComponent = "rtcp" | "rtp"; type RTCIceConnectionState = "checking" | "closed" | "completed" | "connected" | "disconnected" | "failed" | "new"; -type RTCIceCredentialType = "password"; type RTCIceGathererState = "complete" | "gathering" | "new"; type RTCIceGatheringState = "complete" | "gathering" | "new"; type RTCIceProtocol = "tcp" | "udp"; @@ -18230,7 +18465,9 @@ type RTCSctpTransportState = "closed" | "connected" | "connecting"; type RTCSdpType = "answer" | "offer" | "pranswer" | "rollback"; type RTCSignalingState = "closed" | "have-local-offer" | "have-local-pranswer" | "have-remote-offer" | "have-remote-pranswer" | "stable"; type RTCStatsIceCandidatePairState = "failed" | "frozen" | "in-progress" | "inprogress" | "succeeded" | "waiting"; -type RTCStatsType = "candidate-pair" | "certificate" | "codec" | "csrc" | "data-channel" | "inbound-rtp" | "local-candidate" | "media-source" | "outbound-rtp" | "peer-connection" | "remote-candidate" | "remote-inbound-rtp" | "remote-outbound-rtp" | "track" | "transport"; +type RTCStatsType = "candidate-pair" | "certificate" | "codec" | "data-channel" | "inbound-rtp" | "local-candidate" | "media-source" | "outbound-rtp" | "peer-connection" | "remote-candidate" | "remote-inbound-rtp" | "remote-outbound-rtp" | "track" | "transport"; +type ReadableStreamReaderMode = "byob"; +type ReadableStreamType = "bytes"; type ReadyState = "closed" | "ended" | "open"; type RecordingState = "inactive" | "paused" | "recording"; type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url"; diff --git a/cli/tsc/dts/lib.dom.iterable.d.ts b/cli/tsc/dts/lib.dom.iterable.d.ts index cde428dfcb..9cd574ca52 100644 --- a/cli/tsc/dts/lib.dom.iterable.d.ts +++ b/cli/tsc/dts/lib.dom.iterable.d.ts @@ -46,6 +46,10 @@ interface Cache { addAll(requests: Iterable): Promise; } +interface CanvasPath { + roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | Iterable): void; +} + interface CanvasPathDrawingStyles { setLineDash(segments: Iterable): void; } @@ -273,8 +277,8 @@ interface WEBGL_draw_buffers { interface WEBGL_multi_draw { multiDrawArraysInstancedWEBGL(mode: GLenum, firstsList: Int32Array | Iterable, firstsOffset: GLuint, countsList: Int32Array | Iterable, countsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; multiDrawArraysWEBGL(mode: GLenum, firstsList: Int32Array | Iterable, firstsOffset: GLuint, countsList: Int32Array | Iterable, countsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, drawcount: GLsizei): void; } interface WebGL2RenderingContextBase { diff --git a/cli/tsc/dts/lib.es2015.promise.d.ts b/cli/tsc/dts/lib.es2015.promise.d.ts index 57eea0f6bb..685f7164f5 100644 --- a/cli/tsc/dts/lib.es2015.promise.d.ts +++ b/cli/tsc/dts/lib.es2015.promise.d.ts @@ -41,7 +41,7 @@ interface PromiseConstructor { all(values: T): Promise<{ -readonly [P in keyof T]: Awaited }>; // see: lib.es2015.iterable.d.ts - // all(values: Iterable>): Promise; + // all(values: Iterable>): Promise[]>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved @@ -52,7 +52,7 @@ interface PromiseConstructor { race(values: T): Promise>; // see: lib.es2015.iterable.d.ts - // race(values: Iterable): Promise ? U : T>; + // race(values: Iterable>): Promise>; /** * Creates a new rejected promise for the provided reason. @@ -66,13 +66,18 @@ interface PromiseConstructor { * @returns A resolved promise. */ resolve(): Promise; - /** * Creates a new resolved promise for the provided value. * @param value A promise. * @returns A promise whose internal state matches the provided promise. */ - resolve(value: T | PromiseLike): Promise; + resolve(value: T): Promise>; + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise>; } declare var Promise: PromiseConstructor; diff --git a/cli/tsc/dts/lib.es2015.proxy.d.ts b/cli/tsc/dts/lib.es2015.proxy.d.ts index c241866150..8c465ab06a 100644 --- a/cli/tsc/dts/lib.es2015.proxy.d.ts +++ b/cli/tsc/dts/lib.es2015.proxy.d.ts @@ -98,7 +98,7 @@ interface ProxyHandler { * @param target The original object which is being proxied. * @param p The name or `Symbol` of the property to set. * @param receiver The object to which the assignment was originally directed. - * @returns `A `Boolean` indicating whether or not the property was set. + * @returns A `Boolean` indicating whether or not the property was set. */ set?(target: T, p: string | symbol, newValue: any, receiver: any): boolean; diff --git a/cli/tsc/dts/lib.es2015.reflect.d.ts b/cli/tsc/dts/lib.es2015.reflect.d.ts index d1beb6862f..2e2b3893d4 100644 --- a/cli/tsc/dts/lib.es2015.reflect.d.ts +++ b/cli/tsc/dts/lib.es2015.reflect.d.ts @@ -26,6 +26,11 @@ declare namespace Reflect { * @param thisArgument The object to be used as the this object. * @param argumentsList An array of argument values to be passed to the function. */ + function apply( + target: (this: T, ...args: A) => R, + thisArgument: T, + argumentsList: Readonly, + ): R; function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; /** @@ -35,6 +40,11 @@ declare namespace Reflect { * @param argumentsList An array of argument values to be passed to the constructor. * @param newTarget The constructor to be used as the `new.target` object. */ + function construct( + target: new (...args: A) => R, + argumentsList: Readonly, + newTarget?: new (...args: any) => any, + ): R; function construct(target: Function, argumentsList: ArrayLike, newTarget?: Function): any; /** @@ -61,7 +71,11 @@ declare namespace Reflect { * @param receiver The reference to use as the `this` value in the getter function, * if `target[propertyKey]` is an accessor property. */ - function get(target: object, propertyKey: PropertyKey, receiver?: any): any; + function get( + target: T, + propertyKey: P, + receiver?: unknown, + ): P extends keyof T ? T[P] : any; /** * Gets the own property descriptor of the specified object. @@ -69,7 +83,10 @@ declare namespace Reflect { * @param target Object that contains the property. * @param propertyKey The property name. */ - function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined; + function getOwnPropertyDescriptor( + target: T, + propertyKey: P, + ): TypedPropertyDescriptor

| undefined; /** * Returns the prototype of an object. @@ -111,6 +128,12 @@ declare namespace Reflect { * @param receiver The reference to use as the `this` value in the setter function, * if `target[propertyKey]` is an accessor property. */ + function set( + target: T, + propertyKey: P, + value: P extends keyof T ? T[P] : any, + receiver?: any, + ): boolean; function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; /** diff --git a/cli/tsc/dts/lib.es2015.symbol.wellknown.d.ts b/cli/tsc/dts/lib.es2015.symbol.wellknown.d.ts index b1e3264368..81e052bf26 100644 --- a/cli/tsc/dts/lib.es2015.symbol.wellknown.d.ts +++ b/cli/tsc/dts/lib.es2015.symbol.wellknown.d.ts @@ -239,9 +239,9 @@ interface String { match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; /** - * Replaces first match with string or all matches with RegExp. - * @param searchValue A string or RegExp search value. - * @param replaceValue A string containing the text to replace for match. + * Passes a string and {@linkcode replaceValue} to the `[Symbol.replace]` method on {@linkcode searchValue}. This method is expected to implement its own replacement algorithm. + * @param searchValue An object that supports searching for and replacing matches within a string. + * @param replaceValue The replacement text. */ replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; diff --git a/cli/tsc/dts/lib.es2019.d.ts b/cli/tsc/dts/lib.es2019.d.ts index 5eab0e2c23..77d3d6b5f0 100644 --- a/cli/tsc/dts/lib.es2019.d.ts +++ b/cli/tsc/dts/lib.es2019.d.ts @@ -23,3 +23,4 @@ and limitations under the License. /// /// /// +/// diff --git a/cli/tsc/dts/lib.es2019.intl.d.ts b/cli/tsc/dts/lib.es2019.intl.d.ts new file mode 100644 index 0000000000..fe17c7cd71 --- /dev/null +++ b/cli/tsc/dts/lib.es2019.intl.d.ts @@ -0,0 +1,25 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +declare namespace Intl { + interface DateTimeFormatPartTypesRegistry { + unknown: any + } +} diff --git a/cli/tsc/dts/lib.es2020.intl.d.ts b/cli/tsc/dts/lib.es2020.intl.d.ts index 5bce3812d8..5ee8e4cdc4 100644 --- a/cli/tsc/dts/lib.es2020.intl.d.ts +++ b/cli/tsc/dts/lib.es2020.intl.d.ts @@ -103,7 +103,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). */ - type LocalesArgument = UnicodeBCP47LocaleIdentifier | Locale | (UnicodeBCP47LocaleIdentifier | Locale)[] | undefined; + type LocalesArgument = UnicodeBCP47LocaleIdentifier | Locale | readonly (UnicodeBCP47LocaleIdentifier | Locale)[] | undefined; /** * An object with some or all of properties of `options` parameter diff --git a/cli/tsc/dts/lib.es5.d.ts b/cli/tsc/dts/lib.es5.d.ts index 28ca95abe3..01610d97fb 100644 --- a/cli/tsc/dts/lib.es5.d.ts +++ b/cli/tsc/dts/lib.es5.d.ts @@ -214,12 +214,6 @@ interface ObjectConstructor { */ seal(o: T): T; - /** - * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. - * @param a Object on which to lock the attributes. - */ - freeze(a: T[]): readonly T[]; - /** * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. * @param f Object on which to lock the attributes. @@ -449,8 +443,8 @@ interface String { /** * Replaces text in a string, using a regular expression or search string. - * @param searchValue A string to search for. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + * @param searchValue A string or regular expression to search for. + * @param replaceValue A string containing the text to replace. When the {@linkcode searchValue} is a `RegExp`, all matches are replaced if the `g` flag is set (or only those matches at the beginning, if the `y` flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced. */ replace(searchValue: string | RegExp, replaceValue: string): string; @@ -908,7 +902,17 @@ interface Date { interface DateConstructor { new(): Date; new(value: number | string): Date; - new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + /** + * Creates a new Date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param monthIndex The month as a number between 0 and 11 (January to December). + * @param date The date as a number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds. + * @param ms A number from 0 to 999 that specifies the milliseconds. + */ + new(year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; readonly prototype: Date; /** @@ -919,14 +923,15 @@ interface DateConstructor { /** * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. - * @param month The month as a number between 0 and 11 (January to December). + * @param monthIndex The month as a number between 0 and 11 (January to December). * @param date The date as a number between 1 and 31. * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour. * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes. * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds. * @param ms A number from 0 to 999 that specifies the milliseconds. */ - UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + UTC(year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + /** Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC). */ now(): number; } @@ -941,6 +946,10 @@ interface RegExpMatchArray extends Array { * A copy of the search string. */ input?: string; + /** + * The first match. This will always be present because `null` will be returned if there are no matches. + */ + 0: string; } interface RegExpExecArray extends Array { @@ -952,6 +961,10 @@ interface RegExpExecArray extends Array { * A copy of the search string. */ input: string; + /** + * The first match. This will always be present because `null` will be returned if there are no matches. + */ + 0: string; } interface RegExp { @@ -1532,8 +1545,8 @@ interface Promise { */ type Awaited = T extends null | undefined ? T : // special case for `null | undefined` when not in `--strictNullChecks` mode - T extends object & { then(onfulfilled: infer F): any } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped - F extends ((value: infer V, ...args: any) => any) ? // if the argument to `then` is callable, extracts the first argument + T extends object & { then(onfulfilled: infer F, ...args: infer _): any } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped + F extends ((value: infer V, ...args: infer _) => any) ? // if the argument to `then` is callable, extracts the first argument Awaited : // recursively unwrap the value never : // the argument to `then` was not callable T; // non-object or non-thenable diff --git a/cli/tsc/dts/lib.webworker.d.ts b/cli/tsc/dts/lib.webworker.d.ts index 30f83bc846..209f41cfdb 100644 --- a/cli/tsc/dts/lib.webworker.d.ts +++ b/cli/tsc/dts/lib.webworker.d.ts @@ -500,9 +500,18 @@ interface RTCEncodedVideoFrameMetadata { width?: number; } -interface ReadableStreamReadDoneResult { +interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode?: ReadableStreamReaderMode; +} + +interface ReadableStreamReadDoneResult { done: true; - value?: undefined; + value?: T; } interface ReadableStreamReadValueResult { @@ -658,6 +667,21 @@ interface Transformer { writableType?: undefined; } +interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: UnderlyingSourceCancelCallback; + pull?: (controller: ReadableByteStreamController) => void | PromiseLike; + start?: (controller: ReadableByteStreamController) => any; + type: "bytes"; +} + +interface UnderlyingDefaultSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: (controller: ReadableStreamDefaultController) => void | PromiseLike; + start?: (controller: ReadableStreamDefaultController) => any; + type?: undefined; +} + interface UnderlyingSink { abort?: UnderlyingSinkAbortCallback; close?: UnderlyingSinkCloseCallback; @@ -667,17 +691,18 @@ interface UnderlyingSink { } interface UnderlyingSource { + autoAllocateChunkSize?: number; cancel?: UnderlyingSourceCancelCallback; pull?: UnderlyingSourcePullCallback; start?: UnderlyingSourceStartCallback; - type?: undefined; + type?: ReadableStreamType; } interface VideoColorSpaceInit { - fullRange?: boolean; - matrix?: VideoMatrixCoefficients; - primaries?: VideoColorPrimaries; - transfer?: VideoTransferCharacteristics; + fullRange?: boolean | null; + matrix?: VideoMatrixCoefficients | null; + primaries?: VideoColorPrimaries | null; + transfer?: VideoTransferCharacteristics | null; } interface VideoConfiguration { @@ -727,7 +752,7 @@ interface AbortController { /** Returns the AbortSignal object associated with this object. */ readonly signal: AbortSignal; /** Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. */ - // abort(): AbortSignal; - To be re-added in the future + abort(reason?: any): void; } declare var AbortController: { @@ -756,6 +781,7 @@ declare var AbortSignal: { prototype: AbortSignal; new(): AbortSignal; abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; }; interface AbstractWorkerEventMap { @@ -872,6 +898,44 @@ declare var CacheStorage: { new(): CacheStorage; }; +interface CanvasCompositing { + globalAlpha: number; + globalCompositeOperation: GlobalCompositeOperation; +} + +interface CanvasDrawImage { + drawImage(image: CanvasImageSource, dx: number, dy: number): void; + drawImage(image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void; + drawImage(image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; +} + +interface CanvasDrawPath { + beginPath(): void; + clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; + fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInStroke(x: number, y: number): boolean; + isPointInStroke(path: Path2D, x: number, y: number): boolean; + stroke(): void; + stroke(path: Path2D): void; +} + +interface CanvasFillStrokeStyles { + fillStyle: string | CanvasGradient | CanvasPattern; + strokeStyle: string | CanvasGradient | CanvasPattern; + createConicGradient(startAngle: number, x: number, y: number): CanvasGradient; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: CanvasImageSource, repetition: string | null): CanvasPattern | null; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; +} + +interface CanvasFilters { + filter: string; +} + /** An opaque object describing a gradient. It is returned by the methods CanvasRenderingContext2D.createLinearGradient() or CanvasRenderingContext2D.createRadialGradient(). */ interface CanvasGradient { /** @@ -887,6 +951,19 @@ declare var CanvasGradient: { new(): CanvasGradient; }; +interface CanvasImageData { + createImageData(sw: number, sh: number, settings?: ImageDataSettings): ImageData; + createImageData(imagedata: ImageData): ImageData; + getImageData(sx: number, sy: number, sw: number, sh: number, settings?: ImageDataSettings): ImageData; + putImageData(imagedata: ImageData, dx: number, dy: number): void; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void; +} + +interface CanvasImageSmoothing { + imageSmoothingEnabled: boolean; + imageSmoothingQuality: ImageSmoothingQuality; +} + interface CanvasPath { arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void; arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; @@ -897,6 +974,17 @@ interface CanvasPath { moveTo(x: number, y: number): void; quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; rect(x: number, y: number, w: number, h: number): void; + roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | (number | DOMPointInit)[]): void; +} + +interface CanvasPathDrawingStyles { + lineCap: CanvasLineCap; + lineDashOffset: number; + lineJoin: CanvasLineJoin; + lineWidth: number; + miterLimit: number; + getLineDash(): number[]; + setLineDash(segments: number[]): void; } /** An opaque object describing a pattern, based on an image, a canvas, or a video, created by the CanvasRenderingContext2D.createPattern() method. */ @@ -910,6 +998,49 @@ declare var CanvasPattern: { new(): CanvasPattern; }; +interface CanvasRect { + clearRect(x: number, y: number, w: number, h: number): void; + fillRect(x: number, y: number, w: number, h: number): void; + strokeRect(x: number, y: number, w: number, h: number): void; +} + +interface CanvasShadowStyles { + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; +} + +interface CanvasState { + restore(): void; + save(): void; +} + +interface CanvasText { + fillText(text: string, x: number, y: number, maxWidth?: number): void; + measureText(text: string): TextMetrics; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; +} + +interface CanvasTextDrawingStyles { + direction: CanvasDirection; + font: string; + fontKerning: CanvasFontKerning; + textAlign: CanvasTextAlign; + textBaseline: CanvasTextBaseline; +} + +interface CanvasTransform { + getTransform(): DOMMatrix; + resetTransform(): void; + rotate(angle: number): void; + scale(x: number, y: number): void; + setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void; + setTransform(transform?: DOMMatrix2DInit): void; + transform(a: number, b: number, c: number, d: number, e: number, f: number): void; + translate(x: number, y: number): void; +} + /** The Client interface represents an executable context such as a Worker, or a SharedWorker. Window clients are represented by the more-specific WindowClient. You can get Client/WindowClient objects from methods such as Clients.matchAll() and Clients.get(). */ interface Client { readonly frameType: FrameType; @@ -1316,6 +1447,13 @@ interface EXT_sRGB { interface EXT_shader_texture_lod { } +interface EXT_texture_compression_bptc { + readonly COMPRESSED_RGBA_BPTC_UNORM_EXT: GLenum; + readonly COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT: GLenum; + readonly COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT: GLenum; + readonly COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT: GLenum; +} + interface EXT_texture_compression_rgtc { readonly COMPRESSED_RED_GREEN_RGTC2_EXT: GLenum; readonly COMPRESSED_RED_RGTC1_EXT: GLenum; @@ -1329,6 +1467,17 @@ interface EXT_texture_filter_anisotropic { readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum; } +interface EXT_texture_norm16 { + readonly R16_EXT: GLenum; + readonly R16_SNORM_EXT: GLenum; + readonly RG16_EXT: GLenum; + readonly RG16_SNORM_EXT: GLenum; + readonly RGB16_EXT: GLenum; + readonly RGB16_SNORM_EXT: GLenum; + readonly RGBA16_EXT: GLenum; + readonly RGBA16_SNORM_EXT: GLenum; +} + /** Events providing information related to errors in scripts or in files. */ interface ErrorEvent extends Event { readonly colno: number; @@ -1347,6 +1496,7 @@ declare var ErrorEvent: { interface Event { /** Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. */ readonly bubbles: boolean; + /** @deprecated */ cancelBubble: boolean; /** Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */ readonly cancelable: boolean; @@ -2030,13 +2180,13 @@ declare var IDBObjectStore: { }; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { - "blocked": Event; + "blocked": IDBVersionChangeEvent; "upgradeneeded": IDBVersionChangeEvent; } /** Also inherits methods from its parents IDBRequest and EventTarget. */ interface IDBOpenDBRequest extends IDBRequest { - onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onblocked: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -2292,6 +2442,7 @@ interface NavigatorID { readonly appName: string; /** @deprecated */ readonly appVersion: string; + /** @deprecated */ readonly platform: string; /** @deprecated */ readonly product: string; @@ -2361,6 +2512,16 @@ declare var NotificationEvent: { new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; }; +interface OES_draw_buffers_indexed { + blendEquationSeparateiOES(buf: GLuint, modeRGB: GLenum, modeAlpha: GLenum): void; + blendEquationiOES(buf: GLuint, mode: GLenum): void; + blendFuncSeparateiOES(buf: GLuint, srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum): void; + blendFunciOES(buf: GLuint, src: GLenum, dst: GLenum): void; + colorMaskiOES(buf: GLuint, r: GLboolean, g: GLboolean, b: GLboolean, a: GLboolean): void; + disableiOES(target: GLenum, index: GLuint): void; + enableiOES(target: GLenum, index: GLuint): void; +} + /** The OES_element_index_uint extension is part of the WebGL API and adds support for gl.UNSIGNED_INT types to WebGLRenderingContext.drawElements(). */ interface OES_element_index_uint { } @@ -2406,10 +2567,57 @@ interface OVR_multiview2 { readonly MAX_VIEWS_OVR: GLenum; } -/** @deprecated this is not available in most browsers */ -interface OffscreenCanvas extends EventTarget { +interface OffscreenCanvasEventMap { + "contextlost": Event; + "contextrestored": Event; } +interface OffscreenCanvas extends EventTarget { + /** + * These attributes return the dimensions of the OffscreenCanvas object's bitmap. + * + * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). + */ + height: number; + oncontextlost: ((this: OffscreenCanvas, ev: Event) => any) | null; + oncontextrestored: ((this: OffscreenCanvas, ev: Event) => any) | null; + /** + * These attributes return the dimensions of the OffscreenCanvas object's bitmap. + * + * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). + */ + width: number; + /** + * Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API. + * + * This specification defines the "2d" context below, which is similar but distinct from the "2d" context that is created from a canvas element. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL] + * + * Returns null if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context). + */ + getContext(contextId: OffscreenRenderingContextId, options?: any): OffscreenRenderingContext | null; + /** Returns a newly created ImageBitmap object with the image in the OffscreenCanvas object. The image in the OffscreenCanvas object is replaced with a new blank image. */ + transferToImageBitmap(): ImageBitmap; + addEventListener(type: K, listener: (this: OffscreenCanvas, ev: OffscreenCanvasEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OffscreenCanvas, ev: OffscreenCanvasEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var OffscreenCanvas: { + prototype: OffscreenCanvas; + new(width: number, height: number): OffscreenCanvas; +}; + +interface OffscreenCanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform { + readonly canvas: OffscreenCanvas; + commit(): void; +} + +declare var OffscreenCanvasRenderingContext2D: { + prototype: OffscreenCanvasRenderingContext2D; + new(): OffscreenCanvasRenderingContext2D; +}; + /** This Canvas 2D API interface is used to declare a path that can then be used on a CanvasRenderingContext2D object. The path methods of the CanvasRenderingContext2D interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired. */ interface Path2D extends CanvasPath { /** Adds to the path the path given by the argument. */ @@ -2553,6 +2761,7 @@ interface PermissionStatusEventMap { } interface PermissionStatus extends EventTarget { + readonly name: string; onchange: ((this: PermissionStatus, ev: Event) => any) | null; readonly state: PermissionState; addEventListener(type: K, listener: (this: PermissionStatus, ev: PermissionStatusEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -2664,6 +2873,7 @@ declare var PushSubscription: { /** Available only in secure contexts. */ interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; + readonly userVisibleOnly: boolean; } declare var PushSubscriptionOptions: { @@ -2711,7 +2921,9 @@ declare var ReadableByteStreamController: { interface ReadableStream { readonly locked: boolean; cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; tee(): [ReadableStream, ReadableStream]; @@ -2719,11 +2931,13 @@ interface ReadableStream { declare var ReadableStream: { prototype: ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number }): ReadableStream; + new(underlyingSource: UnderlyingDefaultSource, strategy?: QueuingStrategy): ReadableStream; new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; }; interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { - read(view: ArrayBufferView): Promise>; + read(view: T): Promise>; releaseLock(): void; } @@ -2911,6 +3125,7 @@ interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "notificationclick": NotificationEvent; "notificationclose": NotificationEvent; "push": PushEvent; + "pushsubscriptionchange": Event; } /** This ServiceWorker API interface represents the global execution context of a service worker. */ @@ -2924,6 +3139,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { onnotificationclick: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null; onnotificationclose: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null; onpush: ((this: ServiceWorkerGlobalScope, ev: PushEvent) => any) | null; + onpushsubscriptionchange: ((this: ServiceWorkerGlobalScope, ev: Event) => any) | null; readonly registration: ServiceWorkerRegistration; readonly serviceWorker: ServiceWorker; skipWaiting(): Promise; @@ -3340,8 +3556,8 @@ interface WEBGL_lose_context { interface WEBGL_multi_draw { multiDrawArraysInstancedWEBGL(mode: GLenum, firstsList: Int32Array | GLint[], firstsOffset: GLuint, countsList: Int32Array | GLsizei[], countsOffset: GLuint, instanceCountsList: Int32Array | GLsizei[], instanceCountsOffset: GLuint, drawcount: GLsizei): void; multiDrawArraysWEBGL(mode: GLenum, firstsList: Int32Array | GLint[], firstsOffset: GLuint, countsList: Int32Array | GLsizei[], countsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | GLint[], countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | GLsizei[], offsetsOffset: GLuint, instanceCountsList: Int32Array | GLsizei[], instanceCountsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | GLint[], countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | GLsizei[], offsetsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | GLsizei[], countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | GLsizei[], offsetsOffset: GLuint, instanceCountsList: Int32Array | GLsizei[], instanceCountsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | GLsizei[], countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | GLsizei[], offsetsOffset: GLuint, drawcount: GLsizei): void; } interface WebGL2RenderingContext extends WebGL2RenderingContextBase, WebGL2RenderingContextOverloads, WebGLRenderingContextBase { @@ -4739,35 +4955,39 @@ interface WebGLRenderingContextBase { getBufferParameter(target: GLenum, pname: GLenum): any; getContextAttributes(): WebGLContextAttributes | null; getError(): GLenum; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; getExtension(extensionName: "EXT_color_buffer_float"): EXT_color_buffer_float | null; getExtension(extensionName: "EXT_color_buffer_half_float"): EXT_color_buffer_half_float | null; getExtension(extensionName: "EXT_float_blend"): EXT_float_blend | null; - getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; - getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_texture_compression_bptc"): EXT_texture_compression_bptc | null; + getExtension(extensionName: "EXT_texture_compression_rgtc"): EXT_texture_compression_rgtc | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; getExtension(extensionName: "KHR_parallel_shader_compile"): KHR_parallel_shader_compile | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "OES_fbo_render_mipmap"): OES_fbo_render_mipmap | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; getExtension(extensionName: "OVR_multiview2"): OVR_multiview2 | null; getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; getExtension(extensionName: "WEBGL_compressed_texture_etc"): WEBGL_compressed_texture_etc | null; getExtension(extensionName: "WEBGL_compressed_texture_etc1"): WEBGL_compressed_texture_etc1 | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; - getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; - getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; - getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; - getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; - getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; - getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; - getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; - getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; - getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; - getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: "WEBGL_multi_draw"): WEBGL_multi_draw | null; getExtension(name: string): any; getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum): any; getParameter(pname: GLenum): any; @@ -5893,20 +6113,31 @@ type ImageBitmapSource = CanvasImageSource | Blob | ImageData; type Int32List = Int32Array | GLint[]; type MessageEventSource = MessagePort | ServiceWorker; type NamedCurve = string; +type OffscreenRenderingContext = OffscreenCanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext; type OnErrorEventHandler = OnErrorEventHandlerNonNull | null; type PerformanceEntryList = PerformanceEntry[]; type PushMessageDataInit = BufferSource | string; -type ReadableStreamController = ReadableStreamDefaultController; -type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; -type ReadableStreamReader = ReadableStreamDefaultReader; +type ReadableStreamController = ReadableStreamDefaultController | ReadableByteStreamController; +type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; +type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; type RequestInfo = Request | string; type TexImageSource = ImageBitmap | ImageData | OffscreenCanvas; type TimerHandler = string | Function; -type Transferable = ArrayBuffer | MessagePort | ImageBitmap; +type Transferable = OffscreenCanvas | ImageBitmap | MessagePort | ReadableStream | WritableStream | TransformStream | ArrayBuffer; type Uint32List = Uint32Array | GLuint[]; type VibratePattern = number | number[]; type XMLHttpRequestBodyInit = Blob | BufferSource | FormData | URLSearchParams | string; type BinaryType = "arraybuffer" | "blob"; +type CanvasDirection = "inherit" | "ltr" | "rtl"; +type CanvasFillRule = "evenodd" | "nonzero"; +type CanvasFontKerning = "auto" | "none" | "normal"; +type CanvasFontStretch = "condensed" | "expanded" | "extra-condensed" | "extra-expanded" | "normal" | "semi-condensed" | "semi-expanded" | "ultra-condensed" | "ultra-expanded"; +type CanvasFontVariantCaps = "all-petite-caps" | "all-small-caps" | "normal" | "petite-caps" | "small-caps" | "titling-caps" | "unicase"; +type CanvasLineCap = "butt" | "round" | "square"; +type CanvasLineJoin = "bevel" | "miter" | "round"; +type CanvasTextAlign = "center" | "end" | "left" | "right" | "start"; +type CanvasTextBaseline = "alphabetic" | "bottom" | "hanging" | "ideographic" | "middle" | "top"; +type CanvasTextRendering = "auto" | "geometricPrecision" | "optimizeLegibility" | "optimizeSpeed"; type ClientTypes = "all" | "sharedworker" | "window" | "worker"; type ColorGamut = "p3" | "rec2020" | "srgb"; type ColorSpaceConversion = "default" | "none"; @@ -5916,12 +6147,14 @@ type FileSystemHandleKind = "directory" | "file"; type FontFaceLoadStatus = "error" | "loaded" | "loading" | "unloaded"; type FontFaceSetLoadStatus = "loaded" | "loading"; type FrameType = "auxiliary" | "nested" | "none" | "top-level"; +type GlobalCompositeOperation = "color" | "color-burn" | "color-dodge" | "copy" | "darken" | "destination-atop" | "destination-in" | "destination-out" | "destination-over" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "lighter" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light" | "source-atop" | "source-in" | "source-out" | "source-over" | "xor"; type HdrMetadataType = "smpteSt2086" | "smpteSt2094-10" | "smpteSt2094-40"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "done" | "pending"; type IDBTransactionDurability = "default" | "relaxed" | "strict"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; type ImageOrientation = "flipY" | "none"; +type ImageSmoothingQuality = "high" | "low" | "medium"; type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; type KeyType = "private" | "public" | "secret"; type KeyUsage = "decrypt" | "deriveBits" | "deriveKey" | "encrypt" | "sign" | "unwrapKey" | "verify" | "wrapKey"; @@ -5930,12 +6163,15 @@ type MediaDecodingType = "file" | "media-source" | "webrtc"; type MediaEncodingType = "record" | "webrtc"; type NotificationDirection = "auto" | "ltr" | "rtl"; type NotificationPermission = "default" | "denied" | "granted"; +type OffscreenRenderingContextId = "2d" | "bitmaprenderer" | "webgl" | "webgl2" | "webgpu"; type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock" | "xr-spatial-tracking"; type PermissionState = "denied" | "granted" | "prompt"; type PredefinedColorSpace = "display-p3" | "srgb"; type PremultiplyAlpha = "default" | "none" | "premultiply"; type PushEncryptionKeyName = "auth" | "p256dh"; type RTCEncodedVideoFrameType = "delta" | "empty" | "key"; +type ReadableStreamReaderMode = "byob"; +type ReadableStreamType = "bytes"; type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url"; type RequestCache = "default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload"; type RequestCredentials = "include" | "omit" | "same-origin"; diff --git a/cli/tsc/dts/lib.webworker.iterable.d.ts b/cli/tsc/dts/lib.webworker.iterable.d.ts index 3d9e75d003..b803598532 100644 --- a/cli/tsc/dts/lib.webworker.iterable.d.ts +++ b/cli/tsc/dts/lib.webworker.iterable.d.ts @@ -26,6 +26,14 @@ interface Cache { addAll(requests: Iterable): Promise; } +interface CanvasPath { + roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | Iterable): void; +} + +interface CanvasPathDrawingStyles { + setLineDash(segments: Iterable): void; +} + interface DOMStringList { [Symbol.iterator](): IterableIterator; } @@ -103,8 +111,8 @@ interface WEBGL_draw_buffers { interface WEBGL_multi_draw { multiDrawArraysInstancedWEBGL(mode: GLenum, firstsList: Int32Array | Iterable, firstsOffset: GLuint, countsList: Int32Array | Iterable, countsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; multiDrawArraysWEBGL(mode: GLenum, firstsList: Int32Array | Iterable, firstsOffset: GLuint, countsList: Int32Array | Iterable, countsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, drawcount: GLsizei): void; } interface WebGL2RenderingContextBase { diff --git a/cli/tsc/dts/typescript.d.ts b/cli/tsc/dts/typescript.d.ts index 0fd60ae882..b9cd3d1314 100644 --- a/cli/tsc/dts/typescript.d.ts +++ b/cli/tsc/dts/typescript.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "4.8"; + const versionMajorMinor = "4.9"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -232,237 +232,240 @@ declare namespace ts { StaticKeyword = 124, YieldKeyword = 125, AbstractKeyword = 126, - AsKeyword = 127, - AssertsKeyword = 128, - AssertKeyword = 129, - AnyKeyword = 130, - AsyncKeyword = 131, - AwaitKeyword = 132, - BooleanKeyword = 133, - ConstructorKeyword = 134, - DeclareKeyword = 135, - GetKeyword = 136, - InferKeyword = 137, - IntrinsicKeyword = 138, - IsKeyword = 139, - KeyOfKeyword = 140, - ModuleKeyword = 141, - NamespaceKeyword = 142, - NeverKeyword = 143, - OutKeyword = 144, - ReadonlyKeyword = 145, - RequireKeyword = 146, - NumberKeyword = 147, - ObjectKeyword = 148, - SetKeyword = 149, - StringKeyword = 150, - SymbolKeyword = 151, - TypeKeyword = 152, - UndefinedKeyword = 153, - UniqueKeyword = 154, - UnknownKeyword = 155, - FromKeyword = 156, - GlobalKeyword = 157, - BigIntKeyword = 158, - OverrideKeyword = 159, - OfKeyword = 160, - QualifiedName = 161, - ComputedPropertyName = 162, - TypeParameter = 163, - Parameter = 164, - Decorator = 165, - PropertySignature = 166, - PropertyDeclaration = 167, - MethodSignature = 168, - MethodDeclaration = 169, - ClassStaticBlockDeclaration = 170, - Constructor = 171, - GetAccessor = 172, - SetAccessor = 173, - CallSignature = 174, - ConstructSignature = 175, - IndexSignature = 176, - TypePredicate = 177, - TypeReference = 178, - FunctionType = 179, - ConstructorType = 180, - TypeQuery = 181, - TypeLiteral = 182, - ArrayType = 183, - TupleType = 184, - OptionalType = 185, - RestType = 186, - UnionType = 187, - IntersectionType = 188, - ConditionalType = 189, - InferType = 190, - ParenthesizedType = 191, - ThisType = 192, - TypeOperator = 193, - IndexedAccessType = 194, - MappedType = 195, - LiteralType = 196, - NamedTupleMember = 197, - TemplateLiteralType = 198, - TemplateLiteralTypeSpan = 199, - ImportType = 200, - ObjectBindingPattern = 201, - ArrayBindingPattern = 202, - BindingElement = 203, - ArrayLiteralExpression = 204, - ObjectLiteralExpression = 205, - PropertyAccessExpression = 206, - ElementAccessExpression = 207, - CallExpression = 208, - NewExpression = 209, - TaggedTemplateExpression = 210, - TypeAssertionExpression = 211, - ParenthesizedExpression = 212, - FunctionExpression = 213, - ArrowFunction = 214, - DeleteExpression = 215, - TypeOfExpression = 216, - VoidExpression = 217, - AwaitExpression = 218, - PrefixUnaryExpression = 219, - PostfixUnaryExpression = 220, - BinaryExpression = 221, - ConditionalExpression = 222, - TemplateExpression = 223, - YieldExpression = 224, - SpreadElement = 225, - ClassExpression = 226, - OmittedExpression = 227, - ExpressionWithTypeArguments = 228, - AsExpression = 229, - NonNullExpression = 230, - MetaProperty = 231, - SyntheticExpression = 232, - TemplateSpan = 233, - SemicolonClassElement = 234, - Block = 235, - EmptyStatement = 236, - VariableStatement = 237, - ExpressionStatement = 238, - IfStatement = 239, - DoStatement = 240, - WhileStatement = 241, - ForStatement = 242, - ForInStatement = 243, - ForOfStatement = 244, - ContinueStatement = 245, - BreakStatement = 246, - ReturnStatement = 247, - WithStatement = 248, - SwitchStatement = 249, - LabeledStatement = 250, - ThrowStatement = 251, - TryStatement = 252, - DebuggerStatement = 253, - VariableDeclaration = 254, - VariableDeclarationList = 255, - FunctionDeclaration = 256, - ClassDeclaration = 257, - InterfaceDeclaration = 258, - TypeAliasDeclaration = 259, - EnumDeclaration = 260, - ModuleDeclaration = 261, - ModuleBlock = 262, - CaseBlock = 263, - NamespaceExportDeclaration = 264, - ImportEqualsDeclaration = 265, - ImportDeclaration = 266, - ImportClause = 267, - NamespaceImport = 268, - NamedImports = 269, - ImportSpecifier = 270, - ExportAssignment = 271, - ExportDeclaration = 272, - NamedExports = 273, - NamespaceExport = 274, - ExportSpecifier = 275, - MissingDeclaration = 276, - ExternalModuleReference = 277, - JsxElement = 278, - JsxSelfClosingElement = 279, - JsxOpeningElement = 280, - JsxClosingElement = 281, - JsxFragment = 282, - JsxOpeningFragment = 283, - JsxClosingFragment = 284, - JsxAttribute = 285, - JsxAttributes = 286, - JsxSpreadAttribute = 287, - JsxExpression = 288, - CaseClause = 289, - DefaultClause = 290, - HeritageClause = 291, - CatchClause = 292, - AssertClause = 293, - AssertEntry = 294, - ImportTypeAssertionContainer = 295, - PropertyAssignment = 296, - ShorthandPropertyAssignment = 297, - SpreadAssignment = 298, - EnumMember = 299, - UnparsedPrologue = 300, - UnparsedPrepend = 301, - UnparsedText = 302, - UnparsedInternalText = 303, - UnparsedSyntheticReference = 304, - SourceFile = 305, - Bundle = 306, - UnparsedSource = 307, - InputFiles = 308, - JSDocTypeExpression = 309, - JSDocNameReference = 310, - JSDocMemberName = 311, - JSDocAllType = 312, - JSDocUnknownType = 313, - JSDocNullableType = 314, - JSDocNonNullableType = 315, - JSDocOptionalType = 316, - JSDocFunctionType = 317, - JSDocVariadicType = 318, - JSDocNamepathType = 319, - JSDoc = 320, + AccessorKeyword = 127, + AsKeyword = 128, + AssertsKeyword = 129, + AssertKeyword = 130, + AnyKeyword = 131, + AsyncKeyword = 132, + AwaitKeyword = 133, + BooleanKeyword = 134, + ConstructorKeyword = 135, + DeclareKeyword = 136, + GetKeyword = 137, + InferKeyword = 138, + IntrinsicKeyword = 139, + IsKeyword = 140, + KeyOfKeyword = 141, + ModuleKeyword = 142, + NamespaceKeyword = 143, + NeverKeyword = 144, + OutKeyword = 145, + ReadonlyKeyword = 146, + RequireKeyword = 147, + NumberKeyword = 148, + ObjectKeyword = 149, + SatisfiesKeyword = 150, + SetKeyword = 151, + StringKeyword = 152, + SymbolKeyword = 153, + TypeKeyword = 154, + UndefinedKeyword = 155, + UniqueKeyword = 156, + UnknownKeyword = 157, + FromKeyword = 158, + GlobalKeyword = 159, + BigIntKeyword = 160, + OverrideKeyword = 161, + OfKeyword = 162, + QualifiedName = 163, + ComputedPropertyName = 164, + TypeParameter = 165, + Parameter = 166, + Decorator = 167, + PropertySignature = 168, + PropertyDeclaration = 169, + MethodSignature = 170, + MethodDeclaration = 171, + ClassStaticBlockDeclaration = 172, + Constructor = 173, + GetAccessor = 174, + SetAccessor = 175, + CallSignature = 176, + ConstructSignature = 177, + IndexSignature = 178, + TypePredicate = 179, + TypeReference = 180, + FunctionType = 181, + ConstructorType = 182, + TypeQuery = 183, + TypeLiteral = 184, + ArrayType = 185, + TupleType = 186, + OptionalType = 187, + RestType = 188, + UnionType = 189, + IntersectionType = 190, + ConditionalType = 191, + InferType = 192, + ParenthesizedType = 193, + ThisType = 194, + TypeOperator = 195, + IndexedAccessType = 196, + MappedType = 197, + LiteralType = 198, + NamedTupleMember = 199, + TemplateLiteralType = 200, + TemplateLiteralTypeSpan = 201, + ImportType = 202, + ObjectBindingPattern = 203, + ArrayBindingPattern = 204, + BindingElement = 205, + ArrayLiteralExpression = 206, + ObjectLiteralExpression = 207, + PropertyAccessExpression = 208, + ElementAccessExpression = 209, + CallExpression = 210, + NewExpression = 211, + TaggedTemplateExpression = 212, + TypeAssertionExpression = 213, + ParenthesizedExpression = 214, + FunctionExpression = 215, + ArrowFunction = 216, + DeleteExpression = 217, + TypeOfExpression = 218, + VoidExpression = 219, + AwaitExpression = 220, + PrefixUnaryExpression = 221, + PostfixUnaryExpression = 222, + BinaryExpression = 223, + ConditionalExpression = 224, + TemplateExpression = 225, + YieldExpression = 226, + SpreadElement = 227, + ClassExpression = 228, + OmittedExpression = 229, + ExpressionWithTypeArguments = 230, + AsExpression = 231, + NonNullExpression = 232, + MetaProperty = 233, + SyntheticExpression = 234, + SatisfiesExpression = 235, + TemplateSpan = 236, + SemicolonClassElement = 237, + Block = 238, + EmptyStatement = 239, + VariableStatement = 240, + ExpressionStatement = 241, + IfStatement = 242, + DoStatement = 243, + WhileStatement = 244, + ForStatement = 245, + ForInStatement = 246, + ForOfStatement = 247, + ContinueStatement = 248, + BreakStatement = 249, + ReturnStatement = 250, + WithStatement = 251, + SwitchStatement = 252, + LabeledStatement = 253, + ThrowStatement = 254, + TryStatement = 255, + DebuggerStatement = 256, + VariableDeclaration = 257, + VariableDeclarationList = 258, + FunctionDeclaration = 259, + ClassDeclaration = 260, + InterfaceDeclaration = 261, + TypeAliasDeclaration = 262, + EnumDeclaration = 263, + ModuleDeclaration = 264, + ModuleBlock = 265, + CaseBlock = 266, + NamespaceExportDeclaration = 267, + ImportEqualsDeclaration = 268, + ImportDeclaration = 269, + ImportClause = 270, + NamespaceImport = 271, + NamedImports = 272, + ImportSpecifier = 273, + ExportAssignment = 274, + ExportDeclaration = 275, + NamedExports = 276, + NamespaceExport = 277, + ExportSpecifier = 278, + MissingDeclaration = 279, + ExternalModuleReference = 280, + JsxElement = 281, + JsxSelfClosingElement = 282, + JsxOpeningElement = 283, + JsxClosingElement = 284, + JsxFragment = 285, + JsxOpeningFragment = 286, + JsxClosingFragment = 287, + JsxAttribute = 288, + JsxAttributes = 289, + JsxSpreadAttribute = 290, + JsxExpression = 291, + CaseClause = 292, + DefaultClause = 293, + HeritageClause = 294, + CatchClause = 295, + AssertClause = 296, + AssertEntry = 297, + ImportTypeAssertionContainer = 298, + PropertyAssignment = 299, + ShorthandPropertyAssignment = 300, + SpreadAssignment = 301, + EnumMember = 302, + UnparsedPrologue = 303, + UnparsedPrepend = 304, + UnparsedText = 305, + UnparsedInternalText = 306, + UnparsedSyntheticReference = 307, + SourceFile = 308, + Bundle = 309, + UnparsedSource = 310, + InputFiles = 311, + JSDocTypeExpression = 312, + JSDocNameReference = 313, + JSDocMemberName = 314, + JSDocAllType = 315, + JSDocUnknownType = 316, + JSDocNullableType = 317, + JSDocNonNullableType = 318, + JSDocOptionalType = 319, + JSDocFunctionType = 320, + JSDocVariadicType = 321, + JSDocNamepathType = 322, + JSDoc = 323, /** @deprecated Use SyntaxKind.JSDoc */ - JSDocComment = 320, - JSDocText = 321, - JSDocTypeLiteral = 322, - JSDocSignature = 323, - JSDocLink = 324, - JSDocLinkCode = 325, - JSDocLinkPlain = 326, - JSDocTag = 327, - JSDocAugmentsTag = 328, - JSDocImplementsTag = 329, - JSDocAuthorTag = 330, - JSDocDeprecatedTag = 331, - JSDocClassTag = 332, - JSDocPublicTag = 333, - JSDocPrivateTag = 334, - JSDocProtectedTag = 335, - JSDocReadonlyTag = 336, - JSDocOverrideTag = 337, - JSDocCallbackTag = 338, - JSDocEnumTag = 339, - JSDocParameterTag = 340, - JSDocReturnTag = 341, - JSDocThisTag = 342, - JSDocTypeTag = 343, - JSDocTemplateTag = 344, - JSDocTypedefTag = 345, - JSDocSeeTag = 346, - JSDocPropertyTag = 347, - SyntaxList = 348, - NotEmittedStatement = 349, - PartiallyEmittedExpression = 350, - CommaListExpression = 351, - MergeDeclarationMarker = 352, - EndOfDeclarationMarker = 353, - SyntheticReferenceExpression = 354, - Count = 355, + JSDocComment = 323, + JSDocText = 324, + JSDocTypeLiteral = 325, + JSDocSignature = 326, + JSDocLink = 327, + JSDocLinkCode = 328, + JSDocLinkPlain = 329, + JSDocTag = 330, + JSDocAugmentsTag = 331, + JSDocImplementsTag = 332, + JSDocAuthorTag = 333, + JSDocDeprecatedTag = 334, + JSDocClassTag = 335, + JSDocPublicTag = 336, + JSDocPrivateTag = 337, + JSDocProtectedTag = 338, + JSDocReadonlyTag = 339, + JSDocOverrideTag = 340, + JSDocCallbackTag = 341, + JSDocEnumTag = 342, + JSDocParameterTag = 343, + JSDocReturnTag = 344, + JSDocThisTag = 345, + JSDocTypeTag = 346, + JSDocTemplateTag = 347, + JSDocTypedefTag = 348, + JSDocSeeTag = 349, + JSDocPropertyTag = 350, + SyntaxList = 351, + NotEmittedStatement = 352, + PartiallyEmittedExpression = 353, + CommaListExpression = 354, + MergeDeclarationMarker = 355, + EndOfDeclarationMarker = 356, + SyntheticReferenceExpression = 357, + Count = 358, FirstAssignment = 63, LastAssignment = 78, FirstCompoundAssignment = 64, @@ -470,15 +473,15 @@ declare namespace ts { FirstReservedWord = 81, LastReservedWord = 116, FirstKeyword = 81, - LastKeyword = 160, + LastKeyword = 162, FirstFutureReservedWord = 117, LastFutureReservedWord = 125, - FirstTypeNode = 177, - LastTypeNode = 200, + FirstTypeNode = 179, + LastTypeNode = 202, FirstPunctuation = 18, LastPunctuation = 78, FirstToken = 0, - LastToken = 160, + LastToken = 162, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -487,20 +490,20 @@ declare namespace ts { LastTemplateToken = 17, FirstBinaryOperator = 29, LastBinaryOperator = 78, - FirstStatement = 237, - LastStatement = 253, - FirstNode = 161, - FirstJSDocNode = 309, - LastJSDocNode = 347, - FirstJSDocTagNode = 327, - LastJSDocTagNode = 347, + FirstStatement = 240, + LastStatement = 256, + FirstNode = 163, + FirstJSDocNode = 312, + LastJSDocNode = 350, + FirstJSDocTagNode = 330, + LastJSDocTagNode = 350, } export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; export type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; export type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; - export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; - export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.InKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; + export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SatisfiesKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; + export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.InKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; export type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; export type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; export type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; @@ -545,9 +548,10 @@ declare namespace ts { Protected = 16, Static = 32, Readonly = 64, - Abstract = 128, - Async = 256, - Default = 512, + Accessor = 128, + Abstract = 256, + Async = 512, + Default = 1024, Const = 2048, HasComputedJSDocModifiers = 4096, Deprecated = 8192, @@ -559,10 +563,10 @@ declare namespace ts { AccessibilityModifier = 28, ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, - TypeScriptModifier = 116958, - ExportDefault = 513, - All = 257023, - Modifier = 125951 + TypeScriptModifier = 117086, + ExportDefault = 1025, + All = 258047, + Modifier = 126975 } export enum JsxFlags { None = 0, @@ -618,6 +622,7 @@ declare namespace ts { export interface ModifierToken extends KeywordToken { } export type AbstractKeyword = ModifierToken; + export type AccessorKeyword = ModifierToken; export type AsyncKeyword = ModifierToken; export type ConstKeyword = ModifierToken; export type DeclareKeyword = ModifierToken; @@ -633,11 +638,11 @@ declare namespace ts { export type StaticKeyword = ModifierToken; /** @deprecated Use `ReadonlyKeyword` instead. */ export type ReadonlyToken = ReadonlyKeyword; - export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | InKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OutKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; + export type Modifier = AbstractKeyword | AccessorKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | InKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OutKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; export type ModifierLike = Modifier | Decorator; export type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; - export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword; + export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword | AccessorKeyword; export type ModifiersArray = NodeArray; export enum GeneratedIdentifierFlags { None = 0, @@ -764,6 +769,9 @@ declare namespace ts { readonly type?: TypeNode; readonly initializer?: Expression; } + export interface AutoAccessorPropertyDeclaration extends PropertyDeclaration { + _autoAccessorBrand: any; + } export interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrand: any; readonly name?: PropertyName; @@ -1340,6 +1348,11 @@ declare namespace ts { readonly type: TypeNode; readonly expression: UnaryExpression; } + export interface SatisfiesExpression extends Expression { + readonly kind: SyntaxKind.SatisfiesExpression; + readonly expression: Expression; + readonly type: TypeNode; + } export type AssertionExpression = TypeAssertion | AsExpression; export interface NonNullExpression extends LeftHandSideExpression { readonly kind: SyntaxKind.NonNullExpression; @@ -2316,6 +2329,7 @@ declare namespace ts { getPrivateIdentifierPropertyOfType(leftType: Type, name: string, location: Node): Symbol | undefined; getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; getIndexInfosOfType(type: Type): readonly IndexInfo[]; + getIndexInfosOfIndexSymbol: (indexSymbol: Symbol) => IndexInfo[]; getSignaturesOfType(type: Type, kind: SignatureKind): readonly Signature[]; getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined; getBaseTypes(type: InterfaceType): BaseType[]; @@ -2394,7 +2408,7 @@ declare namespace ts { getExportsOfModule(moduleSymbol: Symbol): Symbol[]; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; - getAmbientModules(): Symbol[]; + getAmbientModules(sourceFile?: SourceFile): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; getBaseConstraintOfType(type: Type): Type | undefined; @@ -2562,6 +2576,7 @@ declare namespace ts { MethodExcludes = 103359, GetAccessorExcludes = 46015, SetAccessorExcludes = 78783, + AccessorExcludes = 13247, TypeParameterExcludes = 526824, TypeAliasExcludes = 788968, AliasExcludes = 2097152, @@ -2832,7 +2847,7 @@ declare namespace ts { export interface SubstitutionType extends InstantiableType { objectFlags: ObjectFlags; baseType: Type; - substitute: Type; + constraint: Type; } export enum SignatureKind { Call = 0, @@ -3305,6 +3320,8 @@ declare namespace ts { */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingFileMode?: SourceFile["impliedNodeFormat"] | undefined): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string | undefined; + /** If provided along with custom resolveModuleNames or resolveTypeReferenceDirectives, used to determine if unchanged file path needs to re-resolve modules/type reference directives */ + hasInvalidatedResolutions?(filePath: Path): boolean; createHash?(data: string): string; getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; } @@ -3387,7 +3404,7 @@ declare namespace ts { createNumericLiteral(value: string | number, numericLiteralFlags?: TokenFlags): NumericLiteral; createBigIntLiteral(value: string | PseudoBigInt): BigIntLiteral; createStringLiteral(text: string, isSingleQuote?: boolean): StringLiteral; - createStringLiteralFromNode(sourceNode: PropertyNameLiteral, isSingleQuote?: boolean): StringLiteral; + createStringLiteralFromNode(sourceNode: PropertyNameLiteral | PrivateIdentifier, isSingleQuote?: boolean): StringLiteral; createRegularExpressionLiteral(text: string): RegularExpressionLiteral; createIdentifier(text: string): Identifier; /** @@ -3412,6 +3429,8 @@ declare namespace ts { /** Create a unique name generated for a node. */ getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier; createPrivateIdentifier(text: string): PrivateIdentifier; + createUniquePrivateName(text?: string): PrivateIdentifier; + getGeneratedPrivateNameForNode(node: Node): PrivateIdentifier; createToken(token: SyntaxKind.SuperKeyword): SuperExpression; createToken(token: SyntaxKind.ThisKeyword): ThisExpression; createToken(token: SyntaxKind.NullKeyword): NullLiteral; @@ -3587,6 +3606,8 @@ declare namespace ts { updateNonNullChain(node: NonNullChain, expression: Expression): NonNullChain; createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; + createSatisfiesExpression(expression: Expression, type: TypeNode): SatisfiesExpression; + updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode): SatisfiesExpression; createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; createSemicolonClassElement(): SemicolonClassElement; @@ -3948,7 +3969,7 @@ declare namespace ts { (nodes: NodeArray, visitor: Visitor | undefined, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; (nodes: NodeArray | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray | undefined; } - export type VisitResult = T | T[] | undefined; + export type VisitResult = T | readonly T[] | undefined; export interface Printer { /** * Print a node and its subtree as-is, without any emit transformations. @@ -4515,6 +4536,7 @@ declare namespace ts { function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; + function isAutoAccessorPropertyDeclaration(node: Node): node is AutoAccessorPropertyDeclaration; function isModifierLike(node: Node): node is ModifierLike; function isTypeElement(node: Node): node is TypeElement; function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement; @@ -4716,6 +4738,7 @@ declare namespace ts { function isOmittedExpression(node: Node): node is OmittedExpression; function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; function isAsExpression(node: Node): node is AsExpression; + function isSatisfiesExpression(node: Node): node is SatisfiesExpression; function isNonNullExpression(node: Node): node is NonNullExpression; function isMetaProperty(node: Node): node is MetaProperty; function isSyntheticExpression(node: Node): node is SyntheticExpression; @@ -5376,9 +5399,9 @@ declare namespace ts { /** If provided, called with Diagnostic message that informs about change in watch status */ onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions, errorCount?: number): void; /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: CompilerOptions): FileWatcher; + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: CompilerOptions): FileWatcher; + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; /** If provided, will be used to reset existing delayed compilation */ @@ -5421,6 +5444,8 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile?: SourceFile): (ResolvedModule | undefined)[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingFileMode?: SourceFile["impliedNodeFormat"] | undefined): (ResolvedTypeReferenceDirective | undefined)[]; + /** If provided along with custom resolveModuleNames or resolveTypeReferenceDirectives, used to determine if unchanged file path needs to re-resolve modules/type reference directives */ + hasInvalidatedResolutions?(filePath: Path): boolean; /** * Returns the module resolution cache used by a provided `resolveModuleNames` implementation so that any non-name module resolution operations (eg, package.json lookup) can reuse it */ @@ -6007,8 +6032,15 @@ declare namespace ts { type: "file"; fileName: string; } + enum OrganizeImportsMode { + All = "All", + SortAndCombine = "SortAndCombine", + RemoveUnused = "RemoveUnused" + } interface OrganizeImportsArgs extends CombinedCodeFixScope { + /** @deprecated Use `mode` instead */ skipDestructiveCodeActions?: boolean; + mode?: OrganizeImportsMode; } type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; enum CompletionTriggerKind { @@ -6526,7 +6558,7 @@ declare namespace ts { isGlobalCompletion: boolean; isMemberCompletion: boolean; /** - * In the absence of `CompletionEntry["replacementSpan"], the editor may choose whether to use + * In the absence of `CompletionEntry["replacementSpan"]`, the editor may choose whether to use * this span or its default one. If `CompletionEntry["replacementSpan"]` is defined, that span * must be used to commit that completion entry. */ @@ -6739,6 +6771,8 @@ declare namespace ts { * interface Y { foo:number; } */ memberVariableElement = "property", + /** class X { [public|private]* accessor foo: number; } */ + memberAccessorVariableElement = "accessor", /** * class X { constructor() { } } * class X { static { } } @@ -7018,7 +7052,7 @@ declare namespace ts { (text: string, isSingleQuote?: boolean | undefined, hasExtendedUnicodeEscape?: boolean | undefined): StringLiteral; }; /** @deprecated Use `factory.createStringLiteralFromNode` or the factory supplied by your transformation context instead. */ - const createStringLiteralFromNode: (sourceNode: PropertyNameLiteral, isSingleQuote?: boolean | undefined) => StringLiteral; + const createStringLiteralFromNode: (sourceNode: PrivateIdentifier | PropertyNameLiteral, isSingleQuote?: boolean | undefined) => StringLiteral; /** @deprecated Use `factory.createRegularExpressionLiteral` or the factory supplied by your transformation context instead. */ const createRegularExpressionLiteral: (text: string) => RegularExpressionLiteral; /** @deprecated Use `factory.createLoopVariable` or the factory supplied by your transformation context instead. */ diff --git a/cli/tsc/mod.rs b/cli/tsc/mod.rs index a8cb7bcabc..c22640748b 100644 --- a/cli/tsc/mod.rs +++ b/cli/tsc/mod.rs @@ -6,9 +6,9 @@ use crate::graph_util::ModuleEntry; use crate::node; use crate::node::node_resolve_npm_reference; use crate::node::NodeResolution; -use crate::node::NodeResolutionMode; use crate::npm::NpmPackageReference; use crate::npm::NpmPackageResolver; +use crate::util::checksum; use deno_ast::MediaType; use deno_core::anyhow::anyhow; @@ -32,6 +32,7 @@ use deno_core::OpState; use deno_core::RuntimeOptions; use deno_core::Snapshot; use deno_graph::Resolved; +use deno_runtime::deno_node::NodeResolutionMode; use once_cell::sync::Lazy; use std::borrow::Cow; use std::collections::HashMap; @@ -178,7 +179,7 @@ fn get_maybe_hash( if let Some(source) = maybe_source { let mut data = vec![source.as_bytes().to_owned()]; data.extend_from_slice(hash_data); - Some(crate::checksum::gen(&data)) + Some(checksum::gen(&data)) } else { None } @@ -186,7 +187,7 @@ fn get_maybe_hash( /// Hash the URL so it can be sent to `tsc` in a supportable way fn hash_url(specifier: &ModuleSpecifier, media_type: MediaType) -> String { - let hash = crate::checksum::gen(&[specifier.path().as_bytes()]); + let hash = checksum::gen(&[specifier.path().as_bytes()]); format!( "{}:///{}{}", specifier.scheme(), @@ -365,7 +366,7 @@ fn op_create_hash(s: &mut OpState, args: Value) -> Result { .context("Invalid request from JavaScript for \"op_create_hash\".")?; let mut data = vec![v.data.as_bytes().to_owned()]; data.extend_from_slice(&state.hash_data); - let hash = crate::checksum::gen(&data); + let hash = checksum::gen(&data); Ok(json!({ "hash": hash })) } @@ -541,7 +542,8 @@ fn op_resolve( args: ResolveArgs, ) -> Result, AnyError> { let state = state.borrow_mut::(); - let mut resolved: Vec<(String, String)> = Vec::new(); + let mut resolved: Vec<(String, String)> = + Vec::with_capacity(args.specifiers.len()); let referrer = if let Some(remapped_specifier) = state.remapped_specifiers.get(&args.base) { @@ -618,7 +620,7 @@ fn op_resolve( node::node_resolve( specifier, &referrer, - node::NodeResolutionMode::Types, + NodeResolutionMode::Types, npm_resolver, ) .ok() @@ -660,6 +662,7 @@ fn op_resolve( ".d.ts".to_string(), ), }; + log::debug!("Resolved {} to {:?}", specifier, result); resolved.push(result); } } @@ -682,9 +685,9 @@ pub fn resolve_npm_package_reference_types( } #[op] -fn op_is_node_file(state: &mut OpState, path: String) -> bool { +fn op_is_node_file(state: &mut OpState, path: &str) -> bool { let state = state.borrow::(); - match ModuleSpecifier::parse(&path) { + match ModuleSpecifier::parse(path) { Ok(specifier) => state .maybe_npm_resolver .as_ref() @@ -860,7 +863,6 @@ mod tests { is_dynamic: false, imports: None, resolver: None, - locker: None, module_analyzer: None, reporter: None, }, @@ -893,7 +895,6 @@ mod tests { is_dynamic: false, imports: None, resolver: None, - locker: None, module_analyzer: None, reporter: None, }, diff --git a/cli/checksum.rs b/cli/util/checksum.rs similarity index 100% rename from cli/checksum.rs rename to cli/util/checksum.rs diff --git a/cli/diff.rs b/cli/util/diff.rs similarity index 100% rename from cli/diff.rs rename to cli/util/diff.rs diff --git a/cli/display.rs b/cli/util/display.rs similarity index 100% rename from cli/display.rs rename to cli/util/display.rs diff --git a/cli/file_watcher.rs b/cli/util/file_watcher.rs similarity index 99% rename from cli/file_watcher.rs rename to cli/util/file_watcher.rs index 78a5e7a821..5158437a02 100644 --- a/cli/file_watcher.rs +++ b/cli/util/file_watcher.rs @@ -1,7 +1,7 @@ // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. use crate::colors; -use crate::fs_util::canonicalize_path; +use crate::util::fs::canonicalize_path; use deno_core::error::AnyError; use deno_core::error::JsError; diff --git a/cli/util/fs.rs b/cli/util/fs.rs new file mode 100644 index 0000000000..40dfafdd85 --- /dev/null +++ b/cli/util/fs.rs @@ -0,0 +1,776 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +use deno_core::anyhow::Context; +use deno_core::error::AnyError; +pub use deno_core::normalize_path; +use deno_core::ModuleSpecifier; +use deno_runtime::deno_crypto::rand; +use deno_runtime::deno_node::PathClean; +use std::env::current_dir; +use std::fs::OpenOptions; +use std::io::Error; +use std::io::ErrorKind; +use std::io::Write; +use std::path::Path; +use std::path::PathBuf; +use std::time::Duration; +use walkdir::WalkDir; + +use super::path::specifier_to_file_path; + +pub fn atomic_write_file>( + filename: &Path, + data: T, + mode: u32, +) -> std::io::Result<()> { + let rand: String = (0..4) + .map(|_| format!("{:02x}", rand::random::())) + .collect(); + let extension = format!("{}.tmp", rand); + let tmp_file = filename.with_extension(extension); + write_file(&tmp_file, data, mode)?; + std::fs::rename(tmp_file, filename)?; + Ok(()) +} + +pub fn write_file>( + filename: &Path, + data: T, + mode: u32, +) -> std::io::Result<()> { + write_file_2(filename, data, true, mode, true, false) +} + +pub fn write_file_2>( + filename: &Path, + data: T, + update_mode: bool, + mode: u32, + is_create: bool, + is_append: bool, +) -> std::io::Result<()> { + let mut file = OpenOptions::new() + .read(false) + .write(true) + .append(is_append) + .truncate(!is_append) + .create(is_create) + .open(filename)?; + + if update_mode { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = mode & 0o777; + let permissions = PermissionsExt::from_mode(mode); + file.set_permissions(permissions)?; + } + #[cfg(not(unix))] + let _ = mode; + } + + file.write_all(data.as_ref()) +} + +/// Similar to `std::fs::canonicalize()` but strips UNC prefixes on Windows. +pub fn canonicalize_path(path: &Path) -> Result { + let path = path.canonicalize()?; + #[cfg(windows)] + return Ok(strip_unc_prefix(path)); + #[cfg(not(windows))] + return Ok(path); +} + +/// Canonicalizes a path which might be non-existent by going up the +/// ancestors until it finds a directory that exists, canonicalizes +/// that path, then adds back the remaining path components. +/// +/// Note: When using this, you should be aware that a symlink may +/// subsequently be created along this path by some other code. +pub fn canonicalize_path_maybe_not_exists( + path: &Path, +) -> Result { + let path = path.to_path_buf().clean(); + let mut path = path.as_path(); + let mut names_stack = Vec::new(); + loop { + match canonicalize_path(path) { + Ok(mut canonicalized_path) => { + for name in names_stack.into_iter().rev() { + canonicalized_path = canonicalized_path.join(name); + } + return Ok(canonicalized_path); + } + Err(err) if err.kind() == ErrorKind::NotFound => { + names_stack.push(path.file_name().unwrap()); + path = path.parent().unwrap(); + } + Err(err) => return Err(err), + } + } +} + +#[cfg(windows)] +fn strip_unc_prefix(path: PathBuf) -> PathBuf { + use std::path::Component; + use std::path::Prefix; + + let mut components = path.components(); + match components.next() { + Some(Component::Prefix(prefix)) => { + match prefix.kind() { + // \\?\device + Prefix::Verbatim(device) => { + let mut path = PathBuf::new(); + path.push(format!(r"\\{}\", device.to_string_lossy())); + path.extend(components.filter(|c| !matches!(c, Component::RootDir))); + path + } + // \\?\c:\path + Prefix::VerbatimDisk(_) => { + let mut path = PathBuf::new(); + path.push(prefix.as_os_str().to_string_lossy().replace(r"\\?\", "")); + path.extend(components); + path + } + // \\?\UNC\hostname\share_name\path + Prefix::VerbatimUNC(hostname, share_name) => { + let mut path = PathBuf::new(); + path.push(format!( + r"\\{}\{}\", + hostname.to_string_lossy(), + share_name.to_string_lossy() + )); + path.extend(components.filter(|c| !matches!(c, Component::RootDir))); + path + } + _ => path, + } + } + _ => path, + } +} + +pub fn resolve_from_cwd(path: &Path) -> Result { + let resolved_path = if path.is_absolute() { + path.to_owned() + } else { + let cwd = + current_dir().context("Failed to get current working directory")?; + cwd.join(path) + }; + + Ok(normalize_path(&resolved_path)) +} + +/// Collects file paths that satisfy the given predicate, by recursively walking `files`. +/// If the walker visits a path that is listed in `ignore`, it skips descending into the directory. +pub struct FileCollector bool> { + canonicalized_ignore: Vec, + file_filter: TFilter, + ignore_git_folder: bool, + ignore_node_modules: bool, +} + +impl bool> FileCollector { + pub fn new(file_filter: TFilter) -> Self { + Self { + canonicalized_ignore: Default::default(), + file_filter, + ignore_git_folder: false, + ignore_node_modules: false, + } + } + pub fn add_ignore_paths(mut self, paths: &[PathBuf]) -> Self { + // retain only the paths which exist and ignore the rest + self + .canonicalized_ignore + .extend(paths.iter().filter_map(|i| canonicalize_path(i).ok())); + self + } + + pub fn ignore_node_modules(mut self) -> Self { + self.ignore_node_modules = true; + self + } + + pub fn ignore_git_folder(mut self) -> Self { + self.ignore_git_folder = true; + self + } + + pub fn collect_files( + &self, + files: &[PathBuf], + ) -> Result, AnyError> { + let mut target_files = Vec::new(); + for file in files { + if let Ok(file) = canonicalize_path(file) { + // use an iterator like this in order to minimize the number of file system operations + let mut iterator = WalkDir::new(&file).into_iter(); + loop { + let e = match iterator.next() { + None => break, + Some(Err(_)) => continue, + Some(Ok(entry)) => entry, + }; + let file_type = e.file_type(); + let is_dir = file_type.is_dir(); + if let Ok(c) = canonicalize_path(e.path()) { + if self.canonicalized_ignore.iter().any(|i| c.starts_with(i)) { + if is_dir { + iterator.skip_current_dir(); + } + } else if is_dir { + let should_ignore_dir = c + .file_name() + .map(|dir_name| { + let dir_name = dir_name.to_string_lossy().to_lowercase(); + let is_ignored_file = self.ignore_node_modules + && dir_name == "node_modules" + || self.ignore_git_folder && dir_name == ".git"; + // allow the user to opt out of ignoring by explicitly specifying the dir + file != c && is_ignored_file + }) + .unwrap_or(false); + if should_ignore_dir { + iterator.skip_current_dir(); + } + } else if (self.file_filter)(e.path()) { + target_files.push(c); + } + } else if is_dir { + // failed canonicalizing, so skip it + iterator.skip_current_dir(); + } + } + } + } + Ok(target_files) + } +} + +/// Collects module specifiers that satisfy the given predicate as a file path, by recursively walking `include`. +/// Specifiers that start with http and https are left intact. +/// Note: This ignores all .git and node_modules folders. +pub fn collect_specifiers( + include: Vec, + ignore: &[PathBuf], + predicate: impl Fn(&Path) -> bool, +) -> Result, AnyError> { + let mut prepared = vec![]; + let file_collector = FileCollector::new(predicate) + .add_ignore_paths(ignore) + .ignore_git_folder() + .ignore_node_modules(); + + let root_path = current_dir()?; + for path in include { + let lowercase_path = path.to_lowercase(); + if lowercase_path.starts_with("http://") + || lowercase_path.starts_with("https://") + { + let url = ModuleSpecifier::parse(&path)?; + prepared.push(url); + continue; + } + + let p = if lowercase_path.starts_with("file://") { + specifier_to_file_path(&ModuleSpecifier::parse(&path)?)? + } else { + root_path.join(path) + }; + let p = normalize_path(&p); + if p.is_dir() { + let test_files = file_collector.collect_files(&[p])?; + let mut test_files_as_urls = test_files + .iter() + .map(|f| ModuleSpecifier::from_file_path(f).unwrap()) + .collect::>(); + + test_files_as_urls.sort(); + prepared.extend(test_files_as_urls); + } else { + let url = ModuleSpecifier::from_file_path(p).unwrap(); + prepared.push(url); + } + } + + Ok(prepared) +} + +/// Asynchronously removes a directory and all its descendants, but does not error +/// when the directory does not exist. +pub async fn remove_dir_all_if_exists(path: &Path) -> std::io::Result<()> { + let result = tokio::fs::remove_dir_all(path).await; + match result { + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), + _ => result, + } +} + +/// Copies a directory to another directory. +/// +/// Note: Does not handle symlinks. +pub fn copy_dir_recursive(from: &Path, to: &Path) -> Result<(), AnyError> { + std::fs::create_dir_all(to) + .with_context(|| format!("Creating {}", to.display()))?; + let read_dir = std::fs::read_dir(from) + .with_context(|| format!("Reading {}", from.display()))?; + + for entry in read_dir { + let entry = entry?; + let file_type = entry.file_type()?; + let new_from = from.join(entry.file_name()); + let new_to = to.join(entry.file_name()); + + if file_type.is_dir() { + copy_dir_recursive(&new_from, &new_to).with_context(|| { + format!("Dir {} to {}", new_from.display(), new_to.display()) + })?; + } else if file_type.is_file() { + std::fs::copy(&new_from, &new_to).with_context(|| { + format!("Copying {} to {}", new_from.display(), new_to.display()) + })?; + } + } + + Ok(()) +} + +/// Hardlinks the files in one directory to another directory. +/// +/// Note: Does not handle symlinks. +pub fn hard_link_dir_recursive(from: &Path, to: &Path) -> Result<(), AnyError> { + std::fs::create_dir_all(to) + .with_context(|| format!("Creating {}", to.display()))?; + let read_dir = std::fs::read_dir(from) + .with_context(|| format!("Reading {}", from.display()))?; + + for entry in read_dir { + let entry = entry?; + let file_type = entry.file_type()?; + let new_from = from.join(entry.file_name()); + let new_to = to.join(entry.file_name()); + + if file_type.is_dir() { + hard_link_dir_recursive(&new_from, &new_to).with_context(|| { + format!("Dir {} to {}", new_from.display(), new_to.display()) + })?; + } else if file_type.is_file() { + // note: chance for race conditions here between attempting to create, + // then removing, then attempting to create. There doesn't seem to be + // a way to hard link with overwriting in Rust, but maybe there is some + // way with platform specific code. The workaround here is to handle + // scenarios where something else might create or remove files. + if let Err(err) = std::fs::hard_link(&new_from, &new_to) { + if err.kind() == ErrorKind::AlreadyExists { + if let Err(err) = std::fs::remove_file(&new_to) { + if err.kind() == ErrorKind::NotFound { + // Assume another process/thread created this hard link to the file we are wanting + // to remove then sleep a little bit to let the other process/thread move ahead + // faster to reduce contention. + std::thread::sleep(Duration::from_millis(10)); + } else { + return Err(err).with_context(|| { + format!( + "Removing file to hard link {} to {}", + new_from.display(), + new_to.display() + ) + }); + } + } + + // Always attempt to recreate the hardlink. In contention scenarios, the other process + // might have been killed or exited after removing the file, but before creating the hardlink + if let Err(err) = std::fs::hard_link(&new_from, &new_to) { + // Assume another process/thread created this hard link to the file we are wanting + // to now create then sleep a little bit to let the other process/thread move ahead + // faster to reduce contention. + if err.kind() == ErrorKind::AlreadyExists { + std::thread::sleep(Duration::from_millis(10)); + } else { + return Err(err).with_context(|| { + format!( + "Hard linking {} to {}", + new_from.display(), + new_to.display() + ) + }); + } + } + } else { + return Err(err).with_context(|| { + format!( + "Hard linking {} to {}", + new_from.display(), + new_to.display() + ) + }); + } + } + } + } + + Ok(()) +} + +pub fn symlink_dir(oldpath: &Path, newpath: &Path) -> Result<(), AnyError> { + let err_mapper = |err: Error| { + Error::new( + err.kind(), + format!( + "{}, symlink '{}' -> '{}'", + err, + oldpath.display(), + newpath.display() + ), + ) + }; + #[cfg(unix)] + { + use std::os::unix::fs::symlink; + symlink(oldpath, newpath).map_err(err_mapper)?; + } + #[cfg(not(unix))] + { + use std::os::windows::fs::symlink_dir; + symlink_dir(oldpath, newpath).map_err(err_mapper)?; + } + Ok(()) +} + +/// Gets the total size (in bytes) of a directory. +pub fn dir_size(path: &Path) -> std::io::Result { + let entries = std::fs::read_dir(path)?; + let mut total = 0; + for entry in entries { + let entry = entry?; + total += match entry.metadata()? { + data if data.is_dir() => dir_size(&entry.path())?, + data => data.len(), + }; + } + Ok(total) +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use test_util::TempDir; + + #[test] + fn resolve_from_cwd_child() { + let cwd = current_dir().unwrap(); + assert_eq!(resolve_from_cwd(Path::new("a")).unwrap(), cwd.join("a")); + } + + #[test] + fn resolve_from_cwd_dot() { + let cwd = current_dir().unwrap(); + assert_eq!(resolve_from_cwd(Path::new(".")).unwrap(), cwd); + } + + #[test] + fn resolve_from_cwd_parent() { + let cwd = current_dir().unwrap(); + assert_eq!(resolve_from_cwd(Path::new("a/..")).unwrap(), cwd); + } + + #[test] + fn test_normalize_path() { + assert_eq!(normalize_path(Path::new("a/../b")), PathBuf::from("b")); + assert_eq!(normalize_path(Path::new("a/./b/")), PathBuf::from("a/b/")); + assert_eq!( + normalize_path(Path::new("a/./b/../c")), + PathBuf::from("a/c") + ); + + if cfg!(windows) { + assert_eq!( + normalize_path(Path::new("C:\\a\\.\\b\\..\\c")), + PathBuf::from("C:\\a\\c") + ); + } + } + + // TODO: Get a good expected value here for Windows. + #[cfg(not(windows))] + #[test] + fn resolve_from_cwd_absolute() { + let expected = Path::new("/a"); + assert_eq!(resolve_from_cwd(expected).unwrap(), expected); + } + + #[test] + fn test_collect_files() { + fn create_files(dir_path: &Path, files: &[&str]) { + std::fs::create_dir(dir_path).expect("Failed to create directory"); + for f in files { + let path = dir_path.join(f); + std::fs::write(path, "").expect("Failed to create file"); + } + } + + // dir.ts + // ├── a.ts + // ├── b.js + // ├── child + // | ├── node_modules + // | | └── node_modules.js + // | ├── git + // | | └── git.js + // │ ├── e.mjs + // │ ├── f.mjsx + // │ ├── .foo.TS + // │ └── README.md + // ├── c.tsx + // ├── d.jsx + // └── ignore + // ├── g.d.ts + // └── .gitignore + + let t = TempDir::new(); + + let root_dir_path = t.path().join("dir.ts"); + let root_dir_files = ["a.ts", "b.js", "c.tsx", "d.jsx"]; + create_files(&root_dir_path, &root_dir_files); + + let child_dir_path = root_dir_path.join("child"); + let child_dir_files = ["e.mjs", "f.mjsx", ".foo.TS", "README.md"]; + create_files(&child_dir_path, &child_dir_files); + + t.create_dir_all("dir.ts/child/node_modules"); + t.write("dir.ts/child/node_modules/node_modules.js", ""); + t.create_dir_all("dir.ts/child/.git"); + t.write("dir.ts/child/.git/git.js", ""); + + let ignore_dir_path = root_dir_path.join("ignore"); + let ignore_dir_files = ["g.d.ts", ".gitignore"]; + create_files(&ignore_dir_path, &ignore_dir_files); + + let file_collector = FileCollector::new(|path| { + // exclude dotfiles + path + .file_name() + .and_then(|f| f.to_str()) + .map_or(false, |f| !f.starts_with('.')) + }) + .add_ignore_paths(&[ignore_dir_path]); + + let result = file_collector + .collect_files(&[root_dir_path.clone()]) + .unwrap(); + let expected = [ + "README.md", + "a.ts", + "b.js", + "c.tsx", + "d.jsx", + "e.mjs", + "f.mjsx", + "git.js", + "node_modules.js", + ]; + let mut file_names = result + .into_iter() + .map(|r| r.file_name().unwrap().to_string_lossy().to_string()) + .collect::>(); + file_names.sort(); + assert_eq!(file_names, expected); + + // test ignoring the .git and node_modules folder + let file_collector = + file_collector.ignore_git_folder().ignore_node_modules(); + let result = file_collector + .collect_files(&[root_dir_path.clone()]) + .unwrap(); + let expected = [ + "README.md", + "a.ts", + "b.js", + "c.tsx", + "d.jsx", + "e.mjs", + "f.mjsx", + ]; + let mut file_names = result + .into_iter() + .map(|r| r.file_name().unwrap().to_string_lossy().to_string()) + .collect::>(); + file_names.sort(); + assert_eq!(file_names, expected); + + // test opting out of ignoring by specifying the dir + let result = file_collector + .collect_files(&[ + root_dir_path.clone(), + root_dir_path.join("child/node_modules/"), + ]) + .unwrap(); + let expected = [ + "README.md", + "a.ts", + "b.js", + "c.tsx", + "d.jsx", + "e.mjs", + "f.mjsx", + "node_modules.js", + ]; + let mut file_names = result + .into_iter() + .map(|r| r.file_name().unwrap().to_string_lossy().to_string()) + .collect::>(); + file_names.sort(); + assert_eq!(file_names, expected); + } + + #[test] + fn test_collect_specifiers() { + fn create_files(dir_path: &Path, files: &[&str]) { + std::fs::create_dir(dir_path).expect("Failed to create directory"); + for f in files { + let path = dir_path.join(f); + std::fs::write(path, "").expect("Failed to create file"); + } + } + + // dir.ts + // ├── a.ts + // ├── b.js + // ├── child + // │ ├── e.mjs + // │ ├── f.mjsx + // │ ├── .foo.TS + // │ └── README.md + // ├── c.tsx + // ├── d.jsx + // └── ignore + // ├── g.d.ts + // └── .gitignore + + let t = TempDir::new(); + + let root_dir_path = t.path().join("dir.ts"); + let root_dir_files = ["a.ts", "b.js", "c.tsx", "d.jsx"]; + create_files(&root_dir_path, &root_dir_files); + + let child_dir_path = root_dir_path.join("child"); + let child_dir_files = ["e.mjs", "f.mjsx", ".foo.TS", "README.md"]; + create_files(&child_dir_path, &child_dir_files); + + let ignore_dir_path = root_dir_path.join("ignore"); + let ignore_dir_files = ["g.d.ts", ".gitignore"]; + create_files(&ignore_dir_path, &ignore_dir_files); + + let predicate = |path: &Path| { + // exclude dotfiles + path + .file_name() + .and_then(|f| f.to_str()) + .map_or(false, |f| !f.starts_with('.')) + }; + + let result = collect_specifiers( + vec![ + "http://localhost:8080".to_string(), + root_dir_path.to_str().unwrap().to_string(), + "https://localhost:8080".to_string(), + ], + &[ignore_dir_path], + predicate, + ) + .unwrap(); + + let root_dir_url = ModuleSpecifier::from_file_path( + canonicalize_path(&root_dir_path).unwrap(), + ) + .unwrap() + .to_string(); + let expected: Vec = [ + "http://localhost:8080", + &format!("{}/a.ts", root_dir_url), + &format!("{}/b.js", root_dir_url), + &format!("{}/c.tsx", root_dir_url), + &format!("{}/child/README.md", root_dir_url), + &format!("{}/child/e.mjs", root_dir_url), + &format!("{}/child/f.mjsx", root_dir_url), + &format!("{}/d.jsx", root_dir_url), + "https://localhost:8080", + ] + .iter() + .map(|f| ModuleSpecifier::parse(f).unwrap()) + .collect::>(); + + assert_eq!(result, expected); + + let scheme = if cfg!(target_os = "windows") { + "file:///" + } else { + "file://" + }; + let result = collect_specifiers( + vec![format!( + "{}{}", + scheme, + root_dir_path + .join("child") + .to_str() + .unwrap() + .replace('\\', "/") + )], + &[], + predicate, + ) + .unwrap(); + + let expected: Vec = [ + &format!("{}/child/README.md", root_dir_url), + &format!("{}/child/e.mjs", root_dir_url), + &format!("{}/child/f.mjsx", root_dir_url), + ] + .iter() + .map(|f| ModuleSpecifier::parse(f).unwrap()) + .collect::>(); + + assert_eq!(result, expected); + } + + #[cfg(windows)] + #[test] + fn test_strip_unc_prefix() { + run_test(r"C:\", r"C:\"); + run_test(r"C:\test\file.txt", r"C:\test\file.txt"); + + run_test(r"\\?\C:\", r"C:\"); + run_test(r"\\?\C:\test\file.txt", r"C:\test\file.txt"); + + run_test(r"\\.\C:\", r"\\.\C:\"); + run_test(r"\\.\C:\Test\file.txt", r"\\.\C:\Test\file.txt"); + + run_test(r"\\?\UNC\localhost\", r"\\localhost"); + run_test(r"\\?\UNC\localhost\c$\", r"\\localhost\c$"); + run_test( + r"\\?\UNC\localhost\c$\Windows\file.txt", + r"\\localhost\c$\Windows\file.txt", + ); + run_test(r"\\?\UNC\wsl$\deno.json", r"\\wsl$\deno.json"); + + run_test(r"\\?\server1", r"\\server1"); + run_test(r"\\?\server1\e$\", r"\\server1\e$\"); + run_test( + r"\\?\server1\e$\test\file.txt", + r"\\server1\e$\test\file.txt", + ); + + fn run_test(input: &str, expected: &str) { + assert_eq!( + strip_unc_prefix(PathBuf::from(input)), + PathBuf::from(expected) + ); + } + } +} diff --git a/cli/logger.rs b/cli/util/logger.rs similarity index 100% rename from cli/logger.rs rename to cli/util/logger.rs diff --git a/cli/util/mod.rs b/cli/util/mod.rs new file mode 100644 index 0000000000..176991d32c --- /dev/null +++ b/cli/util/mod.rs @@ -0,0 +1,14 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +// Note: Only add code in this folder that has no application specific logic +pub mod checksum; +pub mod diff; +pub mod display; +pub mod file_watcher; +pub mod fs; +pub mod logger; +pub mod path; +pub mod progress_bar; +pub mod text_encoding; +pub mod unix; +pub mod windows; diff --git a/cli/util/path.rs b/cli/util/path.rs new file mode 100644 index 0000000000..6df982f4ed --- /dev/null +++ b/cli/util/path.rs @@ -0,0 +1,452 @@ +use std::borrow::Cow; +use std::path::Path; +use std::path::PathBuf; + +use deno_ast::ModuleSpecifier; +use deno_core::error::uri_error; +use deno_core::error::AnyError; + +/// Checks if the path has extension Deno supports. +pub fn is_supported_ext(path: &Path) -> bool { + if let Some(ext) = get_extension(path) { + matches!( + ext.as_str(), + "ts" | "tsx" | "js" | "jsx" | "mjs" | "mts" | "cjs" | "cts" + ) + } else { + false + } +} + +/// Get the extension of a file in lowercase. +pub fn get_extension(file_path: &Path) -> Option { + return file_path + .extension() + .and_then(|e| e.to_str()) + .map(|e| e.to_lowercase()); +} + +/// Attempts to convert a specifier to a file path. By default, uses the Url +/// crate's `to_file_path()` method, but falls back to try and resolve unix-style +/// paths on Windows. +pub fn specifier_to_file_path( + specifier: &ModuleSpecifier, +) -> Result { + let result = if cfg!(windows) { + match specifier.to_file_path() { + Ok(path) => Ok(path), + Err(()) => { + // This might be a unix-style path which is used in the tests even on Windows. + // Attempt to see if we can convert it to a `PathBuf`. This code should be removed + // once/if https://github.com/servo/rust-url/issues/730 is implemented. + if specifier.scheme() == "file" + && specifier.host().is_none() + && specifier.port().is_none() + && specifier.path_segments().is_some() + { + let path_str = specifier.path(); + match String::from_utf8( + percent_encoding::percent_decode(path_str.as_bytes()).collect(), + ) { + Ok(path_str) => Ok(PathBuf::from(path_str)), + Err(_) => Err(()), + } + } else { + Err(()) + } + } + } + } else { + specifier.to_file_path() + }; + match result { + Ok(path) => Ok(path), + Err(()) => Err(uri_error(format!( + "Invalid file path.\n Specifier: {}", + specifier + ))), + } +} + +/// Ensures a specifier that will definitely be a directory has a trailing slash. +pub fn ensure_directory_specifier( + mut specifier: ModuleSpecifier, +) -> ModuleSpecifier { + let path = specifier.path(); + if !path.ends_with('/') { + let new_path = format!("{}/", path); + specifier.set_path(&new_path); + } + specifier +} + +/// Gets the parent of this module specifier. +pub fn specifier_parent(specifier: &ModuleSpecifier) -> ModuleSpecifier { + let mut specifier = specifier.clone(); + // don't use specifier.segments() because it will strip the leading slash + let mut segments = specifier.path().split('/').collect::>(); + if segments.iter().all(|s| s.is_empty()) { + return specifier; + } + if let Some(last) = segments.last() { + if last.is_empty() { + segments.pop(); + } + segments.pop(); + let new_path = format!("{}/", segments.join("/")); + specifier.set_path(&new_path); + } + specifier +} + +/// `from.make_relative(to)` but with fixes. +pub fn relative_specifier( + from: &ModuleSpecifier, + to: &ModuleSpecifier, +) -> Option { + let is_dir = to.path().ends_with('/'); + + if is_dir && from == to { + return Some("./".to_string()); + } + + // workaround using parent directory until https://github.com/servo/rust-url/pull/754 is merged + let from = if !from.path().ends_with('/') { + if let Some(end_slash) = from.path().rfind('/') { + let mut new_from = from.clone(); + new_from.set_path(&from.path()[..end_slash + 1]); + Cow::Owned(new_from) + } else { + Cow::Borrowed(from) + } + } else { + Cow::Borrowed(from) + }; + + // workaround for url crate not adding a trailing slash for a directory + // it seems to be fixed once a version greater than 2.2.2 is released + let mut text = from.make_relative(to)?; + if is_dir && !text.ends_with('/') && to.query().is_none() { + text.push('/'); + } + + Some(if text.starts_with("../") || text.starts_with("./") { + text + } else { + format!("./{}", text) + }) +} + +/// This function checks if input path has trailing slash or not. If input path +/// has trailing slash it will return true else it will return false. +pub fn path_has_trailing_slash(path: &Path) -> bool { + if let Some(path_str) = path.to_str() { + if cfg!(windows) { + path_str.ends_with('\\') + } else { + path_str.ends_with('/') + } + } else { + false + } +} + +/// Gets a path with the specified file stem suffix. +/// +/// Ex. `file.ts` with suffix `_2` returns `file_2.ts` +pub fn path_with_stem_suffix(path: &Path, suffix: &str) -> PathBuf { + if let Some(file_name) = path.file_name().map(|f| f.to_string_lossy()) { + if let Some(file_stem) = path.file_stem().map(|f| f.to_string_lossy()) { + if let Some(ext) = path.extension().map(|f| f.to_string_lossy()) { + return if file_stem.to_lowercase().ends_with(".d") { + path.with_file_name(format!( + "{}{}.{}.{}", + &file_stem[..file_stem.len() - ".d".len()], + suffix, + // maintain casing + &file_stem[file_stem.len() - "d".len()..], + ext + )) + } else { + path.with_file_name(format!("{}{}.{}", file_stem, suffix, ext)) + }; + } + } + + path.with_file_name(format!("{}{}", file_name, suffix)) + } else { + path.with_file_name(suffix) + } +} + +/// Gets if the provided character is not supported on all +/// kinds of file systems. +pub fn is_banned_path_char(c: char) -> bool { + matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*') +} + +/// Gets a safe local directory name for the provided url. +/// +/// For example: +/// https://deno.land:8080/path -> deno.land_8080/path +pub fn root_url_to_safe_local_dirname(root: &ModuleSpecifier) -> PathBuf { + fn sanitize_segment(text: &str) -> String { + text + .chars() + .map(|c| if is_banned_segment_char(c) { '_' } else { c }) + .collect() + } + + fn is_banned_segment_char(c: char) -> bool { + matches!(c, '/' | '\\') || is_banned_path_char(c) + } + + let mut result = String::new(); + if let Some(domain) = root.domain() { + result.push_str(&sanitize_segment(domain)); + } + if let Some(port) = root.port() { + if !result.is_empty() { + result.push('_'); + } + result.push_str(&port.to_string()); + } + let mut result = PathBuf::from(result); + if let Some(segments) = root.path_segments() { + for segment in segments.filter(|s| !s.is_empty()) { + result = result.join(sanitize_segment(segment)); + } + } + + result +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_is_supported_ext() { + assert!(!is_supported_ext(Path::new("tests/subdir/redirects"))); + assert!(!is_supported_ext(Path::new("README.md"))); + assert!(is_supported_ext(Path::new("lib/typescript.d.ts"))); + assert!(is_supported_ext(Path::new("testdata/run/001_hello.js"))); + assert!(is_supported_ext(Path::new("testdata/run/002_hello.ts"))); + assert!(is_supported_ext(Path::new("foo.jsx"))); + assert!(is_supported_ext(Path::new("foo.tsx"))); + assert!(is_supported_ext(Path::new("foo.TS"))); + assert!(is_supported_ext(Path::new("foo.TSX"))); + assert!(is_supported_ext(Path::new("foo.JS"))); + assert!(is_supported_ext(Path::new("foo.JSX"))); + assert!(is_supported_ext(Path::new("foo.mjs"))); + assert!(is_supported_ext(Path::new("foo.mts"))); + assert!(is_supported_ext(Path::new("foo.cjs"))); + assert!(is_supported_ext(Path::new("foo.cts"))); + assert!(!is_supported_ext(Path::new("foo.mjsx"))); + } + + #[test] + fn test_specifier_to_file_path() { + run_success_test("file:///", "/"); + run_success_test("file:///test", "/test"); + run_success_test("file:///dir/test/test.txt", "/dir/test/test.txt"); + run_success_test( + "file:///dir/test%20test/test.txt", + "/dir/test test/test.txt", + ); + + fn run_success_test(specifier: &str, expected_path: &str) { + let result = + specifier_to_file_path(&ModuleSpecifier::parse(specifier).unwrap()) + .unwrap(); + assert_eq!(result, PathBuf::from(expected_path)); + } + } + + #[test] + fn test_ensure_directory_specifier() { + run_test("file:///", "file:///"); + run_test("file:///test", "file:///test/"); + run_test("file:///test/", "file:///test/"); + run_test("file:///test/other", "file:///test/other/"); + run_test("file:///test/other/", "file:///test/other/"); + + fn run_test(specifier: &str, expected: &str) { + let result = + ensure_directory_specifier(ModuleSpecifier::parse(specifier).unwrap()); + assert_eq!(result.to_string(), expected); + } + } + + #[test] + fn test_specifier_parent() { + run_test("file:///", "file:///"); + run_test("file:///test", "file:///"); + run_test("file:///test/", "file:///"); + run_test("file:///test/other", "file:///test/"); + run_test("file:///test/other.txt", "file:///test/"); + run_test("file:///test/other/", "file:///test/"); + + fn run_test(specifier: &str, expected: &str) { + let result = + specifier_parent(&ModuleSpecifier::parse(specifier).unwrap()); + assert_eq!(result.to_string(), expected); + } + } + + #[test] + fn test_relative_specifier() { + let fixtures: Vec<(&str, &str, Option<&str>)> = vec![ + ("file:///from", "file:///to", Some("./to")), + ("file:///from", "file:///from/other", Some("./from/other")), + ("file:///from", "file:///from/other/", Some("./from/other/")), + ("file:///from", "file:///other/from", Some("./other/from")), + ("file:///from/", "file:///other/from", Some("../other/from")), + ("file:///from", "file:///other/from/", Some("./other/from/")), + ( + "file:///from", + "file:///to/other.txt", + Some("./to/other.txt"), + ), + ( + "file:///from/test", + "file:///to/other.txt", + Some("../to/other.txt"), + ), + ( + "file:///from/other.txt", + "file:///to/other.txt", + Some("../to/other.txt"), + ), + ( + "https://deno.land/x/a/b/d.ts", + "https://deno.land/x/a/b/c.ts", + Some("./c.ts"), + ), + ( + "https://deno.land/x/a/b/d.ts", + "https://deno.land/x/a/c.ts", + Some("../c.ts"), + ), + ( + "https://deno.land/x/a/b/d.ts", + "https://deno.land/x/a/b/c/d.ts", + Some("./c/d.ts"), + ), + ( + "https://deno.land/x/a/b/c/", + "https://deno.land/x/a/b/c/d.ts", + Some("./d.ts"), + ), + ( + "https://deno.land/x/a/b/c/", + "https://deno.land/x/a/b/c/d/e.ts", + Some("./d/e.ts"), + ), + ( + "https://deno.land/x/a/b/c/f.ts", + "https://deno.land/x/a/b/c/d/e.ts", + Some("./d/e.ts"), + ), + ( + "https://deno.land/x/a/b/d.ts", + "https://deno.land/x/a/c.ts?foo=bar", + Some("../c.ts?foo=bar"), + ), + ( + "https://deno.land/x/a/b/d.ts?foo=bar", + "https://deno.land/x/a/b/c.ts", + Some("./c.ts"), + ), + ("file:///a/b/d.ts", "file:///a/b/c.ts", Some("./c.ts")), + ("https://deno.land/x/a/b/c.ts", "file:///a/b/c.ts", None), + ( + "https://deno.land/", + "https://deno.land/x/a/b/c.ts", + Some("./x/a/b/c.ts"), + ), + ( + "https://deno.land/x/d/e/f.ts", + "https://deno.land/x/a/b/c.ts", + Some("../../a/b/c.ts"), + ), + ]; + for (from_str, to_str, expected) in fixtures { + let from = ModuleSpecifier::parse(from_str).unwrap(); + let to = ModuleSpecifier::parse(to_str).unwrap(); + let actual = relative_specifier(&from, &to); + assert_eq!( + actual.as_deref(), + expected, + "from: \"{}\" to: \"{}\"", + from_str, + to_str + ); + } + } + + #[test] + fn test_path_has_trailing_slash() { + #[cfg(not(windows))] + { + run_test("/Users/johndoe/Desktop/deno-project/target/", true); + run_test(r"/Users/johndoe/deno-project/target//", true); + run_test("/Users/johndoe/Desktop/deno-project", false); + run_test(r"/Users/johndoe/deno-project\", false); + } + + #[cfg(windows)] + { + run_test(r"C:\test\deno-project\", true); + run_test(r"C:\test\deno-project\\", true); + run_test(r"C:\test\file.txt", false); + run_test(r"C:\test\file.txt/", false); + } + + fn run_test(path_str: &str, expected: bool) { + let path = Path::new(path_str); + let result = path_has_trailing_slash(path); + assert_eq!(result, expected); + } + } + + #[test] + fn test_path_with_stem_suffix() { + assert_eq!( + path_with_stem_suffix(&PathBuf::from("/"), "_2"), + PathBuf::from("/_2") + ); + assert_eq!( + path_with_stem_suffix(&PathBuf::from("/test"), "_2"), + PathBuf::from("/test_2") + ); + assert_eq!( + path_with_stem_suffix(&PathBuf::from("/test.txt"), "_2"), + PathBuf::from("/test_2.txt") + ); + assert_eq!( + path_with_stem_suffix(&PathBuf::from("/test/subdir"), "_2"), + PathBuf::from("/test/subdir_2") + ); + assert_eq!( + path_with_stem_suffix(&PathBuf::from("/test/subdir.other.txt"), "_2"), + PathBuf::from("/test/subdir.other_2.txt") + ); + assert_eq!( + path_with_stem_suffix(&PathBuf::from("/test.d.ts"), "_2"), + PathBuf::from("/test_2.d.ts") + ); + assert_eq!( + path_with_stem_suffix(&PathBuf::from("/test.D.TS"), "_2"), + PathBuf::from("/test_2.D.TS") + ); + assert_eq!( + path_with_stem_suffix(&PathBuf::from("/test.d.mts"), "_2"), + PathBuf::from("/test_2.d.mts") + ); + assert_eq!( + path_with_stem_suffix(&PathBuf::from("/test.d.cts"), "_2"), + PathBuf::from("/test_2.d.cts") + ); + } +} diff --git a/cli/progress_bar.rs b/cli/util/progress_bar.rs similarity index 100% rename from cli/progress_bar.rs rename to cli/util/progress_bar.rs diff --git a/cli/text_encoding.rs b/cli/util/text_encoding.rs similarity index 100% rename from cli/text_encoding.rs rename to cli/util/text_encoding.rs diff --git a/cli/unix_util.rs b/cli/util/unix.rs similarity index 100% rename from cli/unix_util.rs rename to cli/util/unix.rs diff --git a/cli/windows_util.rs b/cli/util/windows.rs similarity index 100% rename from cli/windows_util.rs rename to cli/util/windows.rs diff --git a/cli/worker.rs b/cli/worker.rs index 0e9e1d1d73..9a56838a1b 100644 --- a/cli/worker.rs +++ b/cli/worker.rs @@ -24,7 +24,6 @@ use deno_runtime::worker::WorkerOptions; use deno_runtime::BootstrapOptions; use crate::args::DenoSubcommand; -use crate::checksum; use crate::errors; use crate::module_loader::CliModuleLoader; use crate::node; @@ -34,6 +33,7 @@ use crate::proc_state::ProcState; use crate::tools; use crate::tools::coverage::CoverageCollector; use crate::tools::test::TestMode; +use crate::util::checksum; use crate::version; pub struct CliMainWorker { @@ -70,6 +70,7 @@ impl CliMainWorker { &mut self.worker.js_runtime, &self.main_module.to_file_path().unwrap().to_string_lossy(), true, + self.ps.options.inspect_brk().is_some(), )?; } else { self.execute_main_module_possibly_with_npm().await?; diff --git a/core/01_core.js b/core/01_core.js index 5df11c382c..02150674e0 100644 --- a/core/01_core.js +++ b/core/01_core.js @@ -187,8 +187,8 @@ // Rethrow the error throw err; } - handleOpCallTracing("${name}", id, promise); - promise[promiseIdSymbol] = id; + promise = handleOpCallTracing("${name}", id, promise); + promise[promiseIdSymbol] = id; return promise; } `, @@ -218,10 +218,12 @@ if (opCallTracingEnabled) { const stack = StringPrototypeSlice(new Error().stack, 6); MapPrototypeSet(opCallTraces, promiseId, { opName, stack }); - p = PromisePrototypeFinally( + return PromisePrototypeFinally( p, () => MapPrototypeDelete(opCallTraces, promiseId), ); + } else { + return p; } } diff --git a/core/Cargo.toml b/core/Cargo.toml index 773c83980a..b3c97ce2b2 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_core" -version = "0.161.0" +version = "0.162.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/core/error.rs b/core/error.rs index d71da31641..fb9bdf8e40 100644 --- a/core/error.rs +++ b/core/error.rs @@ -207,6 +207,84 @@ impl JsError { Self::inner_from_v8_exception(scope, exception, Default::default()) } + pub fn from_v8_message<'a>( + scope: &'a mut v8::HandleScope, + msg: v8::Local<'a, v8::Message>, + ) -> Self { + // Create a new HandleScope because we're creating a lot of new local + // handles below. + let scope = &mut v8::HandleScope::new(scope); + + let exception_message = msg.get(scope).to_rust_string_lossy(scope); + let state_rc = JsRuntime::state(scope); + + // Convert them into Vec + let mut frames: Vec = vec![]; + + let mut source_line = None; + let mut source_line_frame_index = None; + { + let state = &mut *state_rc.borrow_mut(); + + let script_resource_name = msg + .get_script_resource_name(scope) + .and_then(|v| v8::Local::::try_from(v).ok()) + .map(|v| v.to_rust_string_lossy(scope)); + let line_number: Option = + msg.get_line_number(scope).and_then(|v| v.try_into().ok()); + let column_number: Option = msg.get_start_column().try_into().ok(); + if let (Some(f), Some(l), Some(c)) = + (script_resource_name, line_number, column_number) + { + // V8's column numbers are 0-based, we want 1-based. + let c = c + 1; + if let Some(source_map_getter) = &state.source_map_getter { + let (f, l, c) = apply_source_map( + f, + l, + c, + &mut state.source_map_cache, + source_map_getter.as_ref(), + ); + frames = vec![JsStackFrame::from_location(Some(f), Some(l), Some(c))]; + } else { + frames = vec![JsStackFrame::from_location(Some(f), Some(l), Some(c))]; + } + } + + if let Some(source_map_getter) = &state.source_map_getter { + for (i, frame) in frames.iter().enumerate() { + if let (Some(file_name), Some(line_number)) = + (&frame.file_name, frame.line_number) + { + if !file_name.trim_start_matches('[').starts_with("deno:") { + source_line = get_source_line( + file_name, + line_number, + &mut state.source_map_cache, + source_map_getter.as_ref(), + ); + source_line_frame_index = Some(i); + break; + } + } + } + } + } + + Self { + name: None, + message: None, + exception_message, + cause: None, + source_line, + source_line_frame_index, + frames, + stack: None, + aggregated: None, + } + } + fn inner_from_v8_exception<'a>( scope: &'a mut v8::HandleScope, exception: v8::Local<'a, v8::Value>, @@ -330,7 +408,6 @@ impl JsError { (&frame.file_name, frame.line_number) { if !file_name.trim_start_matches('[').starts_with("deno:") { - // Source lookup expects a 0-based line number, ours are 1-based. source_line = get_source_line( file_name, line_number, diff --git a/core/examples/wasm.js b/core/examples/wasm.js new file mode 100644 index 0000000000..69e475639f --- /dev/null +++ b/core/examples/wasm.js @@ -0,0 +1,28 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +// asc wasm.ts --exportStart --initialMemory 6400 -O -o wasm.wasm +// deno-fmt-ignore +const bytes = new Uint8Array([ + 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 2, + 15, 1, 3, 111, 112, 115, 7, 111, 112, 95, 119, 97, 115, 109, 0, + 0, 3, 3, 2, 0, 0, 5, 4, 1, 0, 128, 50, 7, 36, 4, + 7, 111, 112, 95, 119, 97, 115, 109, 0, 0, 4, 99, 97, 108, 108, + 0, 1, 6, 109, 101, 109, 111, 114, 121, 2, 0, 6, 95, 115, 116, + 97, 114, 116, 0, 2, 10, 10, 2, 4, 0, 16, 0, 11, 3, 0, + 1, 11 + ]); + +const { ops } = Deno.core; + +const module = new WebAssembly.Module(bytes); +const instance = new WebAssembly.Instance(module, { ops }); +ops.op_set_wasm_mem(instance.exports.memory); + +instance.exports.call(); + +const memory = instance.exports.memory; +const view = new Uint8Array(memory.buffer); + +if (view[0] !== 69) { + throw new Error("Expected first byte to be 69"); +} diff --git a/core/examples/wasm.rs b/core/examples/wasm.rs new file mode 100644 index 0000000000..ef68d8aa44 --- /dev/null +++ b/core/examples/wasm.rs @@ -0,0 +1,67 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +use deno_core::op; +use deno_core::Extension; +use deno_core::JsRuntime; +use deno_core::RuntimeOptions; +use std::mem::transmute; +use std::ptr::NonNull; + +// This is a hack to make the `#[op]` macro work with +// deno_core examples. +// You can remove this: + +use deno_core::*; + +struct WasmMemory(NonNull); + +fn wasm_memory_unchecked(state: &mut OpState) -> &mut [u8] { + let WasmMemory(global) = state.borrow::(); + // SAFETY: `v8::Local` is always non-null pointer; the `HandleScope` is + // already on the stack, but we don't have access to it. + let memory_object = unsafe { + transmute::, v8::Local>( + *global, + ) + }; + let backing_store = memory_object.buffer().get_backing_store(); + let ptr = backing_store.data().unwrap().as_ptr() as *mut u8; + let len = backing_store.byte_length(); + // SAFETY: `ptr` is a valid pointer to `len` bytes. + unsafe { std::slice::from_raw_parts_mut(ptr, len) } +} + +#[op(wasm)] +fn op_wasm(state: &mut OpState, memory: Option<&mut [u8]>) { + let memory = memory.unwrap_or_else(|| wasm_memory_unchecked(state)); + memory[0] = 69; +} + +#[op(v8)] +fn op_set_wasm_mem( + scope: &mut v8::HandleScope, + state: &mut OpState, + memory: serde_v8::Value, +) { + let memory = + v8::Local::::try_from(memory.v8_value).unwrap(); + let global = v8::Global::new(scope, memory); + state.put(WasmMemory(global.into_raw())); +} + +fn main() { + // Build a deno_core::Extension providing custom ops + let ext = Extension::builder() + .ops(vec![op_wasm::decl(), op_set_wasm_mem::decl()]) + .build(); + + // Initialize a runtime instance + let mut runtime = JsRuntime::new(RuntimeOptions { + extensions: vec![ext], + ..Default::default() + }); + + runtime + .execute_script("", include_str!("wasm.js")) + .unwrap(); +} diff --git a/core/examples/wasm.ts b/core/examples/wasm.ts new file mode 100644 index 0000000000..cdb9cf78cf --- /dev/null +++ b/core/examples/wasm.ts @@ -0,0 +1,7 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +export declare function op_wasm(): void; + +export function call(): void { + op_wasm(); +} diff --git a/core/inspector.rs b/core/inspector.rs index b1047d421d..8a91360919 100644 --- a/core/inspector.rs +++ b/core/inspector.rs @@ -35,6 +35,7 @@ use std::ptr::NonNull; use std::rc::Rc; use std::sync::Arc; use std::thread; +use v8::HandleScope; pub enum InspectorMsgKind { Notification, @@ -150,6 +151,7 @@ impl JsRuntimeInspector { pub fn new( isolate: &mut v8::OwnedIsolate, context: v8::Global, + is_main: bool, ) -> Rc> { let scope = &mut v8::HandleScope::new(isolate); @@ -183,12 +185,26 @@ impl JsRuntimeInspector { // Tell the inspector about the global context. let context = v8::Local::new(scope, context); let context_name = v8::inspector::StringView::from(&b"global context"[..]); + // NOTE(bartlomieju): this is what Node.js does and it turns out some + // debuggers (like VSCode) rely on this information to disconnect after + // program completes + let aux_data = if is_main { + r#"{"isDefault": true}"# + } else { + r#"{"isDefault": false}"# + }; + let aux_data_view = v8::inspector::StringView::from(aux_data.as_bytes()); self_ .v8_inspector .borrow_mut() .as_mut() .unwrap() - .context_created(context, Self::CONTEXT_GROUP_ID, context_name); + .context_created( + context, + Self::CONTEXT_GROUP_ID, + context_name, + aux_data_view, + ); // Poll the session handler so we will get notified whenever there is // new incoming debugger activity. @@ -198,10 +214,28 @@ impl JsRuntimeInspector { self__ } + pub fn context_destroyed( + &mut self, + scope: &mut HandleScope, + context: v8::Global, + ) { + let context = v8::Local::new(scope, context); + self + .v8_inspector + .borrow_mut() + .as_mut() + .unwrap() + .context_destroyed(context); + } + pub fn has_active_sessions(&self) -> bool { self.sessions.borrow().has_active_sessions() } + pub fn has_blocking_sessions(&self) -> bool { + self.sessions.borrow().has_blocking_sessions() + } + fn poll_sessions( &self, mut invoker_cx: Option<&mut Context>, @@ -247,8 +281,11 @@ impl JsRuntimeInspector { // Accept new connections. let poll_result = sessions.session_rx.poll_next_unpin(cx); if let Poll::Ready(Some(session_proxy)) = poll_result { - let session = - InspectorSession::new(sessions.v8_inspector.clone(), session_proxy); + let session = InspectorSession::new( + sessions.v8_inspector.clone(), + session_proxy, + false, + ); let prev = sessions.handshake.replace(session); assert!(prev.is_none()); } @@ -363,7 +400,7 @@ impl JsRuntimeInspector { // InspectorSessions for a local session is added directly to the "established" // sessions, so it doesn't need to go through the session sender. let inspector_session = - InspectorSession::new(self.v8_inspector.clone(), proxy); + InspectorSession::new(self.v8_inspector.clone(), proxy, true); self .sessions .borrow_mut() @@ -417,6 +454,10 @@ impl SessionContainer { !self.established.is_empty() || self.handshake.is_some() } + fn has_blocking_sessions(&self) -> bool { + self.established.iter().any(|s| s.blocking) + } + /// A temporary placeholder that should be used before actual /// instance of V8Inspector is created. It's used in favor /// of `Default` implementation to signal that it's not meant @@ -513,6 +554,9 @@ struct InspectorSession { v8_channel: v8::inspector::ChannelBase, v8_session: v8::UniqueRef, proxy: InspectorSessionProxy, + // Describes if session should keep event loop alive, eg. a local REPL + // session should keep event loop alive, but a Websocket session shouldn't. + blocking: bool, } impl InspectorSession { @@ -521,6 +565,7 @@ impl InspectorSession { pub fn new( v8_inspector_rc: Rc>>, session_proxy: InspectorSessionProxy, + blocking: bool, ) -> Box { new_box_with(move |self_ptr| { let v8_channel = v8::inspector::ChannelBase::new::(); @@ -541,6 +586,7 @@ impl InspectorSession { v8_channel, v8_session, proxy: session_proxy, + blocking, } }) } diff --git a/core/modules.rs b/core/modules.rs index 8d0ae97334..1041f44f86 100644 --- a/core/modules.rs +++ b/core/modules.rs @@ -754,8 +754,8 @@ pub(crate) enum ModuleError { pub(crate) struct ModuleMap { // Handling of specifiers and v8 objects ids_by_handle: HashMap, ModuleId>, - handles_by_id: HashMap>, - info: HashMap, + pub handles_by_id: HashMap>, + pub info: HashMap, by_name: HashMap<(String, AssertedModuleType), SymbolicModule>, next_module_id: ModuleId, next_load_id: ModuleLoadId, diff --git a/core/ops_builtin.rs b/core/ops_builtin.rs index 6374e9951e..858ce97bd8 100644 --- a/core/ops_builtin.rs +++ b/core/ops_builtin.rs @@ -107,7 +107,7 @@ pub fn op_metrics(state: &mut OpState) -> (OpMetrics, Vec) { /// Builtin utility to print to stdout/stderr #[op] -pub fn op_print(msg: String, is_err: bool) -> Result<(), Error> { +pub fn op_print(msg: &str, is_err: bool) -> Result<(), Error> { if is_err { stderr().write_all(msg.as_bytes())?; stderr().flush().unwrap(); @@ -152,12 +152,12 @@ pub fn op_wasm_streaming_feed( pub fn op_wasm_streaming_set_url( state: &mut OpState, rid: ResourceId, - url: String, + url: &str, ) -> Result<(), Error> { let wasm_streaming = state.resource_table.get::(rid)?; - wasm_streaming.0.borrow_mut().set_url(&url); + wasm_streaming.0.borrow_mut().set_url(url); Ok(()) } diff --git a/core/ops_builtin_v8.rs b/core/ops_builtin_v8.rs index c72e114bd5..5f4f875ee6 100644 --- a/core/ops_builtin_v8.rs +++ b/core/ops_builtin_v8.rs @@ -472,7 +472,7 @@ fn op_serialize( } let backing_store = buf.get_backing_store(); - buf.detach(v8::undefined(scope).into()); + buf.detach(None); let id = shared_array_buffer_store.insert(backing_store); value_serializer.transfer_array_buffer(id, buf); let id = v8::Number::new(scope, id as f64).into(); @@ -770,12 +770,13 @@ fn op_dispatch_exception( scope.terminate_execution(); return; } - match state.inspector().try_borrow() { - Ok(inspector) if !inspector.has_active_sessions() => { - scope.terminate_execution(); - } + + // FIXME(bartlomieju): I'm not sure if this assumption is valid... Maybe when + // inspector is polling on pause? + if state.inspector().try_borrow().is_ok() { + scope.terminate_execution(); + } else { // If the inspector is borrowed at this time, assume an inspector is active. - _ => {} } } diff --git a/core/runtime.rs b/core/runtime.rs index b1ce148832..7ce9d3d09f 100644 --- a/core/runtime.rs +++ b/core/runtime.rs @@ -87,7 +87,10 @@ pub struct JsRuntime { built_from_snapshot: bool, allocations: IsolateAllocations, extensions: Vec, + extensions_with_js: Vec, event_loop_middlewares: Vec>, + // Marks if this is considered the top-level runtime. Used only be inspector. + is_main: bool, } pub(crate) struct DynImportModEvaluate { @@ -238,10 +241,23 @@ pub struct RuntimeOptions { /// executed tries to load modules. pub module_loader: Option>, - /// JsRuntime extensions, not to be confused with ES modules - /// these are sets of ops and other JS code to be initialized. + /// JsRuntime extensions, not to be confused with ES modules. + /// Only ops registered by extensions will be initialized. If you need + /// to execute JS code from extensions, use `extensions_with_js` options + /// instead. pub extensions: Vec, + /// JsRuntime extensions, not to be confused with ES modules. + /// Ops registered by extensions will be initialized and JS code will be + /// executed. If you don't need to execute JS code from extensions, use + /// `extensions` option instead. + /// + /// This is useful when creating snapshots, in such case you would pass + /// extensions using `extensions_with_js`, later when creating a runtime + /// from the snapshot, you would pass these extensions using `extensions` + /// option. + pub extensions_with_js: Vec, + /// V8 snapshot that should be loaded on startup. /// /// Currently can't be used with `will_snapshot`. @@ -274,7 +290,13 @@ pub struct RuntimeOptions { /// [CompiledWasmModuleStore]. If no [CompiledWasmModuleStore] is specified, /// `WebAssembly.Module` objects cannot be serialized. pub compiled_wasm_module_store: Option, + + /// Start inspector instance to allow debuggers to connect. pub inspector: bool, + + /// Describe if this is the main runtime instance, used by debuggers in some + /// situation - like disconnecting when program finishes running. + pub is_main: bool, } #[derive(Copy, Clone, PartialEq, Eq)] @@ -331,11 +353,20 @@ impl JsRuntime { let has_startup_snapshot = options.startup_snapshot.is_some(); // Add builtins extension - options - .extensions - .insert(0, crate::ops_builtin::init_builtins()); + if !has_startup_snapshot { + options + .extensions_with_js + .insert(0, crate::ops_builtin::init_builtins()); + } else { + options + .extensions + .insert(0, crate::ops_builtin::init_builtins()); + } - let ops = Self::collect_ops(&mut options.extensions); + let ops = Self::collect_ops( + &mut options.extensions, + &mut options.extensions_with_js, + ); let mut op_state = OpState::new(ops.len()); if let Some(get_error_class_fn) = options.get_error_class_fn { @@ -498,6 +529,7 @@ impl JsRuntime { Some(JsRuntimeInspector::new( &mut isolate, global_context.clone(), + options.is_main, )) } else { None @@ -530,19 +562,17 @@ impl JsRuntime { allocations: IsolateAllocations::default(), event_loop_middlewares: Vec::with_capacity(options.extensions.len()), extensions: options.extensions, + extensions_with_js: options.extensions_with_js, state: state_rc, module_map: Some(module_map_rc), + is_main: options.is_main, }; // Init resources and ops before extensions to make sure they are // available during the initialization process. js_runtime.init_extension_ops().unwrap(); - // TODO(@AaronO): diff extensions inited in snapshot and those provided - // for now we assume that snapshot and extensions always match - if !has_startup_snapshot { - let realm = js_runtime.global_realm(); - js_runtime.init_extension_js(&realm).unwrap(); - } + let realm = js_runtime.global_realm(); + js_runtime.init_extension_js(&realm).unwrap(); // Init callbacks (opresolve) js_runtime.init_cbs(); @@ -672,7 +702,8 @@ impl JsRuntime { /// Initializes JS of provided Extensions in the given realm fn init_extension_js(&mut self, realm: &JsRealm) -> Result<(), Error> { // Take extensions to avoid double-borrow - let mut extensions: Vec = std::mem::take(&mut self.extensions); + let mut extensions: Vec = + std::mem::take(&mut self.extensions_with_js); for m in extensions.iter_mut() { let js_files = m.init_js(); for (filename, source) in js_files { @@ -681,15 +712,22 @@ impl JsRuntime { } } // Restore extensions - self.extensions = extensions; + self.extensions_with_js = extensions; Ok(()) } /// Collects ops from extensions & applies middleware - fn collect_ops(extensions: &mut [Extension]) -> Vec { + fn collect_ops( + extensions: &mut [Extension], + extensions_with_js: &mut [Extension], + ) -> Vec { + let mut exts = vec![]; + exts.extend(extensions); + exts.extend(extensions_with_js); + // Middleware - let middleware: Vec> = extensions + let middleware: Vec> = exts .iter_mut() .filter_map(|e| e.init_middleware()) .collect(); @@ -698,7 +736,7 @@ impl JsRuntime { let macroware = move |d| middleware.iter().fold(d, |d, m| m(d)); // Flatten ops, apply middlware & override disabled ops - extensions + exts .iter_mut() .filter_map(|e| e.init_ops()) .flatten() @@ -723,22 +761,41 @@ impl JsRuntime { fn init_extension_ops(&mut self) -> Result<(), Error> { let op_state = self.op_state(); // Take extensions to avoid double-borrow - let mut extensions: Vec = std::mem::take(&mut self.extensions); + { + let mut extensions: Vec = std::mem::take(&mut self.extensions); - // Setup state - for e in extensions.iter_mut() { - // ops are already registered during in bindings::initialize_context(); - e.init_state(&mut op_state.borrow_mut())?; + // Setup state + for e in extensions.iter_mut() { + // ops are already registered during in bindings::initialize_context(); + e.init_state(&mut op_state.borrow_mut())?; - // Setup event-loop middleware - if let Some(middleware) = e.init_event_loop_middleware() { - self.event_loop_middlewares.push(middleware); + // Setup event-loop middleware + if let Some(middleware) = e.init_event_loop_middleware() { + self.event_loop_middlewares.push(middleware); + } } + + // Restore extensions + self.extensions = extensions; } + { + let mut extensions: Vec = + std::mem::take(&mut self.extensions_with_js); - // Restore extensions - self.extensions = extensions; + // Setup state + for e in extensions.iter_mut() { + // ops are already registered during in bindings::initialize_context(); + e.init_state(&mut op_state.borrow_mut())?; + // Setup event-loop middleware + if let Some(middleware) = e.init_event_loop_middleware() { + self.event_loop_middlewares.push(middleware); + } + } + + // Restore extensions + self.extensions_with_js = extensions; + } Ok(()) } @@ -949,6 +1006,7 @@ impl JsRuntime { state.inspector = Some(JsRuntimeInspector::new( self.v8_isolate.as_mut().unwrap(), state.global_realm.clone().unwrap().0, + self.is_main, )); } @@ -1088,9 +1146,21 @@ impl JsRuntime { let pending_state = self.event_loop_pending_state(); if !pending_state.is_pending() && !maybe_scheduling { if has_inspector { - let inspector_has_active_sessions = - self.inspector().borrow_mut().has_active_sessions(); - if wait_for_inspector && inspector_has_active_sessions { + let inspector = self.inspector(); + let has_active_sessions = inspector.borrow().has_active_sessions(); + let has_blocking_sessions = inspector.borrow().has_blocking_sessions(); + + if wait_for_inspector && has_active_sessions { + // If there are no blocking sessions (eg. REPL) we can now notify + // debugger that the program has finished running and we're ready + // to exit the process once debugger disconnects. + if !has_blocking_sessions { + let context = self.global_context(); + let scope = &mut self.handle_scope(); + inspector.borrow_mut().context_destroyed(scope, context); + println!("Program finished. Waiting for inspector to disconnect to exit the process..."); + } + return Poll::Pending; } } @@ -1098,7 +1168,7 @@ impl JsRuntime { return Poll::Ready(Ok(())); } - let mut state = self.state.borrow_mut(); + let state = self.state.borrow(); // Check if more async ops have been dispatched // during this turn of event loop. @@ -1115,6 +1185,8 @@ impl JsRuntime { state.waker.wake(); } + drop(state); + if pending_state.has_pending_module_evaluation { if pending_state.has_pending_refed_ops || pending_state.has_pending_dyn_imports @@ -1125,8 +1197,16 @@ impl JsRuntime { { // pass, will be polled again } else { - let msg = "Module evaluation is still pending but there are no pending ops or dynamic imports. This situation is often caused by unresolved promises."; - return Poll::Ready(Err(generic_error(msg))); + let scope = &mut self.handle_scope(); + let messages = find_stalled_top_level_await(scope); + // We are gonna print only a single message to provide a nice formatting + // with source line of offending promise shown. Once user fixed it, then + // they will get another error message for the next promise (but this + // situation is gonna be very rare, if ever happening). + assert!(!messages.is_empty()); + let msg = v8::Local::new(scope, messages[0].clone()); + let js_error = JsError::from_v8_message(scope, msg); + return Poll::Ready(Err(js_error.into())); } } @@ -1137,19 +1217,19 @@ impl JsRuntime { || pending_state.has_tick_scheduled { // pass, will be polled again - } else if state.dyn_module_evaluate_idle_counter >= 1 { - let mut msg = "Dynamically imported module evaluation is still pending but there are no pending ops. This situation is often caused by unresolved promises. -Pending dynamic modules:\n".to_string(); - let module_map = self.module_map.as_mut().unwrap().borrow_mut(); - for pending_evaluate in &state.pending_dyn_mod_evaluate { - let module_info = module_map - .get_info_by_id(&pending_evaluate.module_id) - .unwrap(); - msg.push_str("- "); - msg.push_str(module_info.name.as_str()); - } - return Poll::Ready(Err(generic_error(msg))); + } else if self.state.borrow().dyn_module_evaluate_idle_counter >= 1 { + let scope = &mut self.handle_scope(); + let messages = find_stalled_top_level_await(scope); + // We are gonna print only a single message to provide a nice formatting + // with source line of offending promise shown. Once user fixed it, then + // they will get another error message for the next promise (but this + // situation is gonna be very rare, if ever happening). + assert!(!messages.is_empty()); + let msg = v8::Local::new(scope, messages[0].clone()); + let js_error = JsError::from_v8_message(scope, msg); + return Poll::Ready(Err(js_error.into())); } else { + let mut state = self.state.borrow_mut(); // Delay the above error by one spin of the event loop. A dynamic import // evaluation may complete during this, in which case the counter will // reset. @@ -1199,6 +1279,59 @@ Pending dynamic modules:\n".to_string(); } } +fn get_stalled_top_level_await_message_for_module( + scope: &mut v8::HandleScope, + module_id: ModuleId, +) -> Vec> { + let module_map = JsRuntime::module_map(scope); + let module_map = module_map.borrow(); + let module_handle = module_map.handles_by_id.get(&module_id).unwrap(); + + let module = v8::Local::new(scope, module_handle); + let stalled = module.get_stalled_top_level_await_message(scope); + let mut messages = vec![]; + for (_, message) in stalled { + messages.push(v8::Global::new(scope, message)); + } + messages +} + +fn find_stalled_top_level_await( + scope: &mut v8::HandleScope, +) -> Vec> { + let module_map = JsRuntime::module_map(scope); + let module_map = module_map.borrow(); + + // First check if that's root module + let root_module_id = module_map + .info + .values() + .filter(|m| m.main) + .map(|m| m.id) + .next(); + + if let Some(root_module_id) = root_module_id { + let messages = + get_stalled_top_level_await_message_for_module(scope, root_module_id); + if !messages.is_empty() { + return messages; + } + } + + // It wasn't a top module, so iterate over all modules and try to find + // any with stalled top level await + let module_ids = module_map.handles_by_id.keys().copied().collect::>(); + for module_id in module_ids { + let messages = + get_stalled_top_level_await_message_for_module(scope, module_id); + if !messages.is_empty() { + return messages; + } + } + + unreachable!() +} + #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) struct EventLoopPendingState { has_pending_refed_ops: bool, diff --git a/core/snapshot_util.rs b/core/snapshot_util.rs index b408bad564..bacc0c6aeb 100644 --- a/core/snapshot_util.rs +++ b/core/snapshot_util.rs @@ -12,6 +12,7 @@ pub struct CreateSnapshotOptions { pub snapshot_path: PathBuf, pub startup_snapshot: Option, pub extensions: Vec, + pub extensions_with_js: Vec, pub additional_files: Vec, pub compression_cb: Option>, } @@ -21,6 +22,7 @@ pub fn create_snapshot(create_snapshot_options: CreateSnapshotOptions) { will_snapshot: true, startup_snapshot: create_snapshot_options.startup_snapshot, extensions: create_snapshot_options.extensions, + extensions_with_js: create_snapshot_options.extensions_with_js, ..Default::default() }); diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 9c52673a93..0000000000 --- a/docs/README.md +++ /dev/null @@ -1,3 +0,0 @@ -Documentation is available at: https://deno.land/manual - -Documentation repository is at: https://github.com/denoland/manual diff --git a/ext/broadcast_channel/Cargo.toml b/ext/broadcast_channel/Cargo.toml index da03481425..00c6c8a3c9 100644 --- a/ext/broadcast_channel/Cargo.toml +++ b/ext/broadcast_channel/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_broadcast_channel" -version = "0.73.0" +version = "0.74.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/cache/Cargo.toml b/ext/cache/Cargo.toml index 44b6687f36..06b1a04bb4 100644 --- a/ext/cache/Cargo.toml +++ b/ext/cache/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_cache" -version = "0.11.0" +version = "0.12.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/console/Cargo.toml b/ext/console/Cargo.toml index 810ab88750..f9eb072fd1 100644 --- a/ext/console/Cargo.toml +++ b/ext/console/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_console" -version = "0.79.0" +version = "0.80.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/crypto/Cargo.toml b/ext/crypto/Cargo.toml index 003e29d2bb..2baaecdfc1 100644 --- a/ext/crypto/Cargo.toml +++ b/ext/crypto/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_crypto" -version = "0.93.0" +version = "0.94.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/fetch/23_request.js b/ext/fetch/23_request.js index 508a291394..c09e3326f4 100644 --- a/ext/fetch/23_request.js +++ b/ext/fetch/23_request.js @@ -157,14 +157,14 @@ * @param {InnerRequest} request * @returns {InnerRequest} */ - function cloneInnerRequest(request) { + function cloneInnerRequest(request, skipBody = false) { const headerList = ArrayPrototypeMap( request.headerList, (x) => [x[0], x[1]], ); let body = null; - if (request.body !== null) { + if (request.body !== null && !skipBody) { body = request.body.clone(); } @@ -315,12 +315,14 @@ if (!ObjectPrototypeIsPrototypeOf(RequestPrototype, input)) { throw new TypeError("Unreachable"); } - request = input[_request]; + const originalReq = input[_request]; + // fold in of step 12 from below + request = cloneInnerRequest(originalReq, true); + request.redirectCount = 0; // reset to 0 - cloneInnerRequest copies the value signal = input[_signal]; } - // 12. - // TODO(lucacasonato): create a copy of `request` + // 12. is folded into the else statement of step 6 above. // 22. if (init.redirect !== undefined) { diff --git a/ext/fetch/Cargo.toml b/ext/fetch/Cargo.toml index 0482e6d5bc..dd41ad8c32 100644 --- a/ext/fetch/Cargo.toml +++ b/ext/fetch/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_fetch" -version = "0.102.0" +version = "0.103.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/ffi/Cargo.toml b/ext/ffi/Cargo.toml index 75707435b8..fdf2600724 100644 --- a/ext/ffi/Cargo.toml +++ b/ext/ffi/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_ffi" -version = "0.66.0" +version = "0.67.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/ffi/lib.rs b/ext/ffi/lib.rs index 3de204ef3f..7e7756c931 100644 --- a/ext/ffi/lib.rs +++ b/ext/ffi/lib.rs @@ -303,7 +303,7 @@ union NativeValue { isize_value: isize, f32_value: f32, f64_value: f64, - pointer: *const u8, + pointer: *mut c_void, } impl NativeValue { @@ -972,11 +972,11 @@ fn ffi_parse_pointer_arg( // 2. Number: Common and supported by Fast API. // 3. Null: Very uncommon / can be represented by a 0. let pointer = if let Ok(value) = v8::Local::::try_from(arg) { - value.u64_value().0 as usize as *const u8 + value.u64_value().0 as usize as *mut c_void } else if let Ok(value) = v8::Local::::try_from(arg) { - value.integer_value(scope).unwrap() as usize as *const u8 + value.integer_value(scope).unwrap() as usize as *mut c_void } else if arg.is_null() { - ptr::null() + ptr::null_mut() } else { return Err(type_error( "Invalid FFI pointer type, expected null, integer or BigInt", @@ -996,19 +996,28 @@ fn ffi_parse_buffer_arg( // 5. Null: Very uncommon / can be represented by a 0. let pointer = if let Ok(value) = v8::Local::::try_from(arg) { - let backing_store = value.get_backing_store(); - &backing_store[..] as *const _ as *const u8 + if let Some(non_null) = value.data() { + non_null.as_ptr() + } else { + ptr::null_mut() + } } else if let Ok(value) = v8::Local::::try_from(arg) { let byte_offset = value.byte_offset(); - let backing_store = value + let pointer = value .buffer(scope) .ok_or_else(|| { type_error("Invalid FFI ArrayBufferView, expected data in the buffer") })? - .get_backing_store(); - &backing_store[byte_offset..] as *const _ as *const u8 + .data(); + if let Some(non_null) = pointer { + // SAFETY: Pointer is non-null, and V8 guarantees that the byte_offset + // is within the buffer backing store. + unsafe { non_null.as_ptr().add(byte_offset) } + } else { + ptr::null_mut() + } } else if arg.is_null() { - ptr::null() + ptr::null_mut() } else { return Err(type_error( "Invalid FFI buffer type, expected null, ArrayBuffer, or ArrayBufferView", @@ -1027,11 +1036,11 @@ fn ffi_parse_function_arg( // 2. Number: Common and supported by Fast API, optimise this case as second. // 3. Null: Very uncommon / can be represented by a 0. let pointer = if let Ok(value) = v8::Local::::try_from(arg) { - value.u64_value().0 as usize as *const u8 + value.u64_value().0 as usize as *mut c_void } else if let Ok(value) = v8::Local::::try_from(arg) { - value.integer_value(scope).unwrap() as usize as *const u8 + value.integer_value(scope).unwrap() as usize as *mut c_void } else if arg.is_null() { - ptr::null() + ptr::null_mut() } else { return Err(type_error( "Invalid FFI function type, expected null, integer, or BigInt", @@ -1241,7 +1250,7 @@ where }, NativeType::Pointer | NativeType::Function | NativeType::Buffer => { NativeValue { - pointer: cif.call::<*const u8>(*fun_ptr, &call_args), + pointer: cif.call::<*mut c_void>(*fun_ptr, &call_args), } } }) @@ -1312,7 +1321,7 @@ fn ffi_call( }, NativeType::Pointer | NativeType::Function | NativeType::Buffer => { NativeValue { - pointer: cif.call::<*const u8>(fun_ptr, &call_args), + pointer: cif.call::<*mut c_void>(fun_ptr, &call_args), } } }) @@ -1820,9 +1829,10 @@ impl Future for CallbackInfo { #[op] fn op_ffi_unsafe_callback_ref( - state: &mut deno_core::OpState, + state: Rc>, rid: ResourceId, ) -> Result>, AnyError> { + let state = state.borrow(); let callback_resource = state.resource_table.get::(rid)?; @@ -2065,7 +2075,7 @@ fn op_ffi_call_nonblocking<'scope>( #[op(fast)] fn op_ffi_ptr_of( state: &mut deno_core::OpState, - buf: &[u8], + buf: *const u8, out: &mut [u32], ) -> Result<(), AnyError> where @@ -2084,7 +2094,7 @@ where // SAFETY: Out buffer was asserted to be at least large enough to hold a usize, and properly aligned. let out = unsafe { &mut *outptr }; - *out = buf.as_ptr() as usize; + *out = buf as usize; Ok(()) } diff --git a/ext/flash/01_http.js b/ext/flash/01_http.js index 67729ee398..2b0caff493 100644 --- a/ext/flash/01_http.js +++ b/ext/flash/01_http.js @@ -188,8 +188,8 @@ return str; } - function prepareFastCalls(serverId) { - return core.ops.op_flash_make_request(serverId); + function prepareFastCalls() { + return core.ops.op_flash_make_request(); } function hostnameForDisplay(hostname) { @@ -495,11 +495,15 @@ const serverId = opFn(listenOpts); const serverPromise = core.opAsync("op_flash_drive_server", serverId); - const listenPromise = PromisePrototypeThen( - core.opAsync("op_flash_wait_for_listening", serverId), - (port) => { - onListen({ hostname: listenOpts.hostname, port }); - }, + + PromisePrototypeCatch( + PromisePrototypeThen( + core.opAsync("op_flash_wait_for_listening", serverId), + (port) => { + onListen({ hostname: listenOpts.hostname, port }); + }, + ), + () => {}, ); const finishedPromise = PromisePrototypeCatch(serverPromise, () => {}); @@ -515,7 +519,7 @@ return; } server.closed = true; - core.ops.op_flash_close_server(serverId); + await core.opAsync("op_flash_close_server", serverId); await server.finished; }, async serve() { @@ -630,7 +634,7 @@ signal?.addEventListener("abort", () => { clearInterval(dateInterval); - server.close(); + PromisePrototypeThen(server.close(), () => {}, () => {}); }, { once: true, }); @@ -664,7 +668,7 @@ ); } - const fastOp = prepareFastCalls(serverId); + const fastOp = prepareFastCalls(); let nextRequestSync = () => fastOp.nextRequest(); let getMethodSync = (token) => fastOp.getMethod(token); let respondFast = (token, response, shutdown) => @@ -684,8 +688,8 @@ } await SafePromiseAll([ - listenPromise, PromisePrototypeCatch(server.serve(), console.error), + serverPromise, ]); }; } diff --git a/ext/flash/Cargo.toml b/ext/flash/Cargo.toml index 070c02e30a..bb7e70dacf 100644 --- a/ext/flash/Cargo.toml +++ b/ext/flash/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_flash" -version = "0.15.0" +version = "0.16.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/flash/lib.rs b/ext/flash/lib.rs index 7b43088071..04ed54e1ad 100644 --- a/ext/flash/lib.rs +++ b/ext/flash/lib.rs @@ -35,7 +35,6 @@ use mio::Events; use mio::Interest; use mio::Poll; use mio::Token; -use mio::Waker; use serde::Deserialize; use serde::Serialize; use socket2::Socket; @@ -48,7 +47,6 @@ use std::intrinsics::transmute; use std::io::BufReader; use std::io::Read; use std::io::Write; -use std::marker::PhantomPinned; use std::mem::replace; use std::net::SocketAddr; use std::net::ToSocketAddrs; @@ -57,8 +55,8 @@ use std::rc::Rc; use std::sync::Arc; use std::sync::Mutex; use std::task::Context; +use std::time::Duration; use tokio::sync::mpsc; -use tokio::sync::oneshot; use tokio::task::JoinHandle; mod chunked; @@ -78,24 +76,15 @@ pub struct FlashContext { pub servers: HashMap, } -impl Drop for FlashContext { - fn drop(&mut self) { - // Signal each server instance to shutdown. - for (_, server) in self.servers.drain() { - let _ = server.waker.wake(); - } - } -} - pub struct ServerContext { _addr: SocketAddr, tx: mpsc::Sender, - rx: Option>, + rx: mpsc::Receiver, requests: HashMap, next_token: u32, - listening_rx: Option>>, + listening_rx: Option>, + close_tx: mpsc::Sender<()>, cancel_handle: Rc, - waker: Arc, } #[derive(Debug, Eq, PartialEq)] @@ -113,10 +102,7 @@ fn op_flash_respond( shutdown: bool, ) -> u32 { let flash_ctx = op_state.borrow_mut::(); - let ctx = match flash_ctx.servers.get_mut(&server_id) { - Some(ctx) => ctx, - None => return 0, - }; + let ctx = flash_ctx.servers.get_mut(&server_id).unwrap(); flash_respond(ctx, token, shutdown, &response) } @@ -130,7 +116,7 @@ fn op_try_flash_respond_chuncked( ) -> u32 { let flash_ctx = op_state.borrow_mut::(); let ctx = flash_ctx.servers.get_mut(&server_id).unwrap(); - let tx = ctx.requests.get_mut(&token).unwrap(); + let tx = ctx.requests.get(&token).unwrap(); let sock = tx.socket(); // TODO(@littledivy): Use writev when `UnixIoSlice` lands. @@ -167,20 +153,17 @@ async fn op_flash_respond_async( let sock = { let mut op_state = state.borrow_mut(); let flash_ctx = op_state.borrow_mut::(); - let ctx = match flash_ctx.servers.get_mut(&server_id) { - Some(ctx) => ctx, - None => return Ok(()), - }; + let ctx = flash_ctx.servers.get_mut(&server_id).unwrap(); match shutdown { true => { - let mut tx = ctx.requests.remove(&token).unwrap(); + let tx = ctx.requests.remove(&token).unwrap(); close = !tx.keep_alive; tx.socket() } // In case of a websocket upgrade or streaming response. false => { - let tx = ctx.requests.get_mut(&token).unwrap(); + let tx = ctx.requests.get(&token).unwrap(); tx.socket() } } @@ -214,12 +197,12 @@ async fn op_flash_respond_chuncked( let ctx = flash_ctx.servers.get_mut(&server_id).unwrap(); let sock = match shutdown { true => { - let mut tx = ctx.requests.remove(&token).unwrap(); + let tx = ctx.requests.remove(&token).unwrap(); tx.socket() } // In case of a websocket upgrade or streaming response. false => { - let tx = ctx.requests.get_mut(&token).unwrap(); + let tx = ctx.requests.get(&token).unwrap(); tx.socket() } }; @@ -361,7 +344,7 @@ fn flash_respond( shutdown: bool, response: &[u8], ) -> u32 { - let tx = ctx.requests.get_mut(&token).unwrap(); + let tx = ctx.requests.get(&token).unwrap(); let sock = tx.socket(); sock.read_tx.take(); @@ -445,36 +428,15 @@ fn op_flash_method(state: &mut OpState, server_id: u32, token: u32) -> u32 { } #[op] -fn op_flash_drive_server( - state: &mut OpState, - server_id: u32, -) -> Result> + 'static, AnyError> { - let join_handle = { - let flash_ctx = state.borrow_mut::(); - flash_ctx - .join_handles - .remove(&server_id) - .ok_or_else(|| type_error("server not found"))? +async fn op_flash_close_server(state: Rc>, server_id: u32) { + let close_tx = { + let mut op_state = state.borrow_mut(); + let flash_ctx = op_state.borrow_mut::(); + let ctx = flash_ctx.servers.get_mut(&server_id).unwrap(); + ctx.cancel_handle.cancel(); + ctx.close_tx.clone() }; - Ok(async move { - join_handle - .await - .map_err(|_| type_error("server join error"))??; - Ok(()) - }) -} - -#[op] -fn op_flash_close_server(state: &mut OpState, server_id: u32) { - let flash_ctx = state.borrow_mut::(); - let ctx = flash_ctx.servers.get(&server_id).unwrap(); - - // NOTE: We don't drop ServerContext associated with the given `server_id`, - // because it may still be in use by some unsettled promise after the flash - // thread is finished. - - ctx.cancel_handle.cancel(); - let _ = ctx.waker.wake(); + let _ = close_tx.send(()).await; } #[op] @@ -501,7 +463,7 @@ fn op_flash_path( fn next_request_sync(ctx: &mut ServerContext) -> u32 { let offset = ctx.next_token; - while let Ok(token) = ctx.rx.as_mut().unwrap().try_recv() { + while let Ok(token) = ctx.rx.try_recv() { ctx.requests.insert(ctx.next_token, token); ctx.next_token += 1; } @@ -564,7 +526,6 @@ unsafe fn op_flash_get_method_fast( fn op_flash_make_request<'scope>( scope: &mut v8::HandleScope<'scope>, state: &mut OpState, - server_id: u32, ) -> serde_v8::Value<'scope> { let object_template = v8::ObjectTemplate::new(scope); assert!(object_template @@ -572,7 +533,7 @@ fn op_flash_make_request<'scope>( let obj = object_template.new_instance(scope).unwrap(); let ctx = { let flash_ctx = state.borrow_mut::(); - let ctx = flash_ctx.servers.get_mut(&server_id).unwrap(); + let ctx = flash_ctx.servers.get_mut(&0).unwrap(); ctx as *mut ServerContext }; obj.set_aligned_pointer_in_internal_field(V8_WRAPPER_OBJECT_INDEX, ctx as _); @@ -664,7 +625,7 @@ fn op_flash_make_request<'scope>( } #[inline] -fn has_body_stream(req: &mut Request) -> bool { +fn has_body_stream(req: &Request) -> bool { let sock = req.socket(); sock.read_rx.is_some() } @@ -788,10 +749,7 @@ async fn op_flash_read_body( { let op_state = &mut state.borrow_mut(); let flash_ctx = op_state.borrow_mut::(); - match flash_ctx.servers.get_mut(&server_id) { - Some(ctx) => ctx as *mut ServerContext, - None => return 0, - } + flash_ctx.servers.get_mut(&server_id).unwrap() as *mut ServerContext } .as_mut() .unwrap() @@ -893,40 +851,41 @@ pub struct ListenOpts { reuseport: bool, } -const SERVER_TOKEN: Token = Token(0); -// Token reserved for the thread close signal. -const WAKER_TOKEN: Token = Token(1); - -#[allow(clippy::too_many_arguments)] fn run_server( tx: mpsc::Sender, - listening_tx: mpsc::Sender>, + listening_tx: mpsc::Sender, + mut close_rx: mpsc::Receiver<()>, addr: SocketAddr, maybe_cert: Option, maybe_key: Option, reuseport: bool, - mut poll: Poll, - // We put a waker as an unused argument here as it needs to be alive both in - // the flash thread and in the main thread (otherwise the notification would - // not be caught by the event loop on Linux). - // See the comment in mio's example: - // https://docs.rs/mio/0.8.4/x86_64-unknown-linux-gnu/mio/struct.Waker.html#examples - _waker: Arc, ) -> Result<(), AnyError> { - let mut listener = match listen(addr, reuseport) { - Ok(listener) => listener, - Err(e) => { - listening_tx.blocking_send(Err(e)).unwrap(); - return Err(generic_error( - "failed to start listening on the specified address", - )); - } + let domain = if addr.is_ipv4() { + socket2::Domain::IPV4 + } else { + socket2::Domain::IPV6 }; + let socket = Socket::new(domain, socket2::Type::STREAM, None)?; - // Register server. + #[cfg(not(windows))] + socket.set_reuse_address(true)?; + if reuseport { + #[cfg(target_os = "linux")] + socket.set_reuse_port(true)?; + } + + let socket_addr = socket2::SockAddr::from(addr); + socket.bind(&socket_addr)?; + socket.listen(128)?; + socket.set_nonblocking(true)?; + let std_listener: std::net::TcpListener = socket.into(); + let mut listener = TcpListener::from_std(std_listener); + + let mut poll = Poll::new()?; + let token = Token(0); poll .registry() - .register(&mut listener, SERVER_TOKEN, Interest::READABLE) + .register(&mut listener, token, Interest::READABLE) .unwrap(); let tls_context: Option> = { @@ -948,25 +907,30 @@ fn run_server( }; listening_tx - .blocking_send(Ok(listener.local_addr().unwrap().port())) + .blocking_send(listener.local_addr().unwrap().port()) .unwrap(); let mut sockets = HashMap::with_capacity(1000); - let mut socket_senders = HashMap::with_capacity(1000); - let mut counter: usize = 2; + let mut counter: usize = 1; let mut events = Events::with_capacity(1024); 'outer: loop { - match poll.poll(&mut events, None) { + let result = close_rx.try_recv(); + if result.is_ok() { + break 'outer; + } + // FIXME(bartlomieju): how does Tokio handle it? I just put random 100ms + // timeout here to handle close signal. + match poll.poll(&mut events, Some(Duration::from_millis(100))) { Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue, Err(e) => panic!("{}", e), Ok(()) => (), } 'events: for event in &events { + if close_rx.try_recv().is_ok() { + break 'outer; + } let token = event.token(); match token { - WAKER_TOKEN => { - break 'outer; - } - SERVER_TOKEN => loop { + Token(0) => loop { match listener.accept() { Ok((mut socket, _)) => { counter += 1; @@ -994,7 +958,6 @@ fn run_server( read_lock: Arc::new(Mutex::new(())), parse_done: ParseStatus::None, buffer: UnsafeCell::new(vec![0_u8; 1024]), - _pinned: PhantomPinned, }); trace!("New connection: {}", token.0); @@ -1011,6 +974,7 @@ fn run_server( let mut_ref: Pin<&mut Stream> = Pin::as_mut(socket); Pin::get_unchecked_mut(mut_ref) }; + let sock_ptr = socket as *mut _; if socket.detached { match &mut socket.inner { @@ -1024,7 +988,6 @@ fn run_server( let boxed = sockets.remove(&token).unwrap(); std::mem::forget(boxed); - socket_senders.remove(&token); trace!("Socket detached: {}", token.0); continue; } @@ -1210,10 +1173,8 @@ fn run_server( continue 'events; } - let (socket_tx, socket_rx) = oneshot::channel(); - tx.blocking_send(Request { - socket: socket as *mut _, + socket: sock_ptr, // SAFETY: headers backing buffer outlives the mio event loop ('static) inner: inner_req, keep_alive, @@ -1222,57 +1183,16 @@ fn run_server( content_read: 0, content_length, expect_continue, - socket_rx, - owned_socket: None, }) .ok(); - - socket_senders.insert(token, socket_tx); } } } } - // Now the flash thread is about to finish, but there may be some unsettled - // promises in the main thread that will use the socket. To make the socket - // alive longer enough, we move its ownership to the main thread. - for (tok, socket) in sockets { - if let Some(sender) = socket_senders.remove(&tok) { - // Do nothing if the receiver has already been dropped. - _ = sender.send(socket); - } - } - Ok(()) } -#[inline] -fn listen( - addr: SocketAddr, - reuseport: bool, -) -> Result { - let domain = if addr.is_ipv4() { - socket2::Domain::IPV4 - } else { - socket2::Domain::IPV6 - }; - let socket = Socket::new(domain, socket2::Type::STREAM, None)?; - - #[cfg(not(windows))] - socket.set_reuse_address(true)?; - if reuseport { - #[cfg(target_os = "linux")] - socket.set_reuse_port(true)?; - } - - let socket_addr = socket2::SockAddr::from(addr); - socket.bind(&socket_addr)?; - socket.listen(128)?; - socket.set_nonblocking(true)?; - let std_listener: std::net::TcpListener = socket.into(); - Ok(TcpListener::from_std(std_listener)) -} - fn make_addr_port_pair(hostname: &str, port: u16) -> (&str, u16) { // Default to localhost if given just the port. Example: ":80" if hostname.is_empty() { @@ -1310,19 +1230,17 @@ where .next() .ok_or_else(|| generic_error("No resolved address found"))?; let (tx, rx) = mpsc::channel(100); + let (close_tx, close_rx) = mpsc::channel(1); let (listening_tx, listening_rx) = mpsc::channel(1); - - let poll = Poll::new()?; - let waker = Arc::new(Waker::new(poll.registry(), WAKER_TOKEN).unwrap()); let ctx = ServerContext { _addr: addr, tx, - rx: Some(rx), + rx, requests: HashMap::with_capacity(1000), next_token: 0, + close_tx, listening_rx: Some(listening_rx), cancel_handle: CancelHandle::new_rc(), - waker: waker.clone(), }; let tx = ctx.tx.clone(); let maybe_cert = opts.cert; @@ -1332,12 +1250,11 @@ where run_server( tx, listening_tx, + close_rx, addr, maybe_cert, maybe_key, reuseport, - poll, - waker, ) }); let flash_ctx = state.borrow_mut::(); @@ -1372,26 +1289,47 @@ where } #[op] -async fn op_flash_wait_for_listening( +fn op_flash_wait_for_listening( state: Rc>, server_id: u32, -) -> Result { +) -> Result> + 'static, AnyError> { let mut listening_rx = { - let mut op_state = state.borrow_mut(); - let flash_ctx = op_state.borrow_mut::(); + let mut state = state.borrow_mut(); + let flash_ctx = state.borrow_mut::(); let server_ctx = flash_ctx .servers .get_mut(&server_id) .ok_or_else(|| type_error("server not found"))?; server_ctx.listening_rx.take().unwrap() }; - match listening_rx.recv().await { - Some(Ok(port)) => Ok(port), - Some(Err(e)) => Err(e.into()), - _ => Err(generic_error( - "unknown error occurred while waiting for listening", - )), - } + Ok(async move { + if let Some(port) = listening_rx.recv().await { + Ok(port) + } else { + Err(generic_error("This error will be discarded")) + } + }) +} + +#[op] +fn op_flash_drive_server( + state: Rc>, + server_id: u32, +) -> Result> + 'static, AnyError> { + let join_handle = { + let mut state = state.borrow_mut(); + let flash_ctx = state.borrow_mut::(); + flash_ctx + .join_handles + .remove(&server_id) + .ok_or_else(|| type_error("server not found"))? + }; + Ok(async move { + join_handle + .await + .map_err(|_| type_error("server join error"))??; + Ok(()) + }) } // Asychronous version of op_flash_next. This can be a bottleneck under @@ -1399,34 +1337,26 @@ async fn op_flash_wait_for_listening( // requests i.e `op_flash_next() == 0`. #[op] async fn op_flash_next_async( - state: Rc>, + op_state: Rc>, server_id: u32, ) -> u32 { - let mut op_state = state.borrow_mut(); - let flash_ctx = op_state.borrow_mut::(); - let ctx = flash_ctx.servers.get_mut(&server_id).unwrap(); - let cancel_handle = ctx.cancel_handle.clone(); - let mut rx = ctx.rx.take().unwrap(); - // We need to drop the borrow before await point. - drop(op_state); - - if let Ok(Some(req)) = rx.recv().or_cancel(&cancel_handle).await { - let mut op_state = state.borrow_mut(); + let ctx = { + let mut op_state = op_state.borrow_mut(); let flash_ctx = op_state.borrow_mut::(); let ctx = flash_ctx.servers.get_mut(&server_id).unwrap(); + ctx as *mut ServerContext + }; + // SAFETY: we cannot hold op_state borrow across the await point. The JS caller + // is responsible for ensuring this is not called concurrently. + let ctx = unsafe { &mut *ctx }; + let cancel_handle = &ctx.cancel_handle; + + if let Ok(Some(req)) = ctx.rx.recv().or_cancel(cancel_handle).await { ctx.requests.insert(ctx.next_token, req); ctx.next_token += 1; - // Set the rx back. - ctx.rx = Some(rx); return 1; } - // Set the rx back. - let mut op_state = state.borrow_mut(); - let flash_ctx = op_state.borrow_mut::(); - if let Some(ctx) = flash_ctx.servers.get_mut(&server_id) { - ctx.rx = Some(rx); - } 0 } @@ -1499,7 +1429,7 @@ pub fn detach_socket( // dropped on the server thread. // * conversion from mio::net::TcpStream -> tokio::net::TcpStream. There is no public API so we // use raw fds. - let mut tx = ctx + let tx = ctx .requests .remove(&token) .ok_or_else(|| type_error("request closed"))?; @@ -1594,11 +1524,11 @@ pub fn init(unstable: bool) -> Extension { op_flash_next_async::decl(), op_flash_read_body::decl(), op_flash_upgrade_websocket::decl(), + op_flash_drive_server::decl(), op_flash_wait_for_listening::decl(), op_flash_first_packet::decl(), op_flash_has_body_stream::decl(), op_flash_close_server::decl(), - op_flash_drive_server::decl(), op_flash_make_request::decl(), op_flash_write_resource::decl(), op_try_flash_respond_chuncked::decl(), diff --git a/ext/flash/request.rs b/ext/flash/request.rs index ac077df6fb..0736b56206 100644 --- a/ext/flash/request.rs +++ b/ext/flash/request.rs @@ -2,7 +2,6 @@ use crate::Stream; use std::pin::Pin; -use tokio::sync::oneshot; #[derive(Debug)] pub struct InnerRequest { @@ -21,7 +20,8 @@ pub struct Request { pub inner: InnerRequest, // Pointer to stream owned by the server loop thread. // - // Dereferencing is safe until websocket upgrade is performed. + // Dereferencing is safe until server thread finishes and + // op_flash_serve resolves or websocket upgrade is performed. pub socket: *mut Stream, pub keep_alive: bool, pub content_read: usize, @@ -29,8 +29,6 @@ pub struct Request { pub remaining_chunk_size: Option, pub te_chunked: bool, pub expect_continue: bool, - pub socket_rx: oneshot::Receiver>>, - pub owned_socket: Option>>, } // SAFETY: Sent from server thread to JS thread. @@ -39,16 +37,8 @@ unsafe impl Send for Request {} impl Request { #[inline(always)] - pub fn socket<'a>(&mut self) -> &'a mut Stream { - if let Ok(mut sock) = self.socket_rx.try_recv() { - // SAFETY: We never move the data out of the acquired mutable reference. - self.socket = unsafe { sock.as_mut().get_unchecked_mut() }; - - // Let the struct own the socket so that it won't get dropped. - self.owned_socket = Some(sock); - } - - // SAFETY: Dereferencing is safe until server thread detaches socket. + pub fn socket<'a>(&self) -> &'a mut Stream { + // SAFETY: Dereferencing is safe until server thread detaches socket or finishes. unsafe { &mut *self.socket } } diff --git a/ext/flash/socket.rs b/ext/flash/socket.rs index 7c75b230a6..8256be8a0c 100644 --- a/ext/flash/socket.rs +++ b/ext/flash/socket.rs @@ -1,26 +1,23 @@ use deno_core::error::AnyError; use mio::net::TcpStream; -use std::cell::UnsafeCell; -use std::future::Future; -use std::io::Read; -use std::io::Write; -use std::marker::PhantomPinned; -use std::pin::Pin; -use std::sync::Arc; -use std::sync::Mutex; +use std::{ + cell::UnsafeCell, + future::Future, + io::{Read, Write}, + pin::Pin, + sync::{Arc, Mutex}, +}; use tokio::sync::mpsc; use crate::ParseStatus; type TlsTcpStream = rustls::StreamOwned; -#[derive(Debug)] pub enum InnerStream { Tcp(TcpStream), Tls(Box), } -#[derive(Debug)] pub struct Stream { pub inner: InnerStream, pub detached: bool, @@ -29,7 +26,6 @@ pub struct Stream { pub parse_done: ParseStatus, pub buffer: UnsafeCell>, pub read_lock: Arc>, - pub _pinned: PhantomPinned, } impl Stream { diff --git a/ext/http/Cargo.toml b/ext/http/Cargo.toml index 57c3844017..1f09807b98 100644 --- a/ext/http/Cargo.toml +++ b/ext/http/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_http" -version = "0.73.0" +version = "0.74.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/napi/Cargo.toml b/ext/napi/Cargo.toml index a70636e1e6..4f58c19319 100644 --- a/ext/napi/Cargo.toml +++ b/ext/napi/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_napi" -version = "0.9.0" +version = "0.10.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/net/Cargo.toml b/ext/net/Cargo.toml index fa31150a7e..7d917f78ae 100644 --- a/ext/net/Cargo.toml +++ b/ext/net/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_net" -version = "0.71.0" +version = "0.72.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/net/ops.rs b/ext/net/ops.rs index 96de8cff13..e567c31885 100644 --- a/ext/net/ops.rs +++ b/ext/net/ops.rs @@ -67,8 +67,8 @@ pub fn init() -> Vec { #[cfg(unix)] crate::ops_unix::op_net_send_unixpacket::decl::

(), op_dns_resolve::decl::

(), - op_set_nodelay::decl::

(), - op_set_keepalive::decl::

(), + op_set_nodelay::decl(), + op_set_keepalive::decl(), ] } @@ -509,7 +509,7 @@ where } #[op] -pub fn op_set_nodelay( +pub fn op_set_nodelay( state: &mut OpState, rid: ResourceId, nodelay: bool, @@ -521,7 +521,7 @@ pub fn op_set_nodelay( } #[op] -pub fn op_set_keepalive( +pub fn op_set_keepalive( state: &mut OpState, rid: ResourceId, keepalive: bool, @@ -836,7 +836,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn tcp_set_no_delay() { let set_nodelay = Box::new(|state: &mut OpState, rid| { - op_set_nodelay::call::(state, rid, true).unwrap(); + op_set_nodelay::call(state, rid, true).unwrap(); }); let test_fn = Box::new(|socket: SockRef| { assert!(socket.nodelay().unwrap()); @@ -848,7 +848,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn tcp_set_keepalive() { let set_keepalive = Box::new(|state: &mut OpState, rid| { - op_set_keepalive::call::(state, rid, true).unwrap(); + op_set_keepalive::call(state, rid, true).unwrap(); }); let test_fn = Box::new(|socket: SockRef| { assert!(!socket.nodelay().unwrap()); diff --git a/ext/node/02_require.js b/ext/node/02_require.js index 372cc84719..53921c2425 100644 --- a/ext/node/02_require.js +++ b/ext/node/02_require.js @@ -69,6 +69,8 @@ let statCache = null; let isPreloading = false; let mainModule = null; + let hasBrokenOnInspectBrk = false; + let hasInspectBrk = false; function stat(filename) { // TODO: required only on windows @@ -351,7 +353,7 @@ } } - const isDenoDirPackage = Deno.core.ops.op_require_is_deno_dir_package( + const isDenoDirPackage = core.ops.op_require_is_deno_dir_package( curPath, ); const isRelative = ops.op_require_is_request_relative( @@ -723,6 +725,12 @@ if (requireDepth === 0) { statCache = new SafeMap(); } + + if (hasInspectBrk && !hasBrokenOnInspectBrk) { + hasBrokenOnInspectBrk = true; + core.ops.op_require_break_on_next_statement(); + } + const result = compiledWrapper.call( thisValue, exports, @@ -818,6 +826,17 @@ return require; } + // Matches to: + // - /foo/... + // - \foo\... + // - C:/foo/... + // - C:\foo\... + const RE_START_OF_ABS_PATH = /^([/\\]|[a-zA-Z]:[/\\])/; + + function isAbsolute(filenameOrUrl) { + return RE_START_OF_ABS_PATH.test(filenameOrUrl); + } + function createRequire(filenameOrUrl) { let fileUrlStr; if (filenameOrUrl instanceof URL) { @@ -828,7 +847,7 @@ } fileUrlStr = filenameOrUrl.toString(); } else if (typeof filenameOrUrl === "string") { - if (!filenameOrUrl.startsWith("file:")) { + if (!filenameOrUrl.startsWith("file:") && !isAbsolute(filenameOrUrl)) { throw new Error( `The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received ${filenameOrUrl}`, ); @@ -896,6 +915,9 @@ window.__bootstrap.internals = { ...window.__bootstrap.internals ?? {}, require: { + setInspectBrk() { + hasInspectBrk = true; + }, Module, wrapSafe, toRealPath, diff --git a/ext/node/Cargo.toml b/ext/node/Cargo.toml index eb2e3bf4b4..afb66d05c2 100644 --- a/ext/node/Cargo.toml +++ b/ext/node/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_node" -version = "0.16.0" +version = "0.17.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/node/lib.rs b/ext/node/lib.rs index d69d3b6fe5..5282c0660b 100644 --- a/ext/node/lib.rs +++ b/ext/node/lib.rs @@ -7,6 +7,7 @@ use deno_core::normalize_path; use deno_core::op; use deno_core::url::Url; use deno_core::Extension; +use deno_core::JsRuntimeInspector; use deno_core::OpState; use once_cell::sync::Lazy; use std::collections::HashSet; @@ -29,8 +30,9 @@ pub use resolution::package_imports_resolve; pub use resolution::package_resolve; pub use resolution::path_to_declaration_path; pub use resolution::NodeModuleKind; +pub use resolution::NodeResolutionMode; pub use resolution::DEFAULT_CONDITIONS; -pub use resolution::TYPES_CONDITIONS; +use std::cell::RefCell; pub trait NodePermissions { fn check_read(&mut self, path: &Path) -> Result<(), AnyError>; @@ -41,7 +43,7 @@ pub trait RequireNpmResolver { &self, specifier: &str, referrer: &Path, - conditions: &[&str], + mode: NodeResolutionMode, ) -> Result; fn resolve_package_folder_from_path( @@ -106,6 +108,7 @@ pub fn init( op_require_read_closest_package_json::decl::

(), op_require_read_package_scope::decl(), op_require_package_imports_resolve::decl::

(), + op_require_break_on_next_statement::decl(), ]) .state(move |state| { if let Some(npm_resolver) = maybe_npm_resolver.clone() { @@ -242,7 +245,10 @@ where fn op_require_proxy_path(filename: String) -> String { // Allow a directory to be passed as the filename let trailing_slash = if cfg!(windows) { - filename.ends_with('\\') + // Node also counts a trailing forward slash as a + // directory for node on Windows, but not backslashes + // on non-Windows platforms + filename.ends_with('\\') || filename.ends_with('/') } else { filename.ends_with('/') }; @@ -256,7 +262,7 @@ fn op_require_proxy_path(filename: String) -> String { } #[op] -fn op_require_is_request_relative(request: String) -> bool { +fn op_require_is_request_relative(request: &str) -> bool { if request.starts_with("./") || request.starts_with("../") || request == ".." { return true; @@ -286,7 +292,7 @@ fn op_require_resolve_deno_dir( .resolve_package_folder_from_package( &request, &PathBuf::from(parent_filename), - DEFAULT_CONDITIONS, + NodeResolutionMode::Execution, ) .ok() .map(|p| p.to_string_lossy().to_string()) @@ -500,6 +506,7 @@ fn op_require_try_self( &referrer, NodeModuleKind::Cjs, resolution::REQUIRE_CONDITIONS, + NodeResolutionMode::Execution, &*resolver, ) .map(|r| Some(r.to_string_lossy().to_string())) @@ -562,6 +569,7 @@ fn op_require_resolve_exports( &referrer, NodeModuleKind::Cjs, resolution::REQUIRE_CONDITIONS, + NodeResolutionMode::Execution, &*resolver, ) .map(|r| Some(r.to_string_lossy().to_string())) @@ -621,6 +629,7 @@ where &referrer, NodeModuleKind::Cjs, resolution::REQUIRE_CONDITIONS, + NodeResolutionMode::Execution, &*resolver, ) .map(|r| Some(Url::from_file_path(r).unwrap().to_string())); @@ -630,3 +639,11 @@ where Ok(None) } } + +#[op] +fn op_require_break_on_next_statement(state: &mut OpState) { + let inspector = state.borrow::>>(); + inspector + .borrow_mut() + .wait_for_session_and_break_on_next_statement() +} diff --git a/ext/node/resolution.rs b/ext/node/resolution.rs index 6f61ebff2a..855bebc71d 100644 --- a/ext/node/resolution.rs +++ b/ext/node/resolution.rs @@ -19,7 +19,6 @@ use crate::RequireNpmResolver; pub static DEFAULT_CONDITIONS: &[&str] = &["deno", "node", "import"]; pub static REQUIRE_CONDITIONS: &[&str] = &["require", "node"]; -pub static TYPES_CONDITIONS: &[&str] = &["types"]; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NodeModuleKind { @@ -27,11 +26,23 @@ pub enum NodeModuleKind { Cjs, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NodeResolutionMode { + Execution, + Types, +} + +impl NodeResolutionMode { + pub fn is_types(&self) -> bool { + matches!(self, NodeResolutionMode::Types) + } +} + /// Checks if the resolved file has a corresponding declaration file. pub fn path_to_declaration_path( path: PathBuf, referrer_kind: NodeModuleKind, -) -> PathBuf { +) -> Option { fn probe_extensions( path: &Path, referrer_kind: NodeModuleKind, @@ -56,17 +67,17 @@ pub fn path_to_declaration_path( || lowercase_path.ends_with(".d.cts") || lowercase_path.ends_with(".d.ts") { - return path; + return Some(path); } if let Some(path) = probe_extensions(&path, referrer_kind) { - return path; + return Some(path); } if path.is_dir() { if let Some(path) = probe_extensions(&path.join("index"), referrer_kind) { - return path; + return Some(path); } } - path + None } /// Alternate `PathBuf::with_extension` that will handle known extensions @@ -175,6 +186,7 @@ pub fn package_imports_resolve( referrer: &ModuleSpecifier, referrer_kind: NodeModuleKind, conditions: &[&str], + mode: NodeResolutionMode, npm_resolver: &dyn RequireNpmResolver, ) -> Result { if name == "#" || name.starts_with("#/") || name.ends_with('/') { @@ -202,6 +214,7 @@ pub fn package_imports_resolve( false, true, conditions, + mode, npm_resolver, )?; if let Some(resolved) = maybe_resolved { @@ -243,6 +256,7 @@ pub fn package_imports_resolve( true, true, conditions, + mode, npm_resolver, )?; if let Some(resolved) = maybe_resolved { @@ -306,6 +320,7 @@ fn resolve_package_target_string( pattern: bool, internal: bool, conditions: &[&str], + mode: NodeResolutionMode, npm_resolver: &dyn RequireNpmResolver, ) -> Result { if !subpath.is_empty() && !pattern && !target.ends_with('/') { @@ -338,6 +353,7 @@ fn resolve_package_target_string( &package_json_url, referrer_kind, conditions, + mode, npm_resolver, ) { Ok(Some(path)) => Ok(path), @@ -412,10 +428,11 @@ fn resolve_package_target( pattern: bool, internal: bool, conditions: &[&str], + mode: NodeResolutionMode, npm_resolver: &dyn RequireNpmResolver, ) -> Result, AnyError> { if let Some(target) = target.as_str() { - return Ok(Some(resolve_package_target_string( + return resolve_package_target_string( target.to_string(), subpath, package_subpath, @@ -425,8 +442,10 @@ fn resolve_package_target( pattern, internal, conditions, + mode, npm_resolver, - )?)); + ) + .map(Some); } else if let Some(target_arr) = target.as_array() { if target_arr.is_empty() { return Ok(None); @@ -444,23 +463,25 @@ fn resolve_package_target( pattern, internal, conditions, + mode, npm_resolver, ); - if let Err(e) = resolved_result { - let err_string = e.to_string(); - last_error = Some(e); - if err_string.starts_with("[ERR_INVALID_PACKAGE_TARGET]") { + match resolved_result { + Ok(Some(resolved)) => return Ok(Some(resolved)), + Ok(None) => { + last_error = None; continue; } - return Err(last_error.unwrap()); + Err(e) => { + let err_string = e.to_string(); + last_error = Some(e); + if err_string.starts_with("[ERR_INVALID_PACKAGE_TARGET]") { + continue; + } + return Err(last_error.unwrap()); + } } - let resolved = resolved_result.unwrap(); - if resolved.is_none() { - last_error = None; - continue; - } - return Ok(resolved); } if last_error.is_none() { return Ok(None); @@ -475,8 +496,20 @@ fn resolve_package_target( // Some("\"exports\" cannot contain numeric property keys.".to_string()), // )); - if key == "default" || conditions.contains(&key.as_str()) { + if key == "default" + || conditions.contains(&key.as_str()) + || mode.is_types() && key.as_str() == "types" + { let condition_target = target_obj.get(key).unwrap().to_owned(); + + if mode.is_types() + && key.as_str() != "types" + && condition_target.is_string() + { + // skip because this isn't a types entry + continue; + } + let resolved = resolve_package_target( package_json_path, condition_target, @@ -487,12 +520,15 @@ fn resolve_package_target( pattern, internal, conditions, + mode, npm_resolver, )?; - if resolved.is_none() { - continue; + match resolved { + Some(resolved) => return Ok(Some(resolved)), + None => { + continue; + } } - return Ok(resolved); } } } else if target.is_null() { @@ -520,6 +556,7 @@ fn throw_exports_not_found( ) } +#[allow(clippy::too_many_arguments)] pub fn package_exports_resolve( package_json_path: &Path, package_subpath: String, @@ -527,6 +564,7 @@ pub fn package_exports_resolve( referrer: &ModuleSpecifier, referrer_kind: NodeModuleKind, conditions: &[&str], + mode: NodeResolutionMode, npm_resolver: &dyn RequireNpmResolver, ) -> Result { if package_exports.contains_key(&package_subpath) @@ -544,6 +582,7 @@ pub fn package_exports_resolve( false, false, conditions, + mode, npm_resolver, )?; if resolved.is_none() { @@ -602,6 +641,7 @@ pub fn package_exports_resolve( true, false, conditions, + mode, npm_resolver, )?; if let Some(resolved) = maybe_resolved { @@ -678,6 +718,7 @@ pub fn package_resolve( referrer: &ModuleSpecifier, referrer_kind: NodeModuleKind, conditions: &[&str], + mode: NodeResolutionMode, npm_resolver: &dyn RequireNpmResolver, ) -> Result, AnyError> { let (package_name, package_subpath, _is_scoped) = @@ -696,6 +737,7 @@ pub fn package_resolve( referrer, referrer_kind, conditions, + mode, npm_resolver, ) .map(Some); @@ -705,7 +747,7 @@ pub fn package_resolve( let package_dir_path = npm_resolver.resolve_package_folder_from_package( &package_name, &referrer.to_file_path().unwrap(), - conditions, + mode, )?; let package_json_path = package_dir_path.join("package.json"); @@ -732,19 +774,21 @@ pub fn package_resolve( referrer, referrer_kind, conditions, + mode, npm_resolver, ) .map(Some); } if package_subpath == "." { - return legacy_main_resolve(&package_json, referrer_kind, conditions); + return legacy_main_resolve(&package_json, referrer_kind, mode); } let file_path = package_json.path.parent().unwrap().join(&package_subpath); - if conditions == TYPES_CONDITIONS { - let declaration_path = path_to_declaration_path(file_path, referrer_kind); - Ok(Some(declaration_path)) + if mode.is_types() { + let maybe_declaration_path = + path_to_declaration_path(file_path, referrer_kind); + Ok(maybe_declaration_path) } else { Ok(Some(file_path)) } @@ -802,10 +846,9 @@ fn file_exists(path: &Path) -> bool { pub fn legacy_main_resolve( package_json: &PackageJson, referrer_kind: NodeModuleKind, - conditions: &[&str], + mode: NodeResolutionMode, ) -> Result, AnyError> { - let is_types = conditions == TYPES_CONDITIONS; - let maybe_main = if is_types { + let maybe_main = if mode.is_types() { match package_json.types.as_ref() { Some(types) => Some(types), None => { @@ -813,8 +856,7 @@ pub fn legacy_main_resolve( // a corresponding declaration file if let Some(main) = package_json.main(referrer_kind) { let main = package_json.path.parent().unwrap().join(main).clean(); - let path = path_to_declaration_path(main, referrer_kind); - if path.exists() { + if let Some(path) = path_to_declaration_path(main, referrer_kind) { return Ok(Some(path)); } } @@ -832,7 +874,7 @@ pub fn legacy_main_resolve( } // todo(dsherret): investigate exactly how node and typescript handles this - let endings = if is_types { + let endings = if mode.is_types() { match referrer_kind { NodeModuleKind::Cjs => { vec![".d.ts", ".d.cts", "/index.d.ts", "/index.d.cts"] @@ -863,7 +905,7 @@ pub fn legacy_main_resolve( } } - let index_file_names = if is_types { + let index_file_names = if mode.is_types() { // todo(dsherret): investigate exactly how typescript does this match referrer_kind { NodeModuleKind::Cjs => vec!["index.d.ts", "index.d.cts"], diff --git a/ext/tls/Cargo.toml b/ext/tls/Cargo.toml index 58a7df487d..b387165d44 100644 --- a/ext/tls/Cargo.toml +++ b/ext/tls/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_tls" -version = "0.66.0" +version = "0.67.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/url/00_url.js b/ext/url/00_url.js index 5479cb59ce..754c647b12 100644 --- a/ext/url/00_url.js +++ b/ext/url/00_url.js @@ -56,12 +56,12 @@ function opUrlParse(href, maybeBase) { let status; if (maybeBase === undefined) { - status = ops.op_url_parse(href, componentsBuf.buffer); + status = ops.op_url_parse(href, componentsBuf); } else { - status = core.ops.op_url_parse_with_base( + status = ops.op_url_parse_with_base( href, maybeBase, - componentsBuf.buffer, + componentsBuf, ); } return getSerialization(status, href); @@ -71,7 +71,7 @@ if (status === 0) { return href; } else if (status === 1) { - return core.ops.op_url_get_serialization(); + return ops.op_url_get_serialization(); } else { throw new TypeError("Invalid URL"); } diff --git a/ext/url/Cargo.toml b/ext/url/Cargo.toml index eae81c8919..5408c2452c 100644 --- a/ext/url/Cargo.toml +++ b/ext/url/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_url" -version = "0.79.0" +version = "0.80.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/url/lib.rs b/ext/url/lib.rs index ac668207fd..01014ccd34 100644 --- a/ext/url/lib.rs +++ b/ext/url/lib.rs @@ -41,11 +41,11 @@ pub fn init() -> Extension { #[op] pub fn op_url_parse_with_base( state: &mut OpState, - href: String, - base_href: String, - buf: &mut [u8], + href: &str, + base_href: &str, + buf: &mut [u32], ) -> u32 { - let base_url = match Url::parse(&base_href) { + let base_url = match Url::parse(base_href) { Ok(url) => url, Err(_) => return ParseStatus::Err as u32, }; @@ -67,8 +67,8 @@ pub fn op_url_get_serialization(state: &mut OpState) -> String { } /// Parse `href` without a `base_url`. Fills the out `buf` with URL components. -#[op] -pub fn op_url_parse(state: &mut OpState, href: String, buf: &mut [u8]) -> u32 { +#[op(fast)] +pub fn op_url_parse(state: &mut OpState, href: &str, buf: &mut [u32]) -> u32 { parse_url(state, href, None, buf) } @@ -99,15 +99,14 @@ pub fn op_url_parse(state: &mut OpState, href: String, buf: &mut [u8]) -> u32 { #[inline] fn parse_url( state: &mut OpState, - href: String, + href: &str, base_href: Option<&Url>, - buf: &mut [u8], + buf: &mut [u32], ) -> u32 { - match Url::options().base_url(base_href).parse(&href) { + match Url::options().base_url(base_href).parse(href) { Ok(url) => { let inner_url = quirks::internal_components(&url); - let buf: &mut [u32] = as_u32_slice(buf); buf[0] = inner_url.scheme_end; buf[1] = inner_url.username_end; buf[2] = inner_url.host_start; diff --git a/ext/web/02_event.js b/ext/web/02_event.js index d915b5f207..fa1c943328 100644 --- a/ext/web/02_event.js +++ b/ext/web/02_event.js @@ -139,6 +139,8 @@ const _dispatched = Symbol("[[dispatched]]"); const _isTrusted = Symbol("[[isTrusted]]"); const _path = Symbol("[[path]]"); + // internal. + const _skipInternalInit = Symbol("[[skipSlowInit]]"); class Event { constructor(type, eventInitDict = {}) { @@ -152,29 +154,47 @@ this[_isTrusted] = false; this[_path] = []; - webidl.requiredArguments(arguments.length, 1, { - prefix: "Failed to construct 'Event'", - }); - type = webidl.converters.DOMString(type, { - prefix: "Failed to construct 'Event'", - context: "Argument 1", - }); - const eventInit = eventInitConverter(eventInitDict, { - prefix: "Failed to construct 'Event'", - context: "Argument 2", - }); - this[_attributes] = { - type, - ...eventInit, - currentTarget: null, - eventPhase: Event.NONE, - target: null, - timeStamp: DateNow(), - }; - ReflectDefineProperty(this, "isTrusted", { - enumerable: true, - get: isTrusted, - }); + if (!eventInitDict[_skipInternalInit]) { + webidl.requiredArguments(arguments.length, 1, { + prefix: "Failed to construct 'Event'", + }); + type = webidl.converters.DOMString(type, { + prefix: "Failed to construct 'Event'", + context: "Argument 1", + }); + const eventInit = eventInitConverter(eventInitDict, { + prefix: "Failed to construct 'Event'", + context: "Argument 2", + }); + this[_attributes] = { + type, + ...eventInit, + currentTarget: null, + eventPhase: Event.NONE, + target: null, + timeStamp: DateNow(), + }; + // [LegacyUnforgeable] + ReflectDefineProperty(this, "isTrusted", { + enumerable: true, + get: isTrusted, + }); + } else { + this[_attributes] = { + type, + data: eventInitDict.data ?? null, + bubbles: eventInitDict.bubbles ?? false, + cancelable: eventInitDict.cancelable ?? false, + composed: eventInitDict.composed ?? false, + currentTarget: null, + eventPhase: Event.NONE, + target: null, + timeStamp: DateNow(), + }; + // TODO(@littledivy): Not spec compliant but performance is hurt badly + // for users of `_skipInternalInit`. + this.isTrusted = false; + } } [SymbolFor("Deno.privateCustomInspect")](inspect) { @@ -1191,6 +1211,7 @@ bubbles: eventInitDict?.bubbles ?? false, cancelable: eventInitDict?.cancelable ?? false, composed: eventInitDict?.composed ?? false, + [_skipInternalInit]: eventInitDict?.[_skipInternalInit], }); this.data = eventInitDict?.data ?? null; @@ -1481,6 +1502,7 @@ setIsTrusted, setTarget, defineEventHandler, + _skipInternalInit, Event, ErrorEvent, CloseEvent, diff --git a/ext/web/Cargo.toml b/ext/web/Cargo.toml index 82a4b17331..f3b0075c9d 100644 --- a/ext/web/Cargo.toml +++ b/ext/web/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_web" -version = "0.110.0" +version = "0.111.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/web/blob.rs b/ext/web/blob.rs index 7da42e178c..5f19368609 100644 --- a/ext/web/blob.rs +++ b/ext/web/blob.rs @@ -252,9 +252,9 @@ pub fn op_blob_create_object_url( #[op] pub fn op_blob_revoke_object_url( state: &mut deno_core::OpState, - url: String, + url: &str, ) -> Result<(), AnyError> { - let url = Url::parse(&url)?; + let url = Url::parse(url)?; let blob_store = state.borrow::(); blob_store.remove_object_url(&url); Ok(()) diff --git a/ext/web/compression.rs b/ext/web/compression.rs index d2647e4988..05dcf02b19 100644 --- a/ext/web/compression.rs +++ b/ext/web/compression.rs @@ -41,11 +41,11 @@ impl Resource for CompressionResource { #[op] pub fn op_compression_new( state: &mut OpState, - format: String, + format: &str, is_decoder: bool, ) -> ResourceId { let w = Vec::new(); - let inner = match (format.as_str(), is_decoder) { + let inner = match (format, is_decoder) { ("deflate", true) => Inner::DeflateDecoder(ZlibDecoder::new(w)), ("deflate", false) => { Inner::DeflateEncoder(ZlibEncoder::new(w, Compression::default())) diff --git a/ext/web/lib.deno_web.d.ts b/ext/web/lib.deno_web.d.ts index bc1f6b4716..8da12badf1 100644 --- a/ext/web/lib.deno_web.d.ts +++ b/ext/web/lib.deno_web.d.ts @@ -466,30 +466,36 @@ declare class File extends Blob { } /** @category Streams API */ -interface ReadableStreamReadDoneResult { +interface ReadableStreamDefaultReadDoneResult { done: true; - value?: T; + value?: undefined; } /** @category Streams API */ -interface ReadableStreamReadValueResult { +interface ReadableStreamDefaultReadValueResult { done: false; value: T; } /** @category Streams API */ -type ReadableStreamReadResult = - | ReadableStreamReadValueResult - | ReadableStreamReadDoneResult; +type ReadableStreamDefaultReadResult = + | ReadableStreamDefaultReadValueResult + | ReadableStreamDefaultReadDoneResult; /** @category Streams API */ interface ReadableStreamDefaultReader { readonly closed: Promise; cancel(reason?: any): Promise; - read(): Promise>; + read(): Promise>; releaseLock(): void; } +/** @category Streams API */ +declare var ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new (stream: ReadableStream): ReadableStreamDefaultReader; +}; + /** @category Streams API */ interface ReadableStreamBYOBReadDoneResult { done: true; @@ -517,6 +523,12 @@ interface ReadableStreamBYOBReader { releaseLock(): void; } +/** @category Streams API */ +declare var ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new (stream: ReadableStream): ReadableStreamBYOBReader; +}; + /** @category Streams API */ interface ReadableStreamBYOBRequest { readonly view: ArrayBufferView | null; @@ -524,25 +536,6 @@ interface ReadableStreamBYOBRequest { respondWithNewView(view: ArrayBufferView): void; } -/** @category Streams API */ -declare var ReadableStreamDefaultReader: { - prototype: ReadableStreamDefaultReader; - new (stream: ReadableStream): ReadableStreamDefaultReader; -}; - -/** @category Streams API */ -interface ReadableStreamReader { - cancel(): Promise; - read(): Promise>; - releaseLock(): void; -} - -/** @category Streams API */ -declare var ReadableStreamReader: { - prototype: ReadableStreamReader; - new (): ReadableStreamReader; -}; - /** @category Streams API */ interface ReadableByteStreamControllerCallback { (controller: ReadableByteStreamController): void | PromiseLike; diff --git a/ext/web/lib.rs b/ext/web/lib.rs index 85fae2c64b..7c75a9a288 100644 --- a/ext/web/lib.rs +++ b/ext/web/lib.rs @@ -270,7 +270,7 @@ fn op_encoding_decode_single( #[op] fn op_encoding_new_decoder( state: &mut OpState, - label: String, + label: &str, fatal: bool, ignore_bom: bool, ) -> Result { @@ -352,25 +352,43 @@ impl Resource for TextDecoderResource { } } -#[op(v8)] +#[op] fn op_encoding_encode_into( - scope: &mut v8::HandleScope, - input: serde_v8::Value, + input: Cow<'_, str>, buffer: &mut [u8], out_buf: &mut [u32], -) -> Result<(), AnyError> { - let s = v8::Local::::try_from(input.v8_value)?; +) { + // Since `input` is already UTF-8, we can simply find the last UTF-8 code + // point boundary from input that fits in `buffer`, and copy the bytes up to + // that point. + let boundary = if buffer.len() >= input.len() { + input.len() + } else { + let mut boundary = buffer.len(); - let mut nchars = 0; - out_buf[1] = s.write_utf8( - scope, - buffer, - Some(&mut nchars), - v8::WriteOptions::NO_NULL_TERMINATION - | v8::WriteOptions::REPLACE_INVALID_UTF8, - ) as u32; - out_buf[0] = nchars as u32; - Ok(()) + // The maximum length of a UTF-8 code point is 4 bytes. + for _ in 0..4 { + if input.is_char_boundary(boundary) { + break; + } + debug_assert!(boundary > 0); + boundary -= 1; + } + + debug_assert!(input.is_char_boundary(boundary)); + boundary + }; + + buffer[..boundary].copy_from_slice(input[..boundary].as_bytes()); + + // The `read` output parameter is measured in UTF-16 code units. + out_buf[0] = match input { + // Borrowed Cow strings are zero-copy views into the V8 heap. + // Thus, they are guarantee to be SeqOneByteString. + Cow::Borrowed(v) => v[..boundary].len() as u32, + Cow::Owned(v) => v[..boundary].encode_utf16().count() as u32, + }; + out_buf[1] = boundary as u32; } #[op(v8)] @@ -383,7 +401,7 @@ fn op_transfer_arraybuffer<'a>( return Err(type_error("ArrayBuffer is not detachable")); } let bs = ab.get_backing_store(); - ab.detach(v8::undefined(scope).into()); + ab.detach(None); let ab = v8::ArrayBuffer::with_backing_store(scope, &bs); Ok(serde_v8::Value { v8_value: ab.into(), diff --git a/ext/webgpu/Cargo.toml b/ext/webgpu/Cargo.toml index d1b6e18391..6f258fecf4 100644 --- a/ext/webgpu/Cargo.toml +++ b/ext/webgpu/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_webgpu" -version = "0.80.0" +version = "0.81.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/webidl/Cargo.toml b/ext/webidl/Cargo.toml index 3bbdac108b..1677af6456 100644 --- a/ext/webidl/Cargo.toml +++ b/ext/webidl/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_webidl" -version = "0.79.0" +version = "0.80.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/websocket/01_websocket.js b/ext/websocket/01_websocket.js index 2284a0e771..a30a74cada 100644 --- a/ext/websocket/01_websocket.js +++ b/ext/websocket/01_websocket.js @@ -10,8 +10,14 @@ const webidl = window.__bootstrap.webidl; const { HTTP_TOKEN_CODE_POINT_RE } = window.__bootstrap.infra; const { DOMException } = window.__bootstrap.domException; - const { Event, ErrorEvent, CloseEvent, MessageEvent, defineEventHandler } = - window.__bootstrap.event; + const { + Event, + ErrorEvent, + CloseEvent, + MessageEvent, + defineEventHandler, + _skipInternalInit, + } = window.__bootstrap.event; const { EventTarget } = window.__bootstrap.eventTarget; const { Blob, BlobPrototype } = globalThis.__bootstrap.file; const { @@ -440,6 +446,7 @@ const event = new MessageEvent("message", { data, origin: this[_url], + [_skipInternalInit]: true, }); this.dispatchEvent(event); break; diff --git a/ext/websocket/Cargo.toml b/ext/websocket/Cargo.toml index 538c23e284..9e03a3a433 100644 --- a/ext/websocket/Cargo.toml +++ b/ext/websocket/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_websocket" -version = "0.84.0" +version = "0.85.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/websocket/lib.rs b/ext/websocket/lib.rs index 704c699a76..984d39e9dc 100644 --- a/ext/websocket/lib.rs +++ b/ext/websocket/lib.rs @@ -504,9 +504,12 @@ pub fn op_ws_try_send_string( state: &mut OpState, rid: ResourceId, text: String, -) -> Result { - let resource = state.resource_table.get::(rid)?; - resource.try_send(Message::Text(text)) +) -> bool { + let resource = match state.resource_table.get::(rid) { + Ok(resource) => resource, + Err(_) => return false, + }; + resource.try_send(Message::Text(text)).is_ok() } #[op(fast)] @@ -514,9 +517,12 @@ pub fn op_ws_try_send_binary( state: &mut OpState, rid: u32, value: &[u8], -) -> Result { - let resource = state.resource_table.get::(rid)?; - resource.try_send(Message::Binary(value.to_vec())) +) -> bool { + let resource = match state.resource_table.get::(rid) { + Ok(resource) => resource, + Err(_) => return false, + }; + resource.try_send(Message::Binary(value.to_vec())).is_ok() } #[op(deferred)] diff --git a/ext/webstorage/Cargo.toml b/ext/webstorage/Cargo.toml index b191ae2ddd..393e6738c9 100644 --- a/ext/webstorage/Cargo.toml +++ b/ext/webstorage/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_webstorage" -version = "0.74.0" +version = "0.75.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ext/webstorage/lib.rs b/ext/webstorage/lib.rs index 6284a59bc6..58b7c07e43 100644 --- a/ext/webstorage/lib.rs +++ b/ext/webstorage/lib.rs @@ -139,8 +139,8 @@ pub fn op_webstorage_key( #[op] pub fn op_webstorage_set( state: &mut OpState, - key: String, - value: String, + key: &str, + value: &str, persistent: bool, ) -> Result<(), AnyError> { let conn = get_webstorage(state, persistent)?; @@ -184,7 +184,7 @@ pub fn op_webstorage_get( #[op] pub fn op_webstorage_remove( state: &mut OpState, - key_name: String, + key_name: &str, persistent: bool, ) -> Result<(), AnyError> { let conn = get_webstorage(state, persistent)?; diff --git a/ops/Cargo.toml b/ops/Cargo.toml index a6448ce11b..3f1bd51b2a 100644 --- a/ops/Cargo.toml +++ b/ops/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_ops" -version = "0.39.0" +version = "0.40.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/ops/README.md b/ops/README.md index 441b526ca1..39d8606639 100644 --- a/ops/README.md +++ b/ops/README.md @@ -34,8 +34,8 @@ Cases where code is optimized away: The macro will infer and try to auto generate V8 fast API call trait impl for `sync` ops with: -- arguments: integers, bool, `&mut OpState`, `&[u8]`, &mut [u8]`,`&[u32]`,`&mut - [u32]` +- arguments: integers, bool, `&mut OpState`, `&[u8]`, `&mut [u8]`, `&[u32]`, + `&mut [u32]` - return_type: integers, bool The `#[op(fast)]` attribute should be used to enforce fast call generation at @@ -43,3 +43,20 @@ compile time. Trait gen for `async` ops & a ZeroCopyBuf equivalent type is planned and will be added soon. + +### Wasm calls + +The `#[op(wasm)]` attribute should be used for calls expected to be called from +Wasm. This enables the fast call generation and allows seamless `WasmMemory` +integration for generic and fast calls. + +```rust +#[op(wasm)] +pub fn op_args_get( + offset: i32, + buffer_offset: i32, + memory: Option<&[u8]>, // Must be last parameter. Some(..) when entered from Wasm. +) { + // ... +} +``` diff --git a/ops/attrs.rs b/ops/attrs.rs index 95374ef368..4d298d7ed2 100644 --- a/ops/attrs.rs +++ b/ops/attrs.rs @@ -11,6 +11,7 @@ pub struct Attributes { pub is_v8: bool, pub must_be_fast: bool, pub deferred: bool, + pub is_wasm: bool, } impl Parse for Attributes { @@ -20,18 +21,22 @@ impl Parse for Attributes { let vars: Vec<_> = vars.iter().map(Ident::to_string).collect(); let vars: Vec<_> = vars.iter().map(String::as_str).collect(); for var in vars.iter() { - if !["unstable", "v8", "fast", "deferred"].contains(var) { + if !["unstable", "v8", "fast", "deferred", "wasm"].contains(var) { return Err(Error::new( input.span(), - "invalid attribute, expected one of: unstable, v8, fast, deferred", + "invalid attribute, expected one of: unstable, v8, fast, deferred, wasm", )); } } + + let is_wasm = vars.contains(&"wasm"); + Ok(Self { is_unstable: vars.contains(&"unstable"), is_v8: vars.contains(&"v8"), - must_be_fast: vars.contains(&"fast"), deferred: vars.contains(&"deferred"), + must_be_fast: is_wasm || vars.contains(&"fast"), + is_wasm, }) } } diff --git a/ops/fast_call.rs b/ops/fast_call.rs index c6daa5339a..1d6bfa1fa2 100644 --- a/ops/fast_call.rs +++ b/ops/fast_call.rs @@ -139,12 +139,22 @@ pub(crate) fn generate( // Apply *hard* optimizer hints. if optimizer.has_fast_callback_option + || optimizer.has_wasm_memory || optimizer.needs_opstate() || optimizer.is_async + || optimizer.needs_fast_callback_option { - fast_fn_inputs.push(parse_quote! { + let decl = parse_quote! { fast_api_callback_options: *mut #core::v8::fast_api::FastApiCallbackOptions - }); + }; + + if optimizer.has_fast_callback_option || optimizer.has_wasm_memory { + // Replace last parameter. + assert!(fast_fn_inputs.pop().is_some()); + fast_fn_inputs.push(decl); + } else { + fast_fn_inputs.push(decl); + } input_variants.push(q!({ CallbackOptions })); } @@ -162,14 +172,11 @@ pub(crate) fn generate( let mut output_transforms = q!({}); - if optimizer.needs_opstate() || optimizer.is_async { - // Grab the op_state identifier, the first one. ¯\_(ツ)_/¯ - let op_state = match idents.first() { - Some(ident) if optimizer.has_opstate_in_parameters() => ident.clone(), - // fn op_foo() -> Result<...> - _ => Ident::new("op_state", Span::call_site()), - }; - + if optimizer.needs_opstate() + || optimizer.is_async + || optimizer.has_fast_callback_option + || optimizer.has_wasm_memory + { // Dark arts 🪄 ✨ // // - V8 calling convention guarantees that the callback options pointer is non-null. @@ -179,13 +186,27 @@ pub(crate) fn generate( let prelude = q!({ let __opts: &mut v8::fast_api::FastApiCallbackOptions = unsafe { &mut *fast_api_callback_options }; + }); + + pre_transforms.push_tokens(&prelude); + } + + if optimizer.needs_opstate() || optimizer.is_async { + // Grab the op_state identifier, the first one. ¯\_(ツ)_/¯ + let op_state = match idents.first() { + Some(ident) if optimizer.has_opstate_in_parameters() => ident.clone(), + // fn op_foo() -> Result<...> + _ => Ident::new("op_state", Span::call_site()), + }; + + let ctx = q!({ let __ctx = unsafe { &*(v8::Local::::cast(unsafe { __opts.data.data }).value() as *const _ops::OpCtx) }; }); - pre_transforms.push_tokens(&prelude); + pre_transforms.push_tokens(&ctx); pre_transforms.push_tokens(&match optimizer.is_async { false => q!( Vars { @@ -382,7 +403,9 @@ fn q_fast_ty(v: &FastValue) -> Quote { FastValue::F64 => q!({ f64 }), FastValue::Bool => q!({ bool }), FastValue::V8Value => q!({ v8::Local }), - FastValue::Uint8Array | FastValue::Uint32Array => unreachable!(), + FastValue::Uint8Array + | FastValue::Uint32Array + | FastValue::SeqOneByteString => unreachable!(), } } @@ -400,6 +423,7 @@ fn q_fast_ty_variant(v: &FastValue) -> Quote { FastValue::V8Value => q!({ V8Value }), FastValue::Uint8Array => q!({ TypedArray(CType::Uint8) }), FastValue::Uint32Array => q!({ TypedArray(CType::Uint32) }), + FastValue::SeqOneByteString => q!({ SeqOneByteString }), } } @@ -422,49 +446,3 @@ fn exclude_lifetime_params( where_clause: None, }) } - -#[cfg(test)] -mod tests { - use super::*; - use crate::{Attributes, Op}; - use std::path::PathBuf; - - #[testing_macros::fixture("optimizer_tests/**/*.rs")] - fn test_fast_call_codegen(input: PathBuf) { - let update_expected = std::env::var("UPDATE_EXPECTED").is_ok(); - let core = quote!(deno_core); - - let source = - std::fs::read_to_string(&input).expect("Failed to read test file"); - - let mut attrs = Attributes::default(); - if source.contains("// @test-attr:fast") { - attrs.must_be_fast = true; - } - - let item = syn::parse_str(&source).expect("Failed to parse test file"); - let mut op = Op::new(item, attrs); - let mut optimizer = Optimizer::new(); - if optimizer.analyze(&mut op).is_err() { - // Tested by optimizer::test tests. - return; - } - - let expected = std::fs::read_to_string(input.with_extension("out")) - .expect("Failed to read expected file"); - - let FastImplItems { - impl_and_fn: actual, - .. - } = generate(&core, &mut optimizer, &op.item); - // Validate syntax tree. - let tree = syn::parse2(actual).unwrap(); - let actual = prettyplease::unparse(&tree); - if update_expected { - std::fs::write(input.with_extension("out"), actual) - .expect("Failed to write expected file"); - } else { - assert_eq!(actual, expected); - } - } -} diff --git a/ops/lib.rs b/ops/lib.rs index efd47f8e52..7fa800b14c 100644 --- a/ops/lib.rs +++ b/ops/lib.rs @@ -76,10 +76,11 @@ impl Op { fn gen(mut self) -> TokenStream2 { let mut optimizer = Optimizer::new(); match optimizer.analyze(&mut self) { - Ok(_) | Err(BailoutReason::MustBeSingleSegment) => {} - Err(BailoutReason::FastUnsupportedParamType) => { + Err(BailoutReason::MustBeSingleSegment) + | Err(BailoutReason::FastUnsupportedParamType) => { optimizer.fast_compatible = false; } + _ => {} }; let Self { @@ -192,7 +193,8 @@ fn codegen_v8_async( .inputs .iter() .map_while(|a| { - (if is_v8 { scope_arg(a) } else { None }).or_else(|| opstate_arg(a)) + (if is_v8 { scope_arg(a) } else { None }) + .or_else(|| rc_refcell_opstate_arg(a)) }) .collect::>(); let rust_i0 = special_args.len(); @@ -290,6 +292,16 @@ fn opstate_arg(arg: &FnArg) -> Option { } } +fn rc_refcell_opstate_arg(arg: &FnArg) -> Option { + match arg { + arg if is_rc_refcell_opstate(arg) => Some(quote! { ctx.state.clone(), }), + arg if is_mut_ref_opstate(arg) => Some( + quote! { compile_error!("mutable opstate is not supported in async ops"), }, + ), + _ => None, + } +} + /// Generate the body of a v8 func for a sync op fn codegen_v8_sync( core: &TokenStream2, @@ -385,7 +397,9 @@ fn codegen_arg( let ident = quote::format_ident!("{name}"); let (pat, ty) = match arg { syn::FnArg::Typed(pat) => { - if is_optional_fast_callback_option(&pat.ty) { + if is_optional_fast_callback_option(&pat.ty) + || is_optional_wasm_memory(&pat.ty) + { return quote! { let #ident = None; }; } (&pat.pat, &pat.ty) @@ -397,7 +411,12 @@ fn codegen_arg( return quote! { let #ident = (); }; } // Fast path for `String` - if is_string(&**ty) { + if let Some(is_ref) = is_string(&**ty) { + let ref_block = if is_ref { + quote! { let #ident = #ident.as_ref(); } + } else { + quote! {} + }; return quote! { let #ident = match #core::v8::Local::<#core::v8::String>::try_from(args.get(#idx as i32)) { Ok(v8_string) => #core::serde_v8::to_utf8(v8_string, scope), @@ -405,6 +424,18 @@ fn codegen_arg( return #core::_ops::throw_type_error(scope, format!("Expected string at position {}", #idx)); } }; + #ref_block + }; + } + // Fast path for `Cow<'_, str>` + if is_cow_str(&**ty) { + return quote! { + let #ident = match #core::v8::Local::<#core::v8::String>::try_from(args.get(#idx as i32)) { + Ok(v8_string) => ::std::borrow::Cow::Owned(#core::serde_v8::to_utf8(v8_string, scope)), + Err(_) => { + return #core::_ops::throw_type_error(scope, format!("Expected string at position {}", #idx)); + } + }; }; } // Fast path for `Option` @@ -432,6 +463,13 @@ fn codegen_arg( }; } } + // Fast path for `*const u8` + if is_ptr_u8(&**ty) { + let blk = codegen_u8_ptr(core, idx); + return quote! { + let #ident = #blk; + }; + } // Otherwise deserialize it via serde_v8 quote! { let #ident = args.get(#idx as i32); @@ -450,11 +488,14 @@ fn codegen_u8_slice(core: &TokenStream2, idx: usize) -> TokenStream2 { let value = args.get(#idx as i32); match #core::v8::Local::<#core::v8::ArrayBuffer>::try_from(value) { Ok(b) => { - // Handles detached buffers. let byte_length = b.byte_length(); - let store = b.data() as *mut u8; - // SAFETY: rust guarantees that lifetime of slice is no longer than the call. - unsafe { ::std::slice::from_raw_parts_mut(store, byte_length) } + if let Some(data) = b.data() { + let store = data.cast::().as_ptr(); + // SAFETY: rust guarantees that lifetime of slice is no longer than the call. + unsafe { ::std::slice::from_raw_parts_mut(store, byte_length) } + } else { + &mut [] + } }, Err(_) => { if let Ok(view) = #core::v8::Local::<#core::v8::ArrayBufferView>::try_from(value) { @@ -466,9 +507,13 @@ fn codegen_u8_slice(core: &TokenStream2, idx: usize) -> TokenStream2 { return #core::_ops::throw_type_error(scope, format!("Expected ArrayBufferView at position {}", #idx)); } }; - let store = buffer.data() as *mut u8; - // SAFETY: rust guarantees that lifetime of slice is no longer than the call. - unsafe { ::std::slice::from_raw_parts_mut(store.add(offset), len) } + if let Some(data) = buffer.data() { + let store = data.cast::().as_ptr(); + // SAFETY: rust guarantees that lifetime of slice is no longer than the call. + unsafe { ::std::slice::from_raw_parts_mut(store.add(offset), len) } + } else { + &mut [] + } } else { return #core::_ops::throw_type_error(scope, format!("Expected ArrayBufferView at position {}", #idx)); } @@ -477,6 +522,40 @@ fn codegen_u8_slice(core: &TokenStream2, idx: usize) -> TokenStream2 { } } +fn codegen_u8_ptr(core: &TokenStream2, idx: usize) -> TokenStream2 { + quote! {{ + let value = args.get(#idx as i32); + match #core::v8::Local::<#core::v8::ArrayBuffer>::try_from(value) { + Ok(b) => { + if let Some(data) = b.data() { + data.cast::().as_ptr() + } else { + std::ptr::null::() + } + }, + Err(_) => { + if let Ok(view) = #core::v8::Local::<#core::v8::ArrayBufferView>::try_from(value) { + let offset = view.byte_offset(); + let buffer = match view.buffer(scope) { + Some(v) => v, + None => { + return #core::_ops::throw_type_error(scope, format!("Expected ArrayBufferView at position {}", #idx)); + } + }; + let store = if let Some(data) = buffer.data() { + data.cast::().as_ptr() + } else { + std::ptr::null_mut::() + }; + unsafe { store.add(offset) } + } else { + return #core::_ops::throw_type_error(scope, format!("Expected ArrayBufferView at position {}", #idx)); + } + } + } + }} +} + fn codegen_u32_mut_slice(core: &TokenStream2, idx: usize) -> TokenStream2 { quote! { if let Ok(view) = #core::v8::Local::<#core::v8::Uint32Array>::try_from(args.get(#idx as i32)) { @@ -487,9 +566,13 @@ fn codegen_u32_mut_slice(core: &TokenStream2, idx: usize) -> TokenStream2 { return #core::_ops::throw_type_error(scope, format!("Expected Uint32Array at position {}", #idx)); } }; - let store = buffer.data() as *mut u8; - // SAFETY: buffer from Uint32Array. Rust guarantees that lifetime of slice is no longer than the call. - unsafe { ::std::slice::from_raw_parts_mut(store.add(offset) as *mut u32, len / 4) } + if let Some(data) = buffer.data() { + let store = data.cast::().as_ptr(); + // SAFETY: buffer from Uint32Array. Rust guarantees that lifetime of slice is no longer than the call. + unsafe { ::std::slice::from_raw_parts_mut(store.add(offset) as *mut u32, len / 4) } + } else { + &mut [] + } } else { return #core::_ops::throw_type_error(scope, format!("Expected Uint32Array at position {}", #idx)); } @@ -563,14 +646,25 @@ fn is_result(ty: impl ToTokens) -> bool { } } -fn is_string(ty: impl ToTokens) -> bool { - tokens(ty) == "String" +fn is_string(ty: impl ToTokens) -> Option { + let toks = tokens(ty); + if toks == "String" { + return Some(false); + } + if toks == "& str" { + return Some(true); + } + None } fn is_option_string(ty: impl ToTokens) -> bool { tokens(ty) == "Option < String >" } +fn is_cow_str(ty: impl ToTokens) -> bool { + tokens(&ty).starts_with("Cow <") && tokens(&ty).ends_with("str >") +} + enum SliceType { U8, U8Mut, @@ -602,10 +696,18 @@ fn is_u32_slice_mut(ty: impl ToTokens) -> bool { tokens(ty) == "& mut [u32]" } +fn is_ptr_u8(ty: impl ToTokens) -> bool { + tokens(ty) == "* const u8" +} + fn is_optional_fast_callback_option(ty: impl ToTokens) -> bool { tokens(&ty).contains("Option < & mut FastApiCallbackOptions") } +fn is_optional_wasm_memory(ty: impl ToTokens) -> bool { + tokens(&ty).contains("Option < & mut [u8]") +} + /// Detects if the type can be set using `rv.set_uint32` fast path fn is_u32_rv(ty: impl ToTokens) -> bool { ["u32", "u8", "u16"].iter().any(|&s| tokens(&ty) == s) || is_resource_id(&ty) @@ -669,3 +771,43 @@ fn exclude_lifetime_params( .cloned() .collect::>() } + +#[cfg(test)] +mod tests { + use crate::{Attributes, Op}; + use std::path::PathBuf; + + #[testing_macros::fixture("optimizer_tests/**/*.rs")] + fn test_codegen(input: PathBuf) { + let update_expected = std::env::var("UPDATE_EXPECTED").is_ok(); + + let source = + std::fs::read_to_string(&input).expect("Failed to read test file"); + + let mut attrs = Attributes::default(); + if source.contains("// @test-attr:fast") { + attrs.must_be_fast = true; + } + if source.contains("// @test-attr:wasm") { + attrs.is_wasm = true; + attrs.must_be_fast = true; + } + + let item = syn::parse_str(&source).expect("Failed to parse test file"); + let op = Op::new(item, attrs); + + let expected = std::fs::read_to_string(input.with_extension("out")) + .expect("Failed to read expected output file"); + + let actual = op.gen(); + // Validate syntax tree. + let tree = syn::parse2(actual).unwrap(); + let actual = prettyplease::unparse(&tree); + if update_expected { + std::fs::write(input.with_extension("out"), actual) + .expect("Failed to write expected file"); + } else { + assert_eq!(actual, expected); + } + } +} diff --git a/ops/optimizer.rs b/ops/optimizer.rs index 3ca69a814c..99de4b4240 100644 --- a/ops/optimizer.rs +++ b/ops/optimizer.rs @@ -2,14 +2,14 @@ use crate::Op; use pmutil::{q, Quote}; use proc_macro2::TokenStream; -use std::collections::HashMap; +use std::collections::BTreeMap; use std::fmt::Debug; use std::fmt::Formatter; use syn::{ parse_quote, punctuated::Punctuated, token::Colon2, AngleBracketedGenericArguments, FnArg, GenericArgument, PatType, Path, - PathArguments, PathSegment, ReturnType, Signature, Type, TypePath, - TypeReference, TypeSlice, + PathArguments, PathSegment, ReturnType, Signature, Type, TypePath, TypePtr, + TypeReference, TypeSlice, TypeTuple, }; #[derive(Debug)] @@ -19,12 +19,22 @@ pub(crate) enum BailoutReason { FastUnsupportedParamType, } +#[derive(Debug, PartialEq)] +enum StringType { + Cow, + Ref, + Owned, +} + #[derive(Debug, PartialEq)] enum TransformKind { // serde_v8::Value V8Value, SliceU32(bool), SliceU8(bool), + SeqOneByteString(StringType), + PtrU8, + WasmMemory, } impl Transform { @@ -48,6 +58,27 @@ impl Transform { index, } } + + fn seq_one_byte_string(index: usize, is_ref: StringType) -> Self { + Transform { + kind: TransformKind::SeqOneByteString(is_ref), + index, + } + } + + fn wasm_memory(index: usize) -> Self { + Transform { + kind: TransformKind::WasmMemory, + index, + } + } + + fn u8_ptr(index: usize) -> Self { + Transform { + kind: TransformKind::PtrU8, + index, + } + } } #[derive(Debug, PartialEq)] @@ -116,6 +147,46 @@ impl Transform { }; }) } + // &str + TransformKind::SeqOneByteString(str_ty) => { + *ty = parse_quote! { *const #core::v8::fast_api::FastApiOneByteString }; + match str_ty { + StringType::Ref => q!(Vars { var: &ident }, { + let var = unsafe { &*var }.as_str(); + }), + StringType::Cow => q!(Vars { var: &ident }, { + let var = ::std::borrow::Cow::Borrowed(unsafe { &*var }.as_str()); + }), + StringType::Owned => q!(Vars { var: &ident }, { + let var = unsafe { &*var }.as_str().to_owned(); + }), + } + } + TransformKind::WasmMemory => { + // Note: `ty` is correctly set to __opts by the fast call tier. + q!(Vars { var: &ident, core }, { + let var = unsafe { + &*(__opts.wasm_memory + as *const core::v8::fast_api::FastApiTypedArray) + } + .get_storage_if_aligned(); + }) + } + // *const u8 + TransformKind::PtrU8 => { + *ty = + parse_quote! { *const #core::v8::fast_api::FastApiTypedArray }; + + q!(Vars { var: &ident }, { + let var = match unsafe { &*var }.get_storage_if_aligned() { + Some(v) => v.as_ptr(), + None => { + unsafe { &mut *fast_api_callback_options }.fallback = true; + return Default::default(); + } + }; + }) + } } } } @@ -157,6 +228,7 @@ pub(crate) enum FastValue { V8Value, Uint8Array, Uint32Array, + SeqOneByteString, } impl Default for FastValue { @@ -173,12 +245,17 @@ pub(crate) struct Optimizer { pub(crate) has_rc_opstate: bool, + // Do we need an explict FastApiCallbackOptions argument? pub(crate) has_fast_callback_option: bool, + // Do we depend on FastApiCallbackOptions? + pub(crate) needs_fast_callback_option: bool, + + pub(crate) has_wasm_memory: bool, pub(crate) fast_result: Option, pub(crate) fast_parameters: Vec, - pub(crate) transforms: HashMap, + pub(crate) transforms: BTreeMap, pub(crate) fast_compatible: bool, pub(crate) is_async: bool, @@ -195,6 +272,11 @@ impl Debug for Optimizer { "has_fast_callback_option: {}", self.has_fast_callback_option )?; + writeln!( + f, + "needs_fast_callback_option: {}", + self.needs_fast_callback_option + )?; writeln!(f, "fast_result: {:?}", self.fast_result)?; writeln!(f, "fast_parameters: {:?}", self.fast_parameters)?; writeln!(f, "transforms: {:?}", self.transforms)?; @@ -231,6 +313,9 @@ impl Optimizer { self.is_async = op.is_async; self.fast_compatible = true; + // Just assume for now. We will validate later. + self.has_wasm_memory = op.attrs.is_wasm; + let sig = &op.item.sig; // Analyze return type @@ -275,6 +360,9 @@ impl Optimizer { fn analyze_return_type(&mut self, ty: &Type) -> Result<(), BailoutReason> { match ty { + Type::Tuple(TypeTuple { elems, .. }) if elems.is_empty() => { + self.fast_result = Some(FastValue::Void); + } Type::Path(TypePath { path: Path { segments, .. }, .. @@ -310,6 +398,14 @@ impl Optimizer { self.fast_compatible = false; return Err(BailoutReason::FastUnsupportedParamType); } + Some(GenericArgument::Type(Type::Tuple(TypeTuple { + elems, + .. + }))) + if elems.is_empty() => + { + self.fast_result = Some(FastValue::Void); + } _ => return Err(BailoutReason::FastUnsupportedParamType), } } @@ -377,22 +473,51 @@ impl Optimizer { TypeReference { elem, .. }, ))) = args.last() { - if let Type::Path(TypePath { + if self.has_wasm_memory { + // -> Option<&mut [u8]> + if let Type::Slice(TypeSlice { elem, .. }) = &**elem { + if let Type::Path(TypePath { + path: Path { segments, .. }, + .. + }) = &**elem + { + let segment = single_segment(segments)?; + + match segment { + // Is `T` a u8? + PathSegment { ident, .. } if ident == "u8" => { + self.needs_fast_callback_option = true; + assert!(self + .transforms + .insert(index, Transform::wasm_memory(index)) + .is_none()); + } + _ => { + return Err(BailoutReason::FastUnsupportedParamType) + } + } + } + } + } else if let Type::Path(TypePath { path: Path { segments, .. }, .. }) = &**elem { let segment = single_segment(segments)?; match segment { - // Is `T` a FastApiCallbackOption? + // Is `T` a FastApiCallbackOptions? PathSegment { ident, .. } - if ident == "FastApiCallbackOption" => + if ident == "FastApiCallbackOptions" => { self.has_fast_callback_option = true; } - _ => {} + _ => return Err(BailoutReason::FastUnsupportedParamType), } + } else { + return Err(BailoutReason::FastUnsupportedParamType); } + } else { + return Err(BailoutReason::FastUnsupportedParamType); } } } @@ -456,10 +581,58 @@ impl Optimizer { } } } + // Cow<'_, str> + PathSegment { + ident, arguments, .. + } if ident == "Cow" => { + if let PathArguments::AngleBracketed( + AngleBracketedGenericArguments { args, .. }, + ) = arguments + { + assert_eq!(args.len(), 2); + + let ty = &args[1]; + match ty { + GenericArgument::Type(Type::Path(TypePath { + path: Path { segments, .. }, + .. + })) => { + let segment = single_segment(segments)?; + match segment { + PathSegment { ident, .. } if ident == "str" => { + self.fast_parameters.push(FastValue::SeqOneByteString); + assert!(self + .transforms + .insert( + index, + Transform::seq_one_byte_string( + index, + StringType::Cow + ) + ) + .is_none()); + } + _ => return Err(BailoutReason::FastUnsupportedParamType), + } + } + _ => return Err(BailoutReason::FastUnsupportedParamType), + } + } + } // Is `T` a fast scalar? PathSegment { ident, .. } => { if let Some(val) = get_fast_scalar(ident.to_string().as_str()) { self.fast_parameters.push(val); + } else if ident == "String" { + // Is `T` an owned String? + self.fast_parameters.push(FastValue::SeqOneByteString); + assert!(self + .transforms + .insert( + index, + Transform::seq_one_byte_string(index, StringType::Owned) + ) + .is_none()); } else { return Err(BailoutReason::FastUnsupportedParamType); } @@ -477,9 +650,22 @@ impl Optimizer { let segment = single_segment(segments)?; match segment { // Is `T` a OpState? - PathSegment { ident, .. } if ident == "OpState" => { + PathSegment { ident, .. } + if ident == "OpState" && !self.is_async => + { self.has_ref_opstate = true; } + // Is `T` a str? + PathSegment { ident, .. } if ident == "str" => { + self.fast_parameters.push(FastValue::SeqOneByteString); + assert!(self + .transforms + .insert( + index, + Transform::seq_one_byte_string(index, StringType::Ref) + ) + .is_none()); + } _ => return Err(BailoutReason::FastUnsupportedParamType), } } @@ -494,7 +680,7 @@ impl Optimizer { match segment { // Is `T` a u8? PathSegment { ident, .. } if ident == "u8" => { - self.has_fast_callback_option = true; + self.needs_fast_callback_option = true; self.fast_parameters.push(FastValue::Uint8Array); assert!(self .transforms @@ -503,7 +689,7 @@ impl Optimizer { } // Is `T` a u32? PathSegment { ident, .. } if ident == "u32" => { - self.has_fast_callback_option = true; + self.needs_fast_callback_option = true; self.fast_parameters.push(FastValue::Uint32Array); assert!(self .transforms @@ -517,6 +703,32 @@ impl Optimizer { }, _ => return Err(BailoutReason::FastUnsupportedParamType), }, + // *const T + Type::Ptr(TypePtr { + elem, + const_token: Some(_), + .. + }) => match &**elem { + Type::Path(TypePath { + path: Path { segments, .. }, + .. + }) => { + let segment = single_segment(segments)?; + match segment { + // Is `T` a u8? + PathSegment { ident, .. } if ident == "u8" => { + self.needs_fast_callback_option = true; + self.fast_parameters.push(FastValue::Uint8Array); + assert!(self + .transforms + .insert(index, Transform::u8_ptr(index)) + .is_none()); + } + _ => return Err(BailoutReason::FastUnsupportedParamType), + } + } + _ => return Err(BailoutReason::FastUnsupportedParamType), + }, _ => return Err(BailoutReason::FastUnsupportedParamType), }, _ => return Err(BailoutReason::FastUnsupportedParamType), @@ -582,6 +794,10 @@ mod tests { .expect("Failed to read expected file"); let mut attrs = Attributes::default(); + if source.contains("// @test-attr:wasm") { + attrs.must_be_fast = true; + attrs.is_wasm = true; + } if source.contains("// @test-attr:fast") { attrs.must_be_fast = true; } diff --git a/ops/optimizer_tests/async_nop.expected b/ops/optimizer_tests/async_nop.expected index 78c161e8c6..42a1180bd8 100644 --- a/ops/optimizer_tests/async_nop.expected +++ b/ops/optimizer_tests/async_nop.expected @@ -3,6 +3,7 @@ returns_result: false has_ref_opstate: false has_rc_opstate: false has_fast_callback_option: false +needs_fast_callback_option: false fast_result: Some(Void) fast_parameters: [V8Value, I32] transforms: {} diff --git a/ops/optimizer_tests/async_nop.out b/ops/optimizer_tests/async_nop.out index 901b8a2259..08f7a87a2c 100644 --- a/ops/optimizer_tests/async_nop.out +++ b/ops/optimizer_tests/async_nop.out @@ -1,3 +1,81 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_void_async::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_void_async; +#[doc(hidden)] +impl op_void_async { + pub fn name() -> &'static str { + stringify!(op_void_async) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_void_async_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: true, + is_unstable: false, + is_v8: false, + argc: 0usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + async fn call() {} + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + use deno_core::futures::FutureExt; + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let op_id = ctx.id; + let promise_id = args.get(0); + let promise_id = deno_core::v8::Local::< + deno_core::v8::Integer, + >::try_from(promise_id) + .map(|l| l.value() as deno_core::PromiseId) + .map_err(deno_core::anyhow::Error::from); + let promise_id: deno_core::PromiseId = match promise_id { + Ok(promise_id) => promise_id, + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!("invalid promise id: {}", err), + ); + return; + } + }; + let get_class = { + let state = ::std::cell::RefCell::borrow(&ctx.state); + state.tracker.track_async(op_id); + state.get_error_class_fn + }; + deno_core::_ops::queue_async_op( + ctx, + scope, + false, + async move { + let result = Self::call().await; + let result = Ok(result); + (promise_id, op_id, deno_core::_ops::to_op_result(get_class, result)) + }, + ); + } +} struct op_void_async_fast { _phantom: ::std::marker::PhantomData<()>, } diff --git a/ops/optimizer_tests/async_result.expected b/ops/optimizer_tests/async_result.expected index dcd9cd1e36..be2e79ac03 100644 --- a/ops/optimizer_tests/async_result.expected +++ b/ops/optimizer_tests/async_result.expected @@ -2,7 +2,8 @@ returns_result: true has_ref_opstate: false has_rc_opstate: true -has_fast_callback_option: true +has_fast_callback_option: false +needs_fast_callback_option: true fast_result: None fast_parameters: [V8Value, I32, U32, Uint8Array] transforms: {2: Transform { kind: SliceU8(true), index: 2 }} diff --git a/ops/optimizer_tests/async_result.out b/ops/optimizer_tests/async_result.out index d312fde732..b9719d22af 100644 --- a/ops/optimizer_tests/async_result.out +++ b/ops/optimizer_tests/async_result.out @@ -1,3 +1,140 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_read::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_read; +#[doc(hidden)] +impl op_read { + pub fn name() -> &'static str { + stringify!(op_read) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_read_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: true, + is_unstable: false, + is_v8: false, + argc: 2usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + async fn call( + state: Rc>, + rid: ResourceId, + buf: &mut [u8], + ) -> Result {} + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + use deno_core::futures::FutureExt; + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let op_id = ctx.id; + let promise_id = args.get(0); + let promise_id = deno_core::v8::Local::< + deno_core::v8::Integer, + >::try_from(promise_id) + .map(|l| l.value() as deno_core::PromiseId) + .map_err(deno_core::anyhow::Error::from); + let promise_id: deno_core::PromiseId = match promise_id { + Ok(promise_id) => promise_id, + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!("invalid promise id: {}", err), + ); + return; + } + }; + let arg_0 = args.get(1usize as i32); + let arg_0 = match deno_core::serde_v8::from_v8(scope, arg_0) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 1usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let arg_1 = { + let value = args.get(2usize as i32); + match deno_core::v8::Local::::try_from(value) { + Ok(b) => { + let byte_length = b.byte_length(); + if let Some(data) = b.data() { + let store = data.cast::().as_ptr(); + unsafe { ::std::slice::from_raw_parts_mut(store, byte_length) } + } else { + &mut [] + } + } + Err(_) => { + if let Ok(view) + = deno_core::v8::Local::< + deno_core::v8::ArrayBufferView, + >::try_from(value) { + let len = view.byte_length(); + let offset = view.byte_offset(); + let buffer = match view.buffer(scope) { + Some(v) => v, + None => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected ArrayBufferView at position {}", 2usize), + ); + } + }; + if let Some(data) = buffer.data() { + let store = data.cast::().as_ptr(); + unsafe { + ::std::slice::from_raw_parts_mut(store.add(offset), len) + } + } else { + &mut [] + } + } else { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected ArrayBufferView at position {}", 2usize), + ); + } + } + } + }; + let get_class = { + let state = ::std::cell::RefCell::borrow(&ctx.state); + state.tracker.track_async(op_id); + state.get_error_class_fn + }; + deno_core::_ops::queue_async_op( + ctx, + scope, + false, + async move { + let result = Self::call(ctx.state.clone(), arg_0, arg_1).await; + (promise_id, op_id, deno_core::_ops::to_op_result(get_class, result)) + }, + ); + } +} struct op_read_fast { _phantom: ::std::marker::PhantomData<()>, } diff --git a/ops/optimizer_tests/callback_options.expected b/ops/optimizer_tests/callback_options.expected index b309ab987c..245fdfd55d 100644 --- a/ops/optimizer_tests/callback_options.expected +++ b/ops/optimizer_tests/callback_options.expected @@ -2,7 +2,8 @@ returns_result: false has_ref_opstate: false has_rc_opstate: false -has_fast_callback_option: false +has_fast_callback_option: true +needs_fast_callback_option: false fast_result: Some(Void) fast_parameters: [V8Value] transforms: {} diff --git a/ops/optimizer_tests/callback_options.out b/ops/optimizer_tests/callback_options.out index 426fe0c4aa..81745375d3 100644 --- a/ops/optimizer_tests/callback_options.out +++ b/ops/optimizer_tests/callback_options.out @@ -1,3 +1,56 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_fallback::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_fallback; +#[doc(hidden)] +impl op_fallback { + pub fn name() -> &'static str { + stringify!(op_fallback) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_fallback_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(options: Option<&mut FastApiCallbackOptions>) { + if let Some(options) = options { + options.fallback = true; + } + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = None; + let result = Self::call(arg_0); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + } +} struct op_fallback_fast { _phantom: ::std::marker::PhantomData<()>, } @@ -8,7 +61,7 @@ impl<'scope> deno_core::v8::fast_api::FastFunction for op_fallback_fast { fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { use deno_core::v8::fast_api::Type::*; use deno_core::v8::fast_api::CType; - &[V8Value] + &[V8Value, CallbackOptions] } fn return_type(&self) -> deno_core::v8::fast_api::CType { deno_core::v8::fast_api::CType::Void @@ -16,10 +69,13 @@ impl<'scope> deno_core::v8::fast_api::FastFunction for op_fallback_fast { } fn op_fallback_fast_fn<'scope>( _: deno_core::v8::Local, - options: Option<&mut FastApiCallbackOptions>, + fast_api_callback_options: *mut deno_core::v8::fast_api::FastApiCallbackOptions, ) -> () { use deno_core::v8; use deno_core::_ops; + let __opts: &mut v8::fast_api::FastApiCallbackOptions = unsafe { + &mut *fast_api_callback_options + }; let result = op_fallback::call(options); result } diff --git a/ops/optimizer_tests/cow_str.expected b/ops/optimizer_tests/cow_str.expected new file mode 100644 index 0000000000..8b28965bad --- /dev/null +++ b/ops/optimizer_tests/cow_str.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: false +has_ref_opstate: false +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: false +fast_result: Some(Void) +fast_parameters: [V8Value, SeqOneByteString] +transforms: {0: Transform { kind: SeqOneByteString(Cow), index: 0 }} +is_async: false +fast_compatible: true diff --git a/ops/optimizer_tests/cow_str.out b/ops/optimizer_tests/cow_str.out new file mode 100644 index 0000000000..da405f451d --- /dev/null +++ b/ops/optimizer_tests/cow_str.out @@ -0,0 +1,87 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_cow_str::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_cow_str; +#[doc(hidden)] +impl op_cow_str { + pub fn name() -> &'static str { + stringify!(op_cow_str) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_cow_str_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(c: Cow<'_, str>) {} + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = match deno_core::v8::Local::< + deno_core::v8::String, + >::try_from(args.get(0usize as i32)) { + Ok(v8_string) => { + ::std::borrow::Cow::Owned(deno_core::serde_v8::to_utf8(v8_string, scope)) + } + Err(_) => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected string at position {}", 0usize), + ); + } + }; + let result = Self::call(arg_0); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + } +} +struct op_cow_str_fast { + _phantom: ::std::marker::PhantomData<()>, +} +impl<'scope> deno_core::v8::fast_api::FastFunction for op_cow_str_fast { + fn function(&self) -> *const ::std::ffi::c_void { + op_cow_str_fast_fn as *const ::std::ffi::c_void + } + fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { + use deno_core::v8::fast_api::Type::*; + use deno_core::v8::fast_api::CType; + &[V8Value, SeqOneByteString] + } + fn return_type(&self) -> deno_core::v8::fast_api::CType { + deno_core::v8::fast_api::CType::Void + } +} +fn op_cow_str_fast_fn<'scope>( + _: deno_core::v8::Local, + c: *const deno_core::v8::fast_api::FastApiOneByteString, +) -> () { + use deno_core::v8; + use deno_core::_ops; + let c = ::std::borrow::Cow::Borrowed(unsafe { &*c }.as_str()); + let result = op_cow_str::call(c); + result +} diff --git a/ops/optimizer_tests/cow_str.rs b/ops/optimizer_tests/cow_str.rs new file mode 100644 index 0000000000..b7214bdc7e --- /dev/null +++ b/ops/optimizer_tests/cow_str.rs @@ -0,0 +1,3 @@ +fn op_cow_str(c: Cow<'_, str>) { + // ... +} diff --git a/ops/optimizer_tests/incompatible_1.out b/ops/optimizer_tests/incompatible_1.out new file mode 100644 index 0000000000..92cf4a5764 --- /dev/null +++ b/ops/optimizer_tests/incompatible_1.out @@ -0,0 +1,71 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_sync_serialize_object_with_numbers_as_keys::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_sync_serialize_object_with_numbers_as_keys; +#[doc(hidden)] +impl op_sync_serialize_object_with_numbers_as_keys { + pub fn name() -> &'static str { + stringify!(op_sync_serialize_object_with_numbers_as_keys) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: None, + is_async: false, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(value: serde_json::Value) -> Result<(), Error> { + assert_eq!( + value.to_string(), r#"{"lines":{"100":{"unit":"m"},"200":{"unit":"cm"}}}"# + ); + Ok(()) + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = args.get(0usize as i32); + let arg_0 = match deno_core::serde_v8::from_v8(scope, arg_0) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 0usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let result = Self::call(arg_0); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match result { + Ok(result) => {} + Err(err) => { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + } + }; + } +} diff --git a/ops/optimizer_tests/issue16934.expected b/ops/optimizer_tests/issue16934.expected new file mode 100644 index 0000000000..6b75ff5bf3 --- /dev/null +++ b/ops/optimizer_tests/issue16934.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: false +has_ref_opstate: false +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: false +fast_result: None +fast_parameters: [] +transforms: {} +is_async: false +fast_compatible: false diff --git a/ops/optimizer_tests/issue16934.out b/ops/optimizer_tests/issue16934.out new file mode 100644 index 0000000000..63abd21920 --- /dev/null +++ b/ops/optimizer_tests/issue16934.out @@ -0,0 +1,92 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `send_stdin::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct send_stdin; +#[doc(hidden)] +impl send_stdin { + pub fn name() -> &'static str { + stringify!(send_stdin) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: None, + is_async: true, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + async fn call(state: &mut OpState, cmd: String) -> Result<(), anyhow::Error> { + let instance = state.borrow::().clone(); + instance.send_command(&cmd, CausedBy::Unknown).await?; + Ok(()) + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + use deno_core::futures::FutureExt; + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let op_id = ctx.id; + let promise_id = args.get(0); + let promise_id = deno_core::v8::Local::< + deno_core::v8::Integer, + >::try_from(promise_id) + .map(|l| l.value() as deno_core::PromiseId) + .map_err(deno_core::anyhow::Error::from); + let promise_id: deno_core::PromiseId = match promise_id { + Ok(promise_id) => promise_id, + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!("invalid promise id: {}", err), + ); + return; + } + }; + let arg_0 = match deno_core::v8::Local::< + deno_core::v8::String, + >::try_from(args.get(1usize as i32)) { + Ok(v8_string) => deno_core::serde_v8::to_utf8(v8_string, scope), + Err(_) => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected string at position {}", 1usize), + ); + } + }; + let get_class = { + let state = ::std::cell::RefCell::borrow(&ctx.state); + state.tracker.track_async(op_id); + state.get_error_class_fn + }; + deno_core::_ops::queue_async_op( + ctx, + scope, + false, + async move { + let result = Self::call( + compile_error!("mutable opstate is not supported in async ops"), + arg_0, + ) + .await; + (promise_id, op_id, deno_core::_ops::to_op_result(get_class, result)) + }, + ); + } +} diff --git a/ops/optimizer_tests/issue16934.rs b/ops/optimizer_tests/issue16934.rs new file mode 100644 index 0000000000..1e77f12812 --- /dev/null +++ b/ops/optimizer_tests/issue16934.rs @@ -0,0 +1,11 @@ +async fn send_stdin( + state: &mut OpState, + cmd: String, +) -> Result<(), anyhow::Error> { + // https://github.com/denoland/deno/issues/16934 + // + // OpState borrowed across await point is not allowed, as it will likely panic at runtime. + let instance = state.borrow::().clone(); + instance.send_command(&cmd, CausedBy::Unknown).await?; + Ok(()) +} diff --git a/ops/optimizer_tests/issue16934_fast.expected b/ops/optimizer_tests/issue16934_fast.expected new file mode 100644 index 0000000000..250ff1022d --- /dev/null +++ b/ops/optimizer_tests/issue16934_fast.expected @@ -0,0 +1 @@ +FastUnsupportedParamType \ No newline at end of file diff --git a/ops/optimizer_tests/issue16934_fast.out b/ops/optimizer_tests/issue16934_fast.out new file mode 100644 index 0000000000..615bc6b3b9 --- /dev/null +++ b/ops/optimizer_tests/issue16934_fast.out @@ -0,0 +1,90 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `send_stdin::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct send_stdin; +#[doc(hidden)] +impl send_stdin { + pub fn name() -> &'static str { + stringify!(send_stdin) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: None, + is_async: true, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + async fn call(state: &mut OpState, v: i32) -> Result<(), anyhow::Error> { + Ok(()) + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + use deno_core::futures::FutureExt; + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let op_id = ctx.id; + let promise_id = args.get(0); + let promise_id = deno_core::v8::Local::< + deno_core::v8::Integer, + >::try_from(promise_id) + .map(|l| l.value() as deno_core::PromiseId) + .map_err(deno_core::anyhow::Error::from); + let promise_id: deno_core::PromiseId = match promise_id { + Ok(promise_id) => promise_id, + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!("invalid promise id: {}", err), + ); + return; + } + }; + let arg_0 = args.get(1usize as i32); + let arg_0 = match deno_core::serde_v8::from_v8(scope, arg_0) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 1usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let get_class = { + let state = ::std::cell::RefCell::borrow(&ctx.state); + state.tracker.track_async(op_id); + state.get_error_class_fn + }; + deno_core::_ops::queue_async_op( + ctx, + scope, + false, + async move { + let result = Self::call( + compile_error!("mutable opstate is not supported in async ops"), + arg_0, + ) + .await; + (promise_id, op_id, deno_core::_ops::to_op_result(get_class, result)) + }, + ); + } +} diff --git a/ops/optimizer_tests/issue16934_fast.rs b/ops/optimizer_tests/issue16934_fast.rs new file mode 100644 index 0000000000..8d3488e9d0 --- /dev/null +++ b/ops/optimizer_tests/issue16934_fast.rs @@ -0,0 +1,8 @@ +async fn send_stdin(state: &mut OpState, v: i32) -> Result<(), anyhow::Error> { + // @test-attr:fast + // + // https://github.com/denoland/deno/issues/16934 + // + // OpState borrowed across await point is not allowed, as it will likely panic at runtime. + Ok(()) +} diff --git a/ops/optimizer_tests/op_blob_revoke_object_url.expected b/ops/optimizer_tests/op_blob_revoke_object_url.expected new file mode 100644 index 0000000000..5b3e43edc3 --- /dev/null +++ b/ops/optimizer_tests/op_blob_revoke_object_url.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: true +has_ref_opstate: true +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: false +fast_result: Some(Void) +fast_parameters: [V8Value, SeqOneByteString] +transforms: {1: Transform { kind: SeqOneByteString(Owned), index: 1 }} +is_async: false +fast_compatible: true diff --git a/ops/optimizer_tests/op_blob_revoke_object_url.out b/ops/optimizer_tests/op_blob_revoke_object_url.out new file mode 100644 index 0000000000..28fe17acb8 --- /dev/null +++ b/ops/optimizer_tests/op_blob_revoke_object_url.out @@ -0,0 +1,129 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_blob_revoke_object_url::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_blob_revoke_object_url; +#[doc(hidden)] +impl op_blob_revoke_object_url { + pub fn name() -> &'static str { + stringify!(op_blob_revoke_object_url) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_blob_revoke_object_url_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + pub fn call(state: &mut OpState, url: String) -> Result<(), AnyError> { + let url = Url::parse(&url)?; + let blob_store = state.borrow::(); + blob_store.remove_object_url(&url); + Ok(()) + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + { + let op_state = &mut std::cell::RefCell::borrow_mut(&ctx.state); + if let Some(err) = op_state.last_fast_op_error.take() { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + return; + } + } + let arg_0 = match deno_core::v8::Local::< + deno_core::v8::String, + >::try_from(args.get(0usize as i32)) { + Ok(v8_string) => deno_core::serde_v8::to_utf8(v8_string, scope), + Err(_) => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected string at position {}", 0usize), + ); + } + }; + let result = Self::call(&mut std::cell::RefCell::borrow_mut(&ctx.state), arg_0); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match result { + Ok(result) => {} + Err(err) => { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + } + }; + } +} +struct op_blob_revoke_object_url_fast { + _phantom: ::std::marker::PhantomData<()>, +} +impl<'scope> deno_core::v8::fast_api::FastFunction for op_blob_revoke_object_url_fast { + fn function(&self) -> *const ::std::ffi::c_void { + op_blob_revoke_object_url_fast_fn as *const ::std::ffi::c_void + } + fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { + use deno_core::v8::fast_api::Type::*; + use deno_core::v8::fast_api::CType; + &[V8Value, SeqOneByteString, CallbackOptions] + } + fn return_type(&self) -> deno_core::v8::fast_api::CType { + deno_core::v8::fast_api::CType::Void + } +} +fn op_blob_revoke_object_url_fast_fn<'scope>( + _: deno_core::v8::Local, + url: *const deno_core::v8::fast_api::FastApiOneByteString, + fast_api_callback_options: *mut deno_core::v8::fast_api::FastApiCallbackOptions, +) -> () { + use deno_core::v8; + use deno_core::_ops; + let __opts: &mut v8::fast_api::FastApiCallbackOptions = unsafe { + &mut *fast_api_callback_options + }; + let __ctx = unsafe { + &*(v8::Local::::cast(unsafe { __opts.data.data }).value() + as *const _ops::OpCtx) + }; + let state = &mut ::std::cell::RefCell::borrow_mut(&__ctx.state); + let url = unsafe { &*url }.as_str().to_owned(); + let result = op_blob_revoke_object_url::call(state, url); + match result { + Ok(result) => result, + Err(err) => { + state.last_fast_op_error.replace(err); + __opts.fallback = true; + Default::default() + } + } +} diff --git a/ops/optimizer_tests/op_blob_revoke_object_url.rs b/ops/optimizer_tests/op_blob_revoke_object_url.rs new file mode 100644 index 0000000000..b51a2ed7f5 --- /dev/null +++ b/ops/optimizer_tests/op_blob_revoke_object_url.rs @@ -0,0 +1,9 @@ +pub fn op_blob_revoke_object_url( + state: &mut OpState, + url: String, +) -> Result<(), AnyError> { + let url = Url::parse(&url)?; + let blob_store = state.borrow::(); + blob_store.remove_object_url(&url); + Ok(()) +} diff --git a/ops/optimizer_tests/op_print.expected b/ops/optimizer_tests/op_print.expected new file mode 100644 index 0000000000..fb52693aa2 --- /dev/null +++ b/ops/optimizer_tests/op_print.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: true +has_ref_opstate: true +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: false +fast_result: Some(Void) +fast_parameters: [V8Value, SeqOneByteString, Bool] +transforms: {1: Transform { kind: SeqOneByteString(Ref), index: 1 }} +is_async: false +fast_compatible: true diff --git a/ops/optimizer_tests/op_print.out b/ops/optimizer_tests/op_print.out new file mode 100644 index 0000000000..5d0062a01a --- /dev/null +++ b/ops/optimizer_tests/op_print.out @@ -0,0 +1,141 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_print::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_print; +#[doc(hidden)] +impl op_print { + pub fn name() -> &'static str { + stringify!(op_print) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_print_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 2usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(state: &mut OpState, msg: &str, is_err: bool) -> Result<(), AnyError> {} + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + { + let op_state = &mut std::cell::RefCell::borrow_mut(&ctx.state); + if let Some(err) = op_state.last_fast_op_error.take() { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + return; + } + } + let arg_0 = match deno_core::v8::Local::< + deno_core::v8::String, + >::try_from(args.get(0usize as i32)) { + Ok(v8_string) => deno_core::serde_v8::to_utf8(v8_string, scope), + Err(_) => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected string at position {}", 0usize), + ); + } + }; + let arg_0 = arg_0.as_ref(); + let arg_1 = args.get(1usize as i32); + let arg_1 = match deno_core::serde_v8::from_v8(scope, arg_1) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 1usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let result = Self::call( + &mut std::cell::RefCell::borrow_mut(&ctx.state), + arg_0, + arg_1, + ); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match result { + Ok(result) => {} + Err(err) => { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + } + }; + } +} +struct op_print_fast { + _phantom: ::std::marker::PhantomData<()>, +} +impl<'scope> deno_core::v8::fast_api::FastFunction for op_print_fast { + fn function(&self) -> *const ::std::ffi::c_void { + op_print_fast_fn as *const ::std::ffi::c_void + } + fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { + use deno_core::v8::fast_api::Type::*; + use deno_core::v8::fast_api::CType; + &[V8Value, SeqOneByteString, Bool, CallbackOptions] + } + fn return_type(&self) -> deno_core::v8::fast_api::CType { + deno_core::v8::fast_api::CType::Void + } +} +fn op_print_fast_fn<'scope>( + _: deno_core::v8::Local, + msg: *const deno_core::v8::fast_api::FastApiOneByteString, + is_err: bool, + fast_api_callback_options: *mut deno_core::v8::fast_api::FastApiCallbackOptions, +) -> () { + use deno_core::v8; + use deno_core::_ops; + let __opts: &mut v8::fast_api::FastApiCallbackOptions = unsafe { + &mut *fast_api_callback_options + }; + let __ctx = unsafe { + &*(v8::Local::::cast(unsafe { __opts.data.data }).value() + as *const _ops::OpCtx) + }; + let state = &mut ::std::cell::RefCell::borrow_mut(&__ctx.state); + let msg = unsafe { &*msg }.as_str(); + let result = op_print::call(state, msg, is_err); + match result { + Ok(result) => result, + Err(err) => { + state.last_fast_op_error.replace(err); + __opts.fallback = true; + Default::default() + } + } +} diff --git a/ops/optimizer_tests/op_print.rs b/ops/optimizer_tests/op_print.rs new file mode 100644 index 0000000000..516521a0e9 --- /dev/null +++ b/ops/optimizer_tests/op_print.rs @@ -0,0 +1,6 @@ +fn op_print( + state: &mut OpState, + msg: &str, + is_err: bool, +) -> Result<(), AnyError> { +} diff --git a/ops/optimizer_tests/op_state.expected b/ops/optimizer_tests/op_state.expected index d8d6804557..241ea76936 100644 --- a/ops/optimizer_tests/op_state.expected +++ b/ops/optimizer_tests/op_state.expected @@ -3,6 +3,7 @@ returns_result: false has_ref_opstate: true has_rc_opstate: false has_fast_callback_option: false +needs_fast_callback_option: false fast_result: Some(Void) fast_parameters: [V8Value, I32] transforms: {} diff --git a/ops/optimizer_tests/op_state.out b/ops/optimizer_tests/op_state.out index a98db68d84..5b273960a6 100644 --- a/ops/optimizer_tests/op_state.out +++ b/ops/optimizer_tests/op_state.out @@ -1,3 +1,64 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_set_exit_code::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_set_exit_code; +#[doc(hidden)] +impl op_set_exit_code { + pub fn name() -> &'static str { + stringify!(op_set_exit_code) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_set_exit_code_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(state: &mut OpState, code: i32) { + state.borrow_mut::().set(code); + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = args.get(0usize as i32); + let arg_0 = match deno_core::serde_v8::from_v8(scope, arg_0) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 0usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let result = Self::call(&mut std::cell::RefCell::borrow_mut(&ctx.state), arg_0); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + } +} struct op_set_exit_code_fast { _phantom: ::std::marker::PhantomData<()>, } diff --git a/ops/optimizer_tests/op_state_basic1.expected b/ops/optimizer_tests/op_state_basic1.expected index 6e7b15493c..e325dd2f70 100644 --- a/ops/optimizer_tests/op_state_basic1.expected +++ b/ops/optimizer_tests/op_state_basic1.expected @@ -3,6 +3,7 @@ returns_result: false has_ref_opstate: true has_rc_opstate: false has_fast_callback_option: false +needs_fast_callback_option: false fast_result: Some(U32) fast_parameters: [V8Value, U32, U32] transforms: {} diff --git a/ops/optimizer_tests/op_state_basic1.out b/ops/optimizer_tests/op_state_basic1.out index 0f03f2c586..ab3404a429 100644 --- a/ops/optimizer_tests/op_state_basic1.out +++ b/ops/optimizer_tests/op_state_basic1.out @@ -1,3 +1,91 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `foo::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct foo; +#[doc(hidden)] +impl foo { + pub fn name() -> &'static str { + stringify!(foo) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(foo_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 2usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(state: &mut OpState, a: u32, b: u32) -> u32 { + a + b + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = args.get(0usize as i32); + let arg_0 = match deno_core::serde_v8::from_v8(scope, arg_0) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 0usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let arg_1 = args.get(1usize as i32); + let arg_1 = match deno_core::serde_v8::from_v8(scope, arg_1) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 1usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let result = Self::call( + &mut std::cell::RefCell::borrow_mut(&ctx.state), + arg_0, + arg_1, + ); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match deno_core::serde_v8::to_v8(scope, result) { + Ok(ret) => rv.set(ret), + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!( + "Error serializing return: {}", + deno_core::anyhow::Error::from(err) + ), + ) + } + }; + } +} struct foo_fast { _phantom: ::std::marker::PhantomData<()>, } diff --git a/ops/optimizer_tests/op_state_generics.expected b/ops/optimizer_tests/op_state_generics.expected index b78c81c5fa..c29258d756 100644 --- a/ops/optimizer_tests/op_state_generics.expected +++ b/ops/optimizer_tests/op_state_generics.expected @@ -3,6 +3,7 @@ returns_result: false has_ref_opstate: true has_rc_opstate: false has_fast_callback_option: false +needs_fast_callback_option: false fast_result: Some(Void) fast_parameters: [V8Value] transforms: {} diff --git a/ops/optimizer_tests/op_state_generics.out b/ops/optimizer_tests/op_state_generics.out index d141c74457..bd5e40afe8 100644 --- a/ops/optimizer_tests/op_state_generics.out +++ b/ops/optimizer_tests/op_state_generics.out @@ -1,3 +1,63 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_foo::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_foo; +#[doc(hidden)] +impl op_foo { + pub fn name() -> &'static str { + stringify!(op_foo) + } + pub fn v8_fn_ptr<'scope, SP>() -> deno_core::v8::FunctionCallback + where + SP: SomePermission + 'static, + { + use deno_core::v8::MapFnTo; + Self::v8_func::.map_fn_to() + } + pub fn decl<'scope, SP>() -> deno_core::OpDecl + where + SP: SomePermission + 'static, + { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr::(), + enabled: true, + fast_fn: Some( + Box::new(op_foo_fast:: { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 0usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + pub fn call(state: &mut OpState) + where + SP: SomePermission + 'static, + {} + pub fn v8_func<'scope, SP>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) + where + SP: SomePermission + 'static, + { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let result = Self::call::(&mut std::cell::RefCell::borrow_mut(&ctx.state)); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + } +} struct op_foo_fast { _phantom: ::std::marker::PhantomData, } diff --git a/ops/optimizer_tests/op_state_result.expected b/ops/optimizer_tests/op_state_result.expected index e133900527..15ac033f34 100644 --- a/ops/optimizer_tests/op_state_result.expected +++ b/ops/optimizer_tests/op_state_result.expected @@ -3,6 +3,7 @@ returns_result: true has_ref_opstate: true has_rc_opstate: false has_fast_callback_option: false +needs_fast_callback_option: false fast_result: Some(U32) fast_parameters: [V8Value, U32, U32] transforms: {} diff --git a/ops/optimizer_tests/op_state_result.out b/ops/optimizer_tests/op_state_result.out index 5174dd7f2b..76070b5363 100644 --- a/ops/optimizer_tests/op_state_result.out +++ b/ops/optimizer_tests/op_state_result.out @@ -1,3 +1,104 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `foo::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct foo; +#[doc(hidden)] +impl foo { + pub fn name() -> &'static str { + stringify!(foo) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(foo_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 2usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(state: &mut OpState, a: u32, b: u32) -> Result { + Ok(a + b) + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + { + let op_state = &mut std::cell::RefCell::borrow_mut(&ctx.state); + if let Some(err) = op_state.last_fast_op_error.take() { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + return; + } + } + let arg_0 = args.get(0usize as i32); + let arg_0 = match deno_core::serde_v8::from_v8(scope, arg_0) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 0usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let arg_1 = args.get(1usize as i32); + let arg_1 = match deno_core::serde_v8::from_v8(scope, arg_1) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 1usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let result = Self::call( + &mut std::cell::RefCell::borrow_mut(&ctx.state), + arg_0, + arg_1, + ); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match result { + Ok(result) => { + rv.set_uint32(result as u32); + } + Err(err) => { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + } + }; + } +} struct foo_fast { _phantom: ::std::marker::PhantomData<()>, } diff --git a/ops/optimizer_tests/op_state_warning.expected b/ops/optimizer_tests/op_state_warning.expected index 94580fd6dc..7b33ad1ef4 100644 --- a/ops/optimizer_tests/op_state_warning.expected +++ b/ops/optimizer_tests/op_state_warning.expected @@ -3,6 +3,7 @@ returns_result: true has_ref_opstate: true has_rc_opstate: false has_fast_callback_option: false +needs_fast_callback_option: false fast_result: Some(U32) fast_parameters: [V8Value] transforms: {} diff --git a/ops/optimizer_tests/op_state_warning.out b/ops/optimizer_tests/op_state_warning.out index 2c40b0f714..9917fbf79d 100644 --- a/ops/optimizer_tests/op_state_warning.out +++ b/ops/optimizer_tests/op_state_warning.out @@ -1,3 +1,95 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_listen::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_listen; +#[doc(hidden)] +impl op_listen { + pub fn name() -> &'static str { + stringify!(op_listen) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_listen_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 0usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(state: &mut OpState) -> Result { + log::debug!("listen"); + let addr = "127.0.0.1:4570".parse::().unwrap(); + let std_listener = std::net::TcpListener::bind(&addr)?; + std_listener.set_nonblocking(true)?; + let listener = TcpListener::try_from(std_listener)?; + let rid = state.resource_table.add(listener); + Ok(rid) + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + { + let op_state = &mut std::cell::RefCell::borrow_mut(&ctx.state); + if let Some(err) = op_state.last_fast_op_error.take() { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + return; + } + } + let result = Self::call(&mut std::cell::RefCell::borrow_mut(&ctx.state)); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match result { + Ok(result) => { + match deno_core::serde_v8::to_v8(scope, result) { + Ok(ret) => rv.set(ret), + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!( + "Error serializing return: {}", + deno_core::anyhow::Error::from(err) + ), + ) + } + }; + } + Err(err) => { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + } + }; + } +} struct op_listen_fast { _phantom: ::std::marker::PhantomData<()>, } diff --git a/ops/optimizer_tests/op_state_with_transforms.expected b/ops/optimizer_tests/op_state_with_transforms.expected index 0fc9c99494..d6757801ee 100644 --- a/ops/optimizer_tests/op_state_with_transforms.expected +++ b/ops/optimizer_tests/op_state_with_transforms.expected @@ -2,7 +2,8 @@ returns_result: false has_ref_opstate: true has_rc_opstate: false -has_fast_callback_option: true +has_fast_callback_option: false +needs_fast_callback_option: true fast_result: Some(Void) fast_parameters: [V8Value, Uint8Array] transforms: {1: Transform { kind: SliceU8(true), index: 1 }} diff --git a/ops/optimizer_tests/op_state_with_transforms.out b/ops/optimizer_tests/op_state_with_transforms.out index f981748be0..541a4fd36f 100644 --- a/ops/optimizer_tests/op_state_with_transforms.out +++ b/ops/optimizer_tests/op_state_with_transforms.out @@ -1,3 +1,110 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_now::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_now; +#[doc(hidden)] +impl op_now { + pub fn name() -> &'static str { + stringify!(op_now) + } + pub fn v8_fn_ptr<'scope, TP>() -> deno_core::v8::FunctionCallback + where + TP: TimersPermission + 'static, + { + use deno_core::v8::MapFnTo; + Self::v8_func::.map_fn_to() + } + pub fn decl<'scope, TP>() -> deno_core::OpDecl + where + TP: TimersPermission + 'static, + { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr::(), + enabled: true, + fast_fn: Some( + Box::new(op_now_fast:: { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + pub fn call(state: &mut OpState, buf: &mut [u8]) + where + TP: TimersPermission + 'static, + {} + pub fn v8_func<'scope, TP>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) + where + TP: TimersPermission + 'static, + { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = { + let value = args.get(0usize as i32); + match deno_core::v8::Local::::try_from(value) { + Ok(b) => { + let byte_length = b.byte_length(); + if let Some(data) = b.data() { + let store = data.cast::().as_ptr(); + unsafe { ::std::slice::from_raw_parts_mut(store, byte_length) } + } else { + &mut [] + } + } + Err(_) => { + if let Ok(view) + = deno_core::v8::Local::< + deno_core::v8::ArrayBufferView, + >::try_from(value) { + let len = view.byte_length(); + let offset = view.byte_offset(); + let buffer = match view.buffer(scope) { + Some(v) => v, + None => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected ArrayBufferView at position {}", 0usize), + ); + } + }; + if let Some(data) = buffer.data() { + let store = data.cast::().as_ptr(); + unsafe { + ::std::slice::from_raw_parts_mut(store.add(offset), len) + } + } else { + &mut [] + } + } else { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected ArrayBufferView at position {}", 0usize), + ); + } + } + } + }; + let result = Self::call::< + TP, + >(&mut std::cell::RefCell::borrow_mut(&ctx.state), arg_0); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + } +} struct op_now_fast { _phantom: ::std::marker::PhantomData, } diff --git a/ops/optimizer_tests/opstate_with_arity.expected b/ops/optimizer_tests/opstate_with_arity.expected index 4be888c333..b38455d0dd 100644 --- a/ops/optimizer_tests/opstate_with_arity.expected +++ b/ops/optimizer_tests/opstate_with_arity.expected @@ -3,6 +3,7 @@ returns_result: true has_ref_opstate: false has_rc_opstate: false has_fast_callback_option: false +needs_fast_callback_option: false fast_result: Some(U32) fast_parameters: [V8Value, U32, U32, U32, U32] transforms: {} diff --git a/ops/optimizer_tests/opstate_with_arity.out b/ops/optimizer_tests/opstate_with_arity.out index 20b7769e75..132e54aeff 100644 --- a/ops/optimizer_tests/opstate_with_arity.out +++ b/ops/optimizer_tests/opstate_with_arity.out @@ -1,3 +1,122 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_add_4::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_add_4; +#[doc(hidden)] +impl op_add_4 { + pub fn name() -> &'static str { + stringify!(op_add_4) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_add_4_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 4usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(x1: u32, x2: u32, x3: u32, x4: u32) -> Result { + Ok(x1 + x2 + x3 + x4) + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + { + let op_state = &mut std::cell::RefCell::borrow_mut(&ctx.state); + if let Some(err) = op_state.last_fast_op_error.take() { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + return; + } + } + let arg_0 = args.get(0usize as i32); + let arg_0 = match deno_core::serde_v8::from_v8(scope, arg_0) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 0usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let arg_1 = args.get(1usize as i32); + let arg_1 = match deno_core::serde_v8::from_v8(scope, arg_1) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 1usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let arg_2 = args.get(2usize as i32); + let arg_2 = match deno_core::serde_v8::from_v8(scope, arg_2) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 2usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let arg_3 = args.get(3usize as i32); + let arg_3 = match deno_core::serde_v8::from_v8(scope, arg_3) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 3usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let result = Self::call(arg_0, arg_1, arg_2, arg_3); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match result { + Ok(result) => { + rv.set_uint32(result as u32); + } + Err(err) => { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + } + }; + } +} struct op_add_4_fast { _phantom: ::std::marker::PhantomData<()>, } diff --git a/ops/optimizer_tests/option_arg.expected b/ops/optimizer_tests/option_arg.expected new file mode 100644 index 0000000000..250ff1022d --- /dev/null +++ b/ops/optimizer_tests/option_arg.expected @@ -0,0 +1 @@ +FastUnsupportedParamType \ No newline at end of file diff --git a/ops/optimizer_tests/option_arg.out b/ops/optimizer_tests/option_arg.out new file mode 100644 index 0000000000..9f647765f4 --- /dev/null +++ b/ops/optimizer_tests/option_arg.out @@ -0,0 +1,66 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_try_close::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_try_close; +#[doc(hidden)] +impl op_try_close { + pub fn name() -> &'static str { + stringify!(op_try_close) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: None, + is_async: false, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + pub fn call(state: &mut OpState, rid: Option) -> Result<(), Error> {} + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = args.get(0usize as i32); + let arg_0 = match deno_core::serde_v8::from_v8(scope, arg_0) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 0usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let result = Self::call(&mut std::cell::RefCell::borrow_mut(&ctx.state), arg_0); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match result { + Ok(result) => {} + Err(err) => { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + } + }; + } +} diff --git a/ops/optimizer_tests/option_arg.rs b/ops/optimizer_tests/option_arg.rs new file mode 100644 index 0000000000..47a02974d7 --- /dev/null +++ b/ops/optimizer_tests/option_arg.rs @@ -0,0 +1,6 @@ +pub fn op_try_close( + state: &mut OpState, + rid: Option, +) -> Result<(), Error> { + // ... +} diff --git a/ops/optimizer_tests/owned_string.expected b/ops/optimizer_tests/owned_string.expected new file mode 100644 index 0000000000..a152754129 --- /dev/null +++ b/ops/optimizer_tests/owned_string.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: false +has_ref_opstate: false +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: false +fast_result: Some(U32) +fast_parameters: [V8Value, SeqOneByteString] +transforms: {0: Transform { kind: SeqOneByteString(Owned), index: 0 }} +is_async: false +fast_compatible: true diff --git a/ops/optimizer_tests/owned_string.out b/ops/optimizer_tests/owned_string.out new file mode 100644 index 0000000000..4892221f81 --- /dev/null +++ b/ops/optimizer_tests/owned_string.out @@ -0,0 +1,99 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_string_length::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_string_length; +#[doc(hidden)] +impl op_string_length { + pub fn name() -> &'static str { + stringify!(op_string_length) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_string_length_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(string: String) -> u32 { + string.len() as u32 + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = match deno_core::v8::Local::< + deno_core::v8::String, + >::try_from(args.get(0usize as i32)) { + Ok(v8_string) => deno_core::serde_v8::to_utf8(v8_string, scope), + Err(_) => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected string at position {}", 0usize), + ); + } + }; + let result = Self::call(arg_0); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match deno_core::serde_v8::to_v8(scope, result) { + Ok(ret) => rv.set(ret), + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!( + "Error serializing return: {}", + deno_core::anyhow::Error::from(err) + ), + ) + } + }; + } +} +struct op_string_length_fast { + _phantom: ::std::marker::PhantomData<()>, +} +impl<'scope> deno_core::v8::fast_api::FastFunction for op_string_length_fast { + fn function(&self) -> *const ::std::ffi::c_void { + op_string_length_fast_fn as *const ::std::ffi::c_void + } + fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { + use deno_core::v8::fast_api::Type::*; + use deno_core::v8::fast_api::CType; + &[V8Value, SeqOneByteString] + } + fn return_type(&self) -> deno_core::v8::fast_api::CType { + deno_core::v8::fast_api::CType::Uint32 + } +} +fn op_string_length_fast_fn<'scope>( + _: deno_core::v8::Local, + string: *const deno_core::v8::fast_api::FastApiOneByteString, +) -> u32 { + use deno_core::v8; + use deno_core::_ops; + let string = unsafe { &*string }.as_str().to_owned(); + let result = op_string_length::call(string); + result +} diff --git a/ops/optimizer_tests/owned_string.rs b/ops/optimizer_tests/owned_string.rs new file mode 100644 index 0000000000..102cf00fb9 --- /dev/null +++ b/ops/optimizer_tests/owned_string.rs @@ -0,0 +1,3 @@ +fn op_string_length(string: String) -> u32 { + string.len() as u32 +} diff --git a/ops/optimizer_tests/param_mut_binding_warning.out b/ops/optimizer_tests/param_mut_binding_warning.out new file mode 100644 index 0000000000..daccc28abb --- /dev/null +++ b/ops/optimizer_tests/param_mut_binding_warning.out @@ -0,0 +1,89 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_read_sync::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_read_sync; +#[doc(hidden)] +impl op_read_sync { + pub fn name() -> &'static str { + stringify!(op_read_sync) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: None, + is_async: false, + is_unstable: false, + is_v8: false, + argc: 2usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call( + state: &mut OpState, + rid: ResourceId, + mut buf: ZeroCopyBuf, + ) -> Result { + Ok(23) + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = args.get(0usize as i32); + let arg_0 = match deno_core::serde_v8::from_v8(scope, arg_0) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 0usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let arg_1 = args.get(1usize as i32); + let arg_1 = match deno_core::serde_v8::from_v8(scope, arg_1) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 1usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let result = Self::call( + &mut std::cell::RefCell::borrow_mut(&ctx.state), + arg_0, + arg_1, + ); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match result { + Ok(result) => { + rv.set_uint32(result as u32); + } + Err(err) => { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + } + }; + } +} diff --git a/ops/optimizer_tests/raw_ptr.expected b/ops/optimizer_tests/raw_ptr.expected new file mode 100644 index 0000000000..badd6e3f49 --- /dev/null +++ b/ops/optimizer_tests/raw_ptr.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: false +has_ref_opstate: true +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: true +fast_result: Some(Void) +fast_parameters: [V8Value, Uint8Array, Uint32Array] +transforms: {1: Transform { kind: PtrU8, index: 1 }, 2: Transform { kind: SliceU32(true), index: 2 }} +is_async: false +fast_compatible: true diff --git a/ops/optimizer_tests/raw_ptr.out b/ops/optimizer_tests/raw_ptr.out new file mode 100644 index 0000000000..f9f467ad9b --- /dev/null +++ b/ops/optimizer_tests/raw_ptr.out @@ -0,0 +1,188 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_ffi_ptr_of::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_ffi_ptr_of; +#[doc(hidden)] +impl op_ffi_ptr_of { + pub fn name() -> &'static str { + stringify!(op_ffi_ptr_of) + } + pub fn v8_fn_ptr<'scope, FP>() -> deno_core::v8::FunctionCallback + where + FP: FfiPermissions + 'static, + { + use deno_core::v8::MapFnTo; + Self::v8_func::.map_fn_to() + } + pub fn decl<'scope, FP>() -> deno_core::OpDecl + where + FP: FfiPermissions + 'static, + { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr::(), + enabled: true, + fast_fn: Some( + Box::new(op_ffi_ptr_of_fast:: { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 2usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(state: &mut OpState, buf: *const u8, out: &mut [u32]) + where + FP: FfiPermissions + 'static, + {} + pub fn v8_func<'scope, FP>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) + where + FP: FfiPermissions + 'static, + { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = { + let value = args.get(0usize as i32); + match deno_core::v8::Local::::try_from(value) { + Ok(b) => { + if let Some(data) = b.data() { + data.cast::().as_ptr() + } else { + std::ptr::null::() + } + } + Err(_) => { + if let Ok(view) + = deno_core::v8::Local::< + deno_core::v8::ArrayBufferView, + >::try_from(value) { + let offset = view.byte_offset(); + let buffer = match view.buffer(scope) { + Some(v) => v, + None => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected ArrayBufferView at position {}", 0usize), + ); + } + }; + let store = if let Some(data) = buffer.data() { + data.cast::().as_ptr() + } else { + std::ptr::null_mut::() + }; + unsafe { store.add(offset) } + } else { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected ArrayBufferView at position {}", 0usize), + ); + } + } + } + }; + let arg_1 = if let Ok(view) + = deno_core::v8::Local::< + deno_core::v8::Uint32Array, + >::try_from(args.get(1usize as i32)) { + let (offset, len) = (view.byte_offset(), view.byte_length()); + let buffer = match view.buffer(scope) { + Some(v) => v, + None => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected Uint32Array at position {}", 1usize), + ); + } + }; + if let Some(data) = buffer.data() { + let store = data.cast::().as_ptr(); + unsafe { + ::std::slice::from_raw_parts_mut( + store.add(offset) as *mut u32, + len / 4, + ) + } + } else { + &mut [] + } + } else { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected Uint32Array at position {}", 1usize), + ); + }; + let result = Self::call::< + FP, + >(&mut std::cell::RefCell::borrow_mut(&ctx.state), arg_0, arg_1); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + } +} +struct op_ffi_ptr_of_fast { + _phantom: ::std::marker::PhantomData, +} +impl<'scope, FP> deno_core::v8::fast_api::FastFunction for op_ffi_ptr_of_fast +where + FP: FfiPermissions + 'static, +{ + fn function(&self) -> *const ::std::ffi::c_void { + op_ffi_ptr_of_fast_fn:: as *const ::std::ffi::c_void + } + fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { + use deno_core::v8::fast_api::Type::*; + use deno_core::v8::fast_api::CType; + &[V8Value, TypedArray(CType::Uint8), TypedArray(CType::Uint32), CallbackOptions] + } + fn return_type(&self) -> deno_core::v8::fast_api::CType { + deno_core::v8::fast_api::CType::Void + } +} +fn op_ffi_ptr_of_fast_fn<'scope, FP>( + _: deno_core::v8::Local, + buf: *const deno_core::v8::fast_api::FastApiTypedArray, + out: *const deno_core::v8::fast_api::FastApiTypedArray, + fast_api_callback_options: *mut deno_core::v8::fast_api::FastApiCallbackOptions, +) -> () +where + FP: FfiPermissions + 'static, +{ + use deno_core::v8; + use deno_core::_ops; + let __opts: &mut v8::fast_api::FastApiCallbackOptions = unsafe { + &mut *fast_api_callback_options + }; + let __ctx = unsafe { + &*(v8::Local::::cast(unsafe { __opts.data.data }).value() + as *const _ops::OpCtx) + }; + let state = &mut ::std::cell::RefCell::borrow_mut(&__ctx.state); + let buf = match unsafe { &*buf }.get_storage_if_aligned() { + Some(v) => v.as_ptr(), + None => { + unsafe { &mut *fast_api_callback_options }.fallback = true; + return Default::default(); + } + }; + let out = match unsafe { &*out }.get_storage_if_aligned() { + Some(v) => v, + None => { + unsafe { &mut *fast_api_callback_options }.fallback = true; + return Default::default(); + } + }; + let result = op_ffi_ptr_of::call::(state, buf, out); + result +} diff --git a/ops/optimizer_tests/raw_ptr.rs b/ops/optimizer_tests/raw_ptr.rs new file mode 100644 index 0000000000..249b3b35b8 --- /dev/null +++ b/ops/optimizer_tests/raw_ptr.rs @@ -0,0 +1,6 @@ +fn op_ffi_ptr_of(state: &mut OpState, buf: *const u8, out: &mut [u32]) +where + FP: FfiPermissions + 'static, +{ + // .. +} diff --git a/ops/optimizer_tests/serde_v8_value.expected b/ops/optimizer_tests/serde_v8_value.expected index 058b17b1c2..411fbec0bc 100644 --- a/ops/optimizer_tests/serde_v8_value.expected +++ b/ops/optimizer_tests/serde_v8_value.expected @@ -3,6 +3,7 @@ returns_result: false has_ref_opstate: false has_rc_opstate: false has_fast_callback_option: false +needs_fast_callback_option: false fast_result: Some(Bool) fast_parameters: [V8Value, V8Value] transforms: {0: Transform { kind: V8Value, index: 0 }} diff --git a/ops/optimizer_tests/serde_v8_value.out b/ops/optimizer_tests/serde_v8_value.out index 8c76305476..d4f2c0321d 100644 --- a/ops/optimizer_tests/serde_v8_value.out +++ b/ops/optimizer_tests/serde_v8_value.out @@ -1,3 +1,76 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_is_proxy::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_is_proxy; +#[doc(hidden)] +impl op_is_proxy { + pub fn name() -> &'static str { + stringify!(op_is_proxy) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_is_proxy_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(value: serde_v8::Value) -> bool { + value.v8_value.is_proxy() + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = args.get(0usize as i32); + let arg_0 = match deno_core::serde_v8::from_v8(scope, arg_0) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 0usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let result = Self::call(arg_0); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match deno_core::serde_v8::to_v8(scope, result) { + Ok(ret) => rv.set(ret), + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!( + "Error serializing return: {}", + deno_core::anyhow::Error::from(err) + ), + ) + } + }; + } +} struct op_is_proxy_fast { _phantom: ::std::marker::PhantomData<()>, } diff --git a/ops/optimizer_tests/strings.expected b/ops/optimizer_tests/strings.expected new file mode 100644 index 0000000000..ead741054a --- /dev/null +++ b/ops/optimizer_tests/strings.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: false +has_ref_opstate: false +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: false +fast_result: Some(U32) +fast_parameters: [V8Value, SeqOneByteString] +transforms: {0: Transform { kind: SeqOneByteString(Ref), index: 0 }} +is_async: false +fast_compatible: true diff --git a/ops/optimizer_tests/strings.out b/ops/optimizer_tests/strings.out new file mode 100644 index 0000000000..41f09c4f8d --- /dev/null +++ b/ops/optimizer_tests/strings.out @@ -0,0 +1,100 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_string_length::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_string_length; +#[doc(hidden)] +impl op_string_length { + pub fn name() -> &'static str { + stringify!(op_string_length) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_string_length_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(string: &str) -> u32 { + string.len() as u32 + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = match deno_core::v8::Local::< + deno_core::v8::String, + >::try_from(args.get(0usize as i32)) { + Ok(v8_string) => deno_core::serde_v8::to_utf8(v8_string, scope), + Err(_) => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected string at position {}", 0usize), + ); + } + }; + let arg_0 = arg_0.as_ref(); + let result = Self::call(arg_0); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match deno_core::serde_v8::to_v8(scope, result) { + Ok(ret) => rv.set(ret), + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!( + "Error serializing return: {}", + deno_core::anyhow::Error::from(err) + ), + ) + } + }; + } +} +struct op_string_length_fast { + _phantom: ::std::marker::PhantomData<()>, +} +impl<'scope> deno_core::v8::fast_api::FastFunction for op_string_length_fast { + fn function(&self) -> *const ::std::ffi::c_void { + op_string_length_fast_fn as *const ::std::ffi::c_void + } + fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { + use deno_core::v8::fast_api::Type::*; + use deno_core::v8::fast_api::CType; + &[V8Value, SeqOneByteString] + } + fn return_type(&self) -> deno_core::v8::fast_api::CType { + deno_core::v8::fast_api::CType::Uint32 + } +} +fn op_string_length_fast_fn<'scope>( + _: deno_core::v8::Local, + string: *const deno_core::v8::fast_api::FastApiOneByteString, +) -> u32 { + use deno_core::v8; + use deno_core::_ops; + let string = unsafe { &*string }.as_str(); + let result = op_string_length::call(string); + result +} diff --git a/ops/optimizer_tests/strings.rs b/ops/optimizer_tests/strings.rs new file mode 100644 index 0000000000..860f1e8ec9 --- /dev/null +++ b/ops/optimizer_tests/strings.rs @@ -0,0 +1,3 @@ +fn op_string_length(string: &str) -> u32 { + string.len() as u32 +} diff --git a/ops/optimizer_tests/u64_result.out b/ops/optimizer_tests/u64_result.out new file mode 100644 index 0000000000..0039c75751 --- /dev/null +++ b/ops/optimizer_tests/u64_result.out @@ -0,0 +1,72 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_bench_now::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_bench_now; +#[doc(hidden)] +impl op_bench_now { + pub fn name() -> &'static str { + stringify!(op_bench_now) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: None, + is_async: false, + is_unstable: false, + is_v8: false, + argc: 0usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(state: &mut OpState) -> Result { + let ns = state.borrow::().elapsed().as_nanos(); + let ns_u64 = u64::try_from(ns)?; + Ok(ns_u64) + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let result = Self::call(&mut std::cell::RefCell::borrow_mut(&ctx.state)); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match result { + Ok(result) => { + match deno_core::serde_v8::to_v8(scope, result) { + Ok(ret) => rv.set(ret), + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!( + "Error serializing return: {}", + deno_core::anyhow::Error::from(err) + ), + ) + } + }; + } + Err(err) => { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + } + }; + } +} diff --git a/ops/optimizer_tests/uint8array.expected b/ops/optimizer_tests/uint8array.expected new file mode 100644 index 0000000000..0e5667a637 --- /dev/null +++ b/ops/optimizer_tests/uint8array.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: false +has_ref_opstate: false +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: true +fast_result: Some(Bool) +fast_parameters: [V8Value, Uint8Array, Uint8Array] +transforms: {0: Transform { kind: SliceU8(false), index: 0 }, 1: Transform { kind: SliceU8(true), index: 1 }} +is_async: false +fast_compatible: true diff --git a/ops/optimizer_tests/uint8array.out b/ops/optimizer_tests/uint8array.out new file mode 100644 index 0000000000..90d420fa0d --- /dev/null +++ b/ops/optimizer_tests/uint8array.out @@ -0,0 +1,191 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_import_spki_x25519::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_import_spki_x25519; +#[doc(hidden)] +impl op_import_spki_x25519 { + pub fn name() -> &'static str { + stringify!(op_import_spki_x25519) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_import_spki_x25519_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 2usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + pub fn call(key_data: &[u8], out: &mut [u8]) -> bool {} + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = { + let value = args.get(0usize as i32); + match deno_core::v8::Local::::try_from(value) { + Ok(b) => { + let byte_length = b.byte_length(); + if let Some(data) = b.data() { + let store = data.cast::().as_ptr(); + unsafe { ::std::slice::from_raw_parts_mut(store, byte_length) } + } else { + &mut [] + } + } + Err(_) => { + if let Ok(view) + = deno_core::v8::Local::< + deno_core::v8::ArrayBufferView, + >::try_from(value) { + let len = view.byte_length(); + let offset = view.byte_offset(); + let buffer = match view.buffer(scope) { + Some(v) => v, + None => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected ArrayBufferView at position {}", 0usize), + ); + } + }; + if let Some(data) = buffer.data() { + let store = data.cast::().as_ptr(); + unsafe { + ::std::slice::from_raw_parts_mut(store.add(offset), len) + } + } else { + &mut [] + } + } else { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected ArrayBufferView at position {}", 0usize), + ); + } + } + } + }; + let arg_1 = { + let value = args.get(1usize as i32); + match deno_core::v8::Local::::try_from(value) { + Ok(b) => { + let byte_length = b.byte_length(); + if let Some(data) = b.data() { + let store = data.cast::().as_ptr(); + unsafe { ::std::slice::from_raw_parts_mut(store, byte_length) } + } else { + &mut [] + } + } + Err(_) => { + if let Ok(view) + = deno_core::v8::Local::< + deno_core::v8::ArrayBufferView, + >::try_from(value) { + let len = view.byte_length(); + let offset = view.byte_offset(); + let buffer = match view.buffer(scope) { + Some(v) => v, + None => { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected ArrayBufferView at position {}", 1usize), + ); + } + }; + if let Some(data) = buffer.data() { + let store = data.cast::().as_ptr(); + unsafe { + ::std::slice::from_raw_parts_mut(store.add(offset), len) + } + } else { + &mut [] + } + } else { + return deno_core::_ops::throw_type_error( + scope, + format!("Expected ArrayBufferView at position {}", 1usize), + ); + } + } + } + }; + let result = Self::call(arg_0, arg_1); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match deno_core::serde_v8::to_v8(scope, result) { + Ok(ret) => rv.set(ret), + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!( + "Error serializing return: {}", + deno_core::anyhow::Error::from(err) + ), + ) + } + }; + } +} +struct op_import_spki_x25519_fast { + _phantom: ::std::marker::PhantomData<()>, +} +impl<'scope> deno_core::v8::fast_api::FastFunction for op_import_spki_x25519_fast { + fn function(&self) -> *const ::std::ffi::c_void { + op_import_spki_x25519_fast_fn as *const ::std::ffi::c_void + } + fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { + use deno_core::v8::fast_api::Type::*; + use deno_core::v8::fast_api::CType; + &[V8Value, TypedArray(CType::Uint8), TypedArray(CType::Uint8), CallbackOptions] + } + fn return_type(&self) -> deno_core::v8::fast_api::CType { + deno_core::v8::fast_api::CType::Bool + } +} +fn op_import_spki_x25519_fast_fn<'scope>( + _: deno_core::v8::Local, + key_data: *const deno_core::v8::fast_api::FastApiTypedArray, + out: *const deno_core::v8::fast_api::FastApiTypedArray, + fast_api_callback_options: *mut deno_core::v8::fast_api::FastApiCallbackOptions, +) -> bool { + use deno_core::v8; + use deno_core::_ops; + let key_data = match unsafe { &*key_data }.get_storage_if_aligned() { + Some(v) => v, + None => { + unsafe { &mut *fast_api_callback_options }.fallback = true; + return Default::default(); + } + }; + let out = match unsafe { &*out }.get_storage_if_aligned() { + Some(v) => v, + None => { + unsafe { &mut *fast_api_callback_options }.fallback = true; + return Default::default(); + } + }; + let result = op_import_spki_x25519::call(key_data, out); + result +} diff --git a/ops/optimizer_tests/uint8array.rs b/ops/optimizer_tests/uint8array.rs new file mode 100644 index 0000000000..f4507b21f5 --- /dev/null +++ b/ops/optimizer_tests/uint8array.rs @@ -0,0 +1,3 @@ +pub fn op_import_spki_x25519(key_data: &[u8], out: &mut [u8]) -> bool { + // ... +} diff --git a/ops/optimizer_tests/unit_result.expected b/ops/optimizer_tests/unit_result.expected new file mode 100644 index 0000000000..693a771e9a --- /dev/null +++ b/ops/optimizer_tests/unit_result.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: true +has_ref_opstate: false +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: false +fast_result: Some(Void) +fast_parameters: [V8Value] +transforms: {} +is_async: false +fast_compatible: true diff --git a/ops/optimizer_tests/unit_result.out b/ops/optimizer_tests/unit_result.out new file mode 100644 index 0000000000..f9d1e0c341 --- /dev/null +++ b/ops/optimizer_tests/unit_result.out @@ -0,0 +1,113 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_unit_result::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_unit_result; +#[doc(hidden)] +impl op_unit_result { + pub fn name() -> &'static str { + stringify!(op_unit_result) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_unit_result_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 0usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call() -> Result<(), AnyError> { + Ok(()) + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + { + let op_state = &mut std::cell::RefCell::borrow_mut(&ctx.state); + if let Some(err) = op_state.last_fast_op_error.take() { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + return; + } + } + let result = Self::call(); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match result { + Ok(result) => {} + Err(err) => { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + } + }; + } +} +struct op_unit_result_fast { + _phantom: ::std::marker::PhantomData<()>, +} +impl<'scope> deno_core::v8::fast_api::FastFunction for op_unit_result_fast { + fn function(&self) -> *const ::std::ffi::c_void { + op_unit_result_fast_fn as *const ::std::ffi::c_void + } + fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { + use deno_core::v8::fast_api::Type::*; + use deno_core::v8::fast_api::CType; + &[V8Value, CallbackOptions] + } + fn return_type(&self) -> deno_core::v8::fast_api::CType { + deno_core::v8::fast_api::CType::Void + } +} +fn op_unit_result_fast_fn<'scope>( + _: deno_core::v8::Local, + fast_api_callback_options: *mut deno_core::v8::fast_api::FastApiCallbackOptions, +) -> () { + use deno_core::v8; + use deno_core::_ops; + let __opts: &mut v8::fast_api::FastApiCallbackOptions = unsafe { + &mut *fast_api_callback_options + }; + let __ctx = unsafe { + &*(v8::Local::::cast(unsafe { __opts.data.data }).value() + as *const _ops::OpCtx) + }; + let op_state = &mut ::std::cell::RefCell::borrow_mut(&__ctx.state); + let result = op_unit_result::call(); + match result { + Ok(result) => result, + Err(err) => { + op_state.last_fast_op_error.replace(err); + __opts.fallback = true; + Default::default() + } + } +} diff --git a/ops/optimizer_tests/unit_result.rs b/ops/optimizer_tests/unit_result.rs new file mode 100644 index 0000000000..207896929c --- /dev/null +++ b/ops/optimizer_tests/unit_result.rs @@ -0,0 +1,3 @@ +fn op_unit_result() -> Result<(), AnyError> { + Ok(()) +} diff --git a/ops/optimizer_tests/unit_result2.expected b/ops/optimizer_tests/unit_result2.expected new file mode 100644 index 0000000000..d799a77b2f --- /dev/null +++ b/ops/optimizer_tests/unit_result2.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: true +has_ref_opstate: true +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: false +fast_result: Some(Void) +fast_parameters: [V8Value, U32, Bool] +transforms: {} +is_async: false +fast_compatible: true diff --git a/ops/optimizer_tests/unit_result2.out b/ops/optimizer_tests/unit_result2.out new file mode 100644 index 0000000000..87e0ee0b56 --- /dev/null +++ b/ops/optimizer_tests/unit_result2.out @@ -0,0 +1,149 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_set_nodelay::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_set_nodelay; +#[doc(hidden)] +impl op_set_nodelay { + pub fn name() -> &'static str { + stringify!(op_set_nodelay) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_set_nodelay_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 2usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + pub fn call( + state: &mut OpState, + rid: ResourceId, + nodelay: bool, + ) -> Result<(), AnyError> { + super::check_unstable(state, "Deno.Conn#setNoDelay"); + let resource: Rc = state + .resource_table + .get::(rid)?; + resource.set_nodelay(nodelay) + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + { + let op_state = &mut std::cell::RefCell::borrow_mut(&ctx.state); + if let Some(err) = op_state.last_fast_op_error.take() { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + return; + } + } + let arg_0 = args.get(0usize as i32); + let arg_0 = match deno_core::serde_v8::from_v8(scope, arg_0) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 0usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let arg_1 = args.get(1usize as i32); + let arg_1 = match deno_core::serde_v8::from_v8(scope, arg_1) { + Ok(v) => v, + Err(err) => { + let msg = format!( + "Error parsing args at position {}: {}", 1usize, + deno_core::anyhow::Error::from(err) + ); + return deno_core::_ops::throw_type_error(scope, msg); + } + }; + let result = Self::call( + &mut std::cell::RefCell::borrow_mut(&ctx.state), + arg_0, + arg_1, + ); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match result { + Ok(result) => {} + Err(err) => { + let exception = deno_core::error::to_v8_error( + scope, + op_state.get_error_class_fn, + &err, + ); + scope.throw_exception(exception); + } + }; + } +} +struct op_set_nodelay_fast { + _phantom: ::std::marker::PhantomData<()>, +} +impl<'scope> deno_core::v8::fast_api::FastFunction for op_set_nodelay_fast { + fn function(&self) -> *const ::std::ffi::c_void { + op_set_nodelay_fast_fn as *const ::std::ffi::c_void + } + fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { + use deno_core::v8::fast_api::Type::*; + use deno_core::v8::fast_api::CType; + &[V8Value, Uint32, Bool, CallbackOptions] + } + fn return_type(&self) -> deno_core::v8::fast_api::CType { + deno_core::v8::fast_api::CType::Void + } +} +fn op_set_nodelay_fast_fn<'scope>( + _: deno_core::v8::Local, + rid: ResourceId, + nodelay: bool, + fast_api_callback_options: *mut deno_core::v8::fast_api::FastApiCallbackOptions, +) -> () { + use deno_core::v8; + use deno_core::_ops; + let __opts: &mut v8::fast_api::FastApiCallbackOptions = unsafe { + &mut *fast_api_callback_options + }; + let __ctx = unsafe { + &*(v8::Local::::cast(unsafe { __opts.data.data }).value() + as *const _ops::OpCtx) + }; + let state = &mut ::std::cell::RefCell::borrow_mut(&__ctx.state); + let result = op_set_nodelay::call(state, rid, nodelay); + match result { + Ok(result) => result, + Err(err) => { + state.last_fast_op_error.replace(err); + __opts.fallback = true; + Default::default() + } + } +} diff --git a/ops/optimizer_tests/unit_result2.rs b/ops/optimizer_tests/unit_result2.rs new file mode 100644 index 0000000000..d3e8ced6a3 --- /dev/null +++ b/ops/optimizer_tests/unit_result2.rs @@ -0,0 +1,10 @@ +pub fn op_set_nodelay( + state: &mut OpState, + rid: ResourceId, + nodelay: bool, +) -> Result<(), AnyError> { + super::check_unstable(state, "Deno.Conn#setNoDelay"); + let resource: Rc = + state.resource_table.get::(rid)?; + resource.set_nodelay(nodelay) +} diff --git a/ops/optimizer_tests/unit_ret.expected b/ops/optimizer_tests/unit_ret.expected new file mode 100644 index 0000000000..5d414e1e33 --- /dev/null +++ b/ops/optimizer_tests/unit_ret.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: false +has_ref_opstate: false +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: false +fast_result: Some(Void) +fast_parameters: [V8Value] +transforms: {} +is_async: false +fast_compatible: true diff --git a/ops/optimizer_tests/unit_ret.out b/ops/optimizer_tests/unit_ret.out new file mode 100644 index 0000000000..c18fa19152 --- /dev/null +++ b/ops/optimizer_tests/unit_ret.out @@ -0,0 +1,84 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_unit::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_unit; +#[doc(hidden)] +impl op_unit { + pub fn name() -> &'static str { + stringify!(op_unit) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_unit_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 0usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call() -> () { + () + } + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let result = Self::call(); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + match deno_core::serde_v8::to_v8(scope, result) { + Ok(ret) => rv.set(ret), + Err(err) => { + deno_core::_ops::throw_type_error( + scope, + format!( + "Error serializing return: {}", + deno_core::anyhow::Error::from(err) + ), + ) + } + }; + } +} +struct op_unit_fast { + _phantom: ::std::marker::PhantomData<()>, +} +impl<'scope> deno_core::v8::fast_api::FastFunction for op_unit_fast { + fn function(&self) -> *const ::std::ffi::c_void { + op_unit_fast_fn as *const ::std::ffi::c_void + } + fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { + use deno_core::v8::fast_api::Type::*; + use deno_core::v8::fast_api::CType; + &[V8Value] + } + fn return_type(&self) -> deno_core::v8::fast_api::CType { + deno_core::v8::fast_api::CType::Void + } +} +fn op_unit_fast_fn<'scope>(_: deno_core::v8::Local) -> () { + use deno_core::v8; + use deno_core::_ops; + let result = op_unit::call(); + result +} diff --git a/ops/optimizer_tests/unit_ret.rs b/ops/optimizer_tests/unit_ret.rs new file mode 100644 index 0000000000..4cf3651db7 --- /dev/null +++ b/ops/optimizer_tests/unit_ret.rs @@ -0,0 +1,3 @@ +fn op_unit() -> () { + () +} diff --git a/ops/optimizer_tests/wasm_op.expected b/ops/optimizer_tests/wasm_op.expected new file mode 100644 index 0000000000..98cfb4e7db --- /dev/null +++ b/ops/optimizer_tests/wasm_op.expected @@ -0,0 +1,11 @@ +=== Optimizer Dump === +returns_result: false +has_ref_opstate: false +has_rc_opstate: false +has_fast_callback_option: false +needs_fast_callback_option: true +fast_result: Some(Void) +fast_parameters: [V8Value] +transforms: {0: Transform { kind: WasmMemory, index: 0 }} +is_async: false +fast_compatible: true diff --git a/ops/optimizer_tests/wasm_op.out b/ops/optimizer_tests/wasm_op.out new file mode 100644 index 0000000000..a40beb158e --- /dev/null +++ b/ops/optimizer_tests/wasm_op.out @@ -0,0 +1,81 @@ +#[allow(non_camel_case_types)] +///Auto-generated by `deno_ops`, i.e: `#[op]` +/// +///Use `op_wasm::decl()` to get an op-declaration +///you can include in a `deno_core::Extension`. +pub struct op_wasm; +#[doc(hidden)] +impl op_wasm { + pub fn name() -> &'static str { + stringify!(op_wasm) + } + pub fn v8_fn_ptr<'scope>() -> deno_core::v8::FunctionCallback { + use deno_core::v8::MapFnTo; + Self::v8_func.map_fn_to() + } + pub fn decl<'scope>() -> deno_core::OpDecl { + deno_core::OpDecl { + name: Self::name(), + v8_fn_ptr: Self::v8_fn_ptr(), + enabled: true, + fast_fn: Some( + Box::new(op_wasm_fast { + _phantom: ::std::marker::PhantomData, + }), + ), + is_async: false, + is_unstable: false, + is_v8: false, + argc: 1usize, + } + } + #[inline] + #[allow(clippy::too_many_arguments)] + fn call(memory: Option<&mut [u8]>) {} + pub fn v8_func<'scope>( + scope: &mut deno_core::v8::HandleScope<'scope>, + args: deno_core::v8::FunctionCallbackArguments, + mut rv: deno_core::v8::ReturnValue, + ) { + let ctx = unsafe { + &*(deno_core::v8::Local::::cast(args.data()).value() + as *const deno_core::_ops::OpCtx) + }; + let arg_0 = None; + let result = Self::call(arg_0); + let op_state = ::std::cell::RefCell::borrow(&*ctx.state); + op_state.tracker.track_sync(ctx.id); + } +} +struct op_wasm_fast { + _phantom: ::std::marker::PhantomData<()>, +} +impl<'scope> deno_core::v8::fast_api::FastFunction for op_wasm_fast { + fn function(&self) -> *const ::std::ffi::c_void { + op_wasm_fast_fn as *const ::std::ffi::c_void + } + fn args(&self) -> &'static [deno_core::v8::fast_api::Type] { + use deno_core::v8::fast_api::Type::*; + use deno_core::v8::fast_api::CType; + &[V8Value, CallbackOptions] + } + fn return_type(&self) -> deno_core::v8::fast_api::CType { + deno_core::v8::fast_api::CType::Void + } +} +fn op_wasm_fast_fn<'scope>( + _: deno_core::v8::Local, + fast_api_callback_options: *mut deno_core::v8::fast_api::FastApiCallbackOptions, +) -> () { + use deno_core::v8; + use deno_core::_ops; + let __opts: &mut v8::fast_api::FastApiCallbackOptions = unsafe { + &mut *fast_api_callback_options + }; + let memory = unsafe { + &*(__opts.wasm_memory as *const deno_core::v8::fast_api::FastApiTypedArray) + } + .get_storage_if_aligned(); + let result = op_wasm::call(memory); + result +} diff --git a/ops/optimizer_tests/wasm_op.rs b/ops/optimizer_tests/wasm_op.rs new file mode 100644 index 0000000000..b18f32fd15 --- /dev/null +++ b/ops/optimizer_tests/wasm_op.rs @@ -0,0 +1,3 @@ +fn op_wasm(memory: Option<&mut [u8]>) { + // @test-attr:wasm +} diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index d130e9edc4..a62259a1a7 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_runtime" -version = "0.87.0" +version = "0.88.0" authors.workspace = true edition.workspace = true license.workspace = true @@ -12,6 +12,8 @@ description = "Provides the deno runtime library" [features] # "fake" feature that allows to generate docs on docs.rs docsrs = [] +# feature that modifies the snapshot to allow extending it +snapshot_from_snapshot = [] [lib] name = "deno_runtime" diff --git a/runtime/build.rs b/runtime/build.rs index bab7745cc3..5887941cab 100644 --- a/runtime/build.rs +++ b/runtime/build.rs @@ -120,7 +120,7 @@ mod not_docs { } fn create_runtime_snapshot(snapshot_path: PathBuf, files: Vec) { - let extensions: Vec = vec![ + let extensions_with_js: Vec = vec![ deno_webidl::init(), deno_console::init(), deno_url::init(), @@ -154,7 +154,8 @@ mod not_docs { cargo_manifest_dir: env!("CARGO_MANIFEST_DIR"), snapshot_path, startup_snapshot: None, - extensions, + extensions: vec![], + extensions_with_js, additional_files: files, compression_cb: Some(Box::new(|vec, snapshot_slice| { lzzzz::lz4_hc::compress_to_vec( @@ -168,7 +169,14 @@ mod not_docs { } pub fn build_snapshot(runtime_snapshot_path: PathBuf) { - let js_files = get_js_files(env!("CARGO_MANIFEST_DIR"), "js"); + #[allow(unused_mut)] + let mut js_files = get_js_files(env!("CARGO_MANIFEST_DIR"), "js"); + #[cfg(not(feature = "snapshot_from_snapshot"))] + { + let manifest = env!("CARGO_MANIFEST_DIR"); + let path = PathBuf::from(manifest); + js_files.push(path.join("js").join("99_main.js")); + } create_runtime_snapshot(runtime_snapshot_path, js_files); } } diff --git a/runtime/js/40_spawn.js b/runtime/js/40_spawn.js index 8f44c89292..863063e3f6 100644 --- a/runtime/js/40_spawn.js +++ b/runtime/js/40_spawn.js @@ -277,136 +277,44 @@ }; } - class Command { - #command; - #options; + function createCommand(spawn, spawnSync, spawnChild) { + return class Command { + #command; + #options; - #child; + constructor(command, options) { + this.#command = command; + this.#options = options; + } - #consumed; - - constructor(command, options) { - this.#command = command; - this.#options = options; - } - - output() { - if (this.#child) { - return this.#child.output(); - } else { - if (this.#consumed) { - throw new TypeError( - "Command instance is being or has already been consumed.", - ); - } + output() { if (this.#options?.stdin === "piped") { throw new TypeError( "Piped stdin is not supported for this function, use 'Deno.Command.spawn()' instead", ); } - - this.#consumed = true; - return Deno.spawn(this.#command, this.#options); - } - } - - outputSync() { - if (this.#consumed) { - throw new TypeError( - "Command instance is being or has already been consumed.", - ); - } - if (this.#child) { - throw new TypeError("Was spawned"); - } - if (this.#options?.stdin === "piped") { - throw new TypeError( - "Piped stdin is not supported for this function, use 'Deno.Command.spawn()' instead", - ); + return spawn(this.#command, this.#options); } - this.#consumed = true; - return Deno.spawnSync(this.#command, this.#options); - } - - spawn() { - if (this.#consumed) { - throw new TypeError( - "Command instance is being or has already been consumed.", - ); + outputSync() { + if (this.#options?.stdin === "piped") { + throw new TypeError( + "Piped stdin is not supported for this function, use 'Deno.Command.spawn()' instead", + ); + } + return spawnSync(this.#command, this.#options); } - this.#consumed = true; - this.#child = Deno.spawnChild(this.#command, this.#options); - } - - get stdin() { - if (!this.#child) { - throw new TypeError("Wasn't spawned"); + spawn() { + return spawnChild(this.#command, this.#options); } - - return this.#child.stdin; - } - - get stdout() { - if (!this.#child) { - throw new TypeError("Wasn't spawned"); - } - - return this.#child.stdout; - } - - get stderr() { - if (!this.#child) { - throw new TypeError("Wasn't spawned"); - } - - return this.#child.stderr; - } - - get status() { - if (!this.#child) { - throw new TypeError("Wasn't spawned"); - } - - return this.#child.status; - } - - get pid() { - if (!this.#child) { - throw new TypeError("Wasn't spawned"); - } - - return this.#child.pid; - } - - kill(signo = "SIGTERM") { - if (!this.#child) { - throw new TypeError("Wasn't spawned"); - } - this.#child.kill(signo); - } - - ref() { - if (!this.#child) { - throw new TypeError("Wasn't spawned"); - } - - this.#child.ref(); - } - - unref() { - if (!this.#child) { - throw new TypeError("Wasn't spawned"); - } - - this.#child.unref(); - } + }; } window.__bootstrap.spawn = { Child, - Command, + ChildProcess: Child, + createCommand, createSpawn, createSpawnChild, createSpawnSync, diff --git a/runtime/js/90_deno_ns.js b/runtime/js/90_deno_ns.js index cd6c07464c..e3ccf1b6fd 100644 --- a/runtime/js/90_deno_ns.js +++ b/runtime/js/90_deno_ns.js @@ -144,6 +144,7 @@ funlock: __bootstrap.fs.funlock, funlockSync: __bootstrap.fs.funlockSync, Child: __bootstrap.spawn.Child, + ChildProcess: __bootstrap.spawn.ChildProcess, spawnChild: __bootstrap.spawn.spawnChild, spawn: __bootstrap.spawn.spawn, spawnSync: __bootstrap.spawn.spawnSync, diff --git a/runtime/js/99_main.js b/runtime/js/99_main.js index 2ea3504e2c..adfc0d3602 100644 --- a/runtime/js/99_main.js +++ b/runtime/js/99_main.js @@ -482,6 +482,14 @@ delete Intl.v8BreakIterator; }, }); + ObjectAssign(internals.nodeUnstable, { + Command: __bootstrap.spawn.createCommand( + internals.nodeUnstable.spawn, + internals.nodeUnstable.spawnSync, + internals.nodeUnstable.spawnChild, + ), + }); + const finalDenoNs = { core, internal: internalSymbol, @@ -513,6 +521,14 @@ delete Intl.v8BreakIterator; ops.op_net_listen_unixpacket, ), }); + + ObjectAssign(finalDenoNs, { + Command: __bootstrap.spawn.createCommand( + finalDenoNs.spawn, + finalDenoNs.spawnSync, + finalDenoNs.spawnChild, + ), + }); } // Setup `Deno` global - we're actually overriding already existing global @@ -617,6 +633,14 @@ delete Intl.v8BreakIterator; }, }); + ObjectAssign(internals.nodeUnstable, { + Command: __bootstrap.spawn.createCommand( + internals.nodeUnstable.spawn, + internals.nodeUnstable.spawnSync, + internals.nodeUnstable.spawnChild, + ), + }); + const finalDenoNs = { core, internal: internalSymbol, @@ -640,6 +664,13 @@ delete Intl.v8BreakIterator; ops.op_net_listen_unixpacket, ), }); + ObjectAssign(finalDenoNs, { + Command: __bootstrap.spawn.createCommand( + finalDenoNs.spawn, + finalDenoNs.spawnSync, + finalDenoNs.spawnChild, + ), + }); } ObjectDefineProperties(finalDenoNs, { pid: util.readOnly(runtimeOptions.pid), diff --git a/runtime/ops/fs.rs b/runtime/ops/fs.rs index ebd24ebe05..8d719393f3 100644 --- a/runtime/ops/fs.rs +++ b/runtime/ops/fs.rs @@ -524,13 +524,13 @@ fn op_umask(state: &mut OpState, mask: Option) -> Result { } #[op] -fn op_chdir(state: &mut OpState, directory: String) -> Result<(), AnyError> { +fn op_chdir(state: &mut OpState, directory: &str) -> Result<(), AnyError> { let d = PathBuf::from(&directory); state .borrow_mut::() .read .check(&d, Some("Deno.chdir()"))?; - set_current_dir(&d).map_err(|err| { + set_current_dir(d).map_err(|err| { Error::new(err.kind(), format!("{}, chdir '{}'", err, directory)) })?; Ok(()) @@ -603,10 +603,10 @@ async fn op_mkdir_async( #[op] fn op_chmod_sync( state: &mut OpState, - path: String, + path: &str, mode: u32, ) -> Result<(), AnyError> { - let path = Path::new(&path); + let path = Path::new(path); let mode = mode & 0o777; state @@ -661,11 +661,11 @@ fn raw_chmod(path: &Path, _raw_mode: u32) -> Result<(), AnyError> { #[op] fn op_chown_sync( state: &mut OpState, - path: String, + path: &str, #[cfg_attr(windows, allow(unused_variables))] uid: Option, #[cfg_attr(windows, allow(unused_variables))] gid: Option, ) -> Result<(), AnyError> { - let path = Path::new(&path).to_path_buf(); + let path = Path::new(path).to_path_buf(); state .borrow_mut::() .write @@ -734,10 +734,10 @@ async fn op_chown_async( #[op] fn op_remove_sync( state: &mut OpState, - path: String, + path: &str, recursive: bool, ) -> Result<(), AnyError> { - let path = PathBuf::from(&path); + let path = PathBuf::from(path); state .borrow_mut::() @@ -835,11 +835,11 @@ async fn op_remove_async( #[op] fn op_copy_file_sync( state: &mut OpState, - from: String, - to: String, + from: &str, + to: &str, ) -> Result<(), AnyError> { - let from_path = PathBuf::from(&from); - let to_path = PathBuf::from(&to); + let from_path = PathBuf::from(from); + let to_path = PathBuf::from(to); let permissions = state.borrow_mut::(); permissions @@ -1097,11 +1097,11 @@ pub struct StatArgs { #[op] fn op_stat_sync( state: &mut OpState, - path: String, + path: &str, lstat: bool, out_buf: &mut [u32], ) -> Result<(), AnyError> { - let path = PathBuf::from(&path); + let path = PathBuf::from(path); state .borrow_mut::() .read @@ -1313,11 +1313,11 @@ async fn op_read_dir_async( #[op] fn op_rename_sync( state: &mut OpState, - oldpath: String, - newpath: String, + oldpath: &str, + newpath: &str, ) -> Result<(), AnyError> { - let oldpath = PathBuf::from(&oldpath); - let newpath = PathBuf::from(&newpath); + let oldpath = PathBuf::from(oldpath); + let newpath = PathBuf::from(newpath); let permissions = state.borrow_mut::(); permissions @@ -1382,11 +1382,11 @@ async fn op_rename_async( #[op] fn op_link_sync( state: &mut OpState, - oldpath: String, - newpath: String, + oldpath: &str, + newpath: &str, ) -> Result<(), AnyError> { - let oldpath = PathBuf::from(&oldpath); - let newpath = PathBuf::from(&newpath); + let oldpath = PathBuf::from(oldpath); + let newpath = PathBuf::from(newpath); let permissions = state.borrow_mut::(); permissions.read.check(&oldpath, Some("Deno.linkSync()"))?; @@ -1449,12 +1449,12 @@ async fn op_link_async( #[op] fn op_symlink_sync( state: &mut OpState, - oldpath: String, - newpath: String, + oldpath: &str, + newpath: &str, _type: Option, ) -> Result<(), AnyError> { - let oldpath = PathBuf::from(&oldpath); - let newpath = PathBuf::from(&newpath); + let oldpath = PathBuf::from(oldpath); + let newpath = PathBuf::from(newpath); state .borrow_mut::() @@ -1669,10 +1669,10 @@ async fn op_ftruncate_async( #[op] fn op_truncate_sync( state: &mut OpState, - path: String, + path: &str, len: u64, ) -> Result<(), AnyError> { - let path = PathBuf::from(&path); + let path = PathBuf::from(path); state .borrow_mut::() @@ -1949,13 +1949,13 @@ async fn op_futime_async( #[op] fn op_utime_sync( state: &mut OpState, - path: String, + path: &str, atime_secs: i64, atime_nanos: u32, mtime_secs: i64, mtime_nanos: u32, ) -> Result<(), AnyError> { - let path = PathBuf::from(&path); + let path = PathBuf::from(path); let atime = filetime::FileTime::from_unix_time(atime_secs, atime_nanos); let mtime = filetime::FileTime::from_unix_time(mtime_secs, mtime_nanos); diff --git a/runtime/ops/io.rs b/runtime/ops/io.rs index 8ed6969f9c..186052afe6 100644 --- a/runtime/ops/io.rs +++ b/runtime/ops/io.rs @@ -16,7 +16,6 @@ use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; -use deno_core::ZeroCopyBuf; use once_cell::sync::Lazy; use std::borrow::Cow; use std::cell::RefCell; @@ -671,7 +670,7 @@ impl Resource for StdFileResource { #[op] pub fn op_print( state: &mut OpState, - msg: String, + msg: &str, is_err: bool, ) -> Result<(), AnyError> { let rid = if is_err { 2 } else { 1 }; @@ -683,32 +682,32 @@ pub fn op_print( }) } -#[op] +#[op(fast)] fn op_read_sync( state: &mut OpState, - rid: ResourceId, - mut buf: ZeroCopyBuf, + rid: u32, + buf: &mut [u8], ) -> Result { StdFileResource::with_resource(state, rid, move |resource| { resource.with_inner_and_metadata(|inner, _| { inner - .read(&mut buf) + .read(buf) .map(|n: usize| n as u32) .map_err(AnyError::from) }) }) } -#[op] +#[op(fast)] fn op_write_sync( state: &mut OpState, - rid: ResourceId, - buf: ZeroCopyBuf, + rid: u32, + buf: &mut [u8], ) -> Result { StdFileResource::with_resource(state, rid, move |resource| { resource.with_inner_and_metadata(|inner, _| { inner - .write_and_maybe_flush(&buf) + .write_and_maybe_flush(buf) .map(|nwritten: usize| nwritten as u32) .map_err(AnyError::from) }) diff --git a/runtime/ops/os/mod.rs b/runtime/ops/os/mod.rs index b93935955b..844fbaecc0 100644 --- a/runtime/ops/os/mod.rs +++ b/runtime/ops/os/mod.rs @@ -78,10 +78,10 @@ fn op_exec_path(state: &mut OpState) -> Result { #[op] fn op_set_env( state: &mut OpState, - key: String, - value: String, + key: &str, + value: &str, ) -> Result<(), AnyError> { - state.borrow_mut::().env.check(&key)?; + state.borrow_mut::().env.check(key)?; if key.is_empty() { return Err(type_error("Key is an empty string.")); } diff --git a/runtime/ops/signal.rs b/runtime/ops/signal.rs index 95c166787c..66530a8384 100644 --- a/runtime/ops/signal.rs +++ b/runtime/ops/signal.rs @@ -453,9 +453,9 @@ pub fn signal_int_to_str(s: libc::c_int) -> Result<&'static str, AnyError> { #[op] fn op_signal_bind( state: &mut OpState, - sig: String, + sig: &str, ) -> Result { - let signo = signal_str_to_int(&sig)?; + let signo = signal_str_to_int(sig)?; if signal_hook_registry::FORBIDDEN.contains(&signo) { return Err(type_error(format!( "Binding to signal '{}' is not allowed", @@ -474,9 +474,9 @@ fn op_signal_bind( #[op] fn op_signal_bind( state: &mut OpState, - sig: String, + sig: &str, ) -> Result { - let signo = signal_str_to_int(&sig)?; + let signo = signal_str_to_int(sig)?; let resource = SignalStreamResource { signal: AsyncRefCell::new(match signo { // SIGINT diff --git a/runtime/ops/tty.rs b/runtime/ops/tty.rs index 6382f967fc..f807889051 100644 --- a/runtime/ops/tty.rs +++ b/runtime/ops/tty.rs @@ -16,10 +16,6 @@ use deno_core::error::custom_error; use winapi::shared::minwindef::DWORD; #[cfg(windows)] use winapi::um::wincon; -#[cfg(windows)] -const RAW_MODE_MASK: DWORD = wincon::ENABLE_LINE_INPUT - | wincon::ENABLE_ECHO_INPUT - | wincon::ENABLE_PROCESSED_INPUT; #[cfg(windows)] fn get_windows_handle( @@ -85,11 +81,16 @@ fn op_stdin_set_raw( { return Err(Error::last_os_error().into()); } + + const RAW_MODE_MASK: DWORD = wincon::ENABLE_LINE_INPUT + | wincon::ENABLE_ECHO_INPUT + | wincon::ENABLE_PROCESSED_INPUT; let new_mode = if is_raw { - original_mode & !RAW_MODE_MASK + original_mode & !RAW_MODE_MASK | wincon::ENABLE_VIRTUAL_TERMINAL_INPUT } else { - original_mode | RAW_MODE_MASK + original_mode | RAW_MODE_MASK & !wincon::ENABLE_VIRTUAL_TERMINAL_INPUT }; + // SAFETY: winapi call if unsafe { consoleapi::SetConsoleMode(handle, new_mode) } == FALSE { return Err(Error::last_os_error().into()); diff --git a/runtime/web_worker.rs b/runtime/web_worker.rs index a8e0842f22..ee47d0d990 100644 --- a/runtime/web_worker.rs +++ b/runtime/web_worker.rs @@ -17,6 +17,7 @@ use deno_core::futures::channel::mpsc; use deno_core::futures::future::poll_fn; use deno_core::futures::stream::StreamExt; use deno_core::futures::task::AtomicWaker; +use deno_core::located_script_name; use deno_core::serde::Deserialize; use deno_core::serde::Serialize; use deno_core::serde_json::json; @@ -31,8 +32,8 @@ use deno_core::ModuleLoader; use deno_core::ModuleSpecifier; use deno_core::RuntimeOptions; use deno_core::SharedArrayBufferStore; +use deno_core::Snapshot; use deno_core::SourceMapGetter; -use deno_core::{located_script_name, Snapshot}; use deno_node::RequireNpmResolver; use deno_tls::rustls::RootCertStore; use deno_web::create_entangled_message_port; @@ -472,6 +473,12 @@ impl WebWorker { &mut js_runtime, false, ); + + // Put inspector handle into the op state so we can put a breakpoint when + // executing a CJS entrypoint. + let op_state = js_runtime.op_state(); + let inspector = js_runtime.inspector(); + op_state.borrow_mut().put(inspector); } let (internal_handle, external_handle) = { diff --git a/runtime/worker.rs b/runtime/worker.rs index 0c439c703b..01498e1f62 100644 --- a/runtime/worker.rs +++ b/runtime/worker.rs @@ -240,6 +240,7 @@ impl MainWorker { compiled_wasm_module_store: options.compiled_wasm_module_store.clone(), extensions, inspector: options.maybe_inspector_server.is_some(), + is_main: true, ..Default::default() }); @@ -249,6 +250,12 @@ impl MainWorker { &mut js_runtime, options.should_break_on_first_statement, ); + + // Put inspector handle into the op state so we can put a breakpoint when + // executing a CJS entrypoint. + let op_state = js_runtime.op_state(); + let inspector = js_runtime.inspector(); + op_state.borrow_mut().put(inspector); } Self { diff --git a/serde_v8/Cargo.toml b/serde_v8/Cargo.toml index 8ad0c553e6..2e412130ee 100644 --- a/serde_v8/Cargo.toml +++ b/serde_v8/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "serde_v8" -version = "0.72.0" +version = "0.73.0" authors.workspace = true edition.workspace = true license.workspace = true diff --git a/serde_v8/magic/detached_buffer.rs b/serde_v8/magic/detached_buffer.rs index 78232cbe77..cbe8b39c39 100644 --- a/serde_v8/magic/detached_buffer.rs +++ b/serde_v8/magic/detached_buffer.rs @@ -63,7 +63,7 @@ impl FromV8 for DetachedBuffer { return Err(crate::Error::ExpectedDetachable); } let store = b.get_backing_store(); - b.detach(v8::undefined(scope).into()); // Detach + b.detach(None); // Detach Ok(Self(V8Slice { store, range })) } } diff --git a/test_ffi/src/lib.rs b/test_ffi/src/lib.rs index be0d2e42f8..1c1770bf02 100644 --- a/test_ffi/src/lib.rs +++ b/test_ffi/src/lib.rs @@ -45,8 +45,8 @@ pub extern "C" fn return_buffer() -> *const u8 { } #[no_mangle] -pub extern "C" fn is_null_ptr(ptr: *const u8) -> u8 { - ptr.is_null() as u8 +pub extern "C" fn is_null_ptr(ptr: *const u8) -> bool { + ptr.is_null() } #[no_mangle] diff --git a/test_ffi/tests/ffi_types.ts b/test_ffi/tests/ffi_types.ts index e2054cfe1b..a49224cfdc 100644 --- a/test_ffi/tests/ffi_types.ts +++ b/test_ffi/tests/ffi_types.ts @@ -5,7 +5,7 @@ const remote = Deno.dlopen( "dummy_lib.so", { - method1: { parameters: ["usize", "usize"], result: "void", callback: true }, + method1: { parameters: ["usize", "bool"], result: "void", callback: true }, method2: { parameters: [], result: "void" }, method3: { parameters: ["usize"], result: "void" }, method4: { parameters: ["isize"], result: "void" }, @@ -61,16 +61,16 @@ const remote = Deno.dlopen( static13: { type: "f32" }, static14: { type: "f64" }, static15: { type: "bool" }, - } as const, + }, ); Deno.dlopen( "dummy_lib_2.so", - // @ts-expect-error: Returning a function pointer // is declared using "pointer" or "function" + UnsafeFnPointer { wrong_method1: { parameters: [], + // @ts-expect-error not assignable to type 'NativeResultType' result: { function: { parameters: [], @@ -78,14 +78,18 @@ Deno.dlopen( }, }, }, - } as const, + }, ); // @ts-expect-error: Invalid argument remote.symbols.method1(0); +// @ts-expect-error: Invalid argument +remote.symbols.method1(0, 0); +// @ts-expect-error: Invalid argument +remote.symbols.method1(true, true); // @ts-expect-error: Invalid return type - remote.symbols.method1(0, 0); - remote.symbols.method1(0n, 0n); + remote.symbols.method1(0, true); + remote.symbols.method1(0n, true); // @ts-expect-error: Expected 0 arguments, but got 1. remote.symbols.method2(null); @@ -170,7 +174,7 @@ const fnptr = new Deno.UnsafeFnPointer( { parameters: ["u32", "pointer"], result: "void", - } as const, + }, ); // @ts-expect-error: Invalid argument fnptr.call(null, null); @@ -180,7 +184,7 @@ const unsafe_callback_wrong1 = new Deno.UnsafeCallback( { parameters: ["i8"], result: "void", - } as const, + }, // @ts-expect-error: i8 is not a pointer (_: bigint) => {}, ); @@ -188,7 +192,7 @@ const unsafe_callback_wrong2 = new Deno.UnsafeCallback( { parameters: ["pointer"], result: "u64", - } as const, + }, // @ts-expect-error: must return a number or bigint (_: Deno.UnsafePointer) => {}, ); @@ -196,7 +200,7 @@ const unsafe_callback_wrong3 = new Deno.UnsafeCallback( { parameters: [], result: "void", - } as const, + }, // @ts-expect-error: no parameters (_: Deno.UnsafePointer) => {}, ); @@ -204,7 +208,7 @@ const unsafe_callback_wrong4 = new Deno.UnsafeCallback( { parameters: ["u64"], result: "void", - } as const, + }, // @ts-expect-error: Callback's 64bit parameters are either number or bigint (_: number) => {}, ); @@ -212,21 +216,21 @@ const unsafe_callback_right1 = new Deno.UnsafeCallback( { parameters: ["u8", "u32", "pointer"], result: "void", - } as const, + }, (_1: number, _2: number, _3: Deno.PointerValue) => {}, ); const unsafe_callback_right2 = new Deno.UnsafeCallback( { parameters: [], result: "u8", - } as const, + }, () => 3, ); const unsafe_callback_right3 = new Deno.UnsafeCallback( { parameters: [], result: "function", - } as const, + }, // Callbacks can return other callbacks' pointers, if really wanted. () => unsafe_callback_right2.pointer, ); @@ -234,14 +238,14 @@ const unsafe_callback_right4 = new Deno.UnsafeCallback( { parameters: ["u8", "u32", "pointer"], result: "u8", - } as const, + }, (_1: number, _2: number, _3: Deno.PointerValue) => 3, ); const unsafe_callback_right5 = new Deno.UnsafeCallback( { parameters: ["u8", "i32", "pointer"], result: "void", - } as const, + }, (_1: number, _2: number, _3: Deno.PointerValue) => {}, ); diff --git a/test_ffi/tests/test.js b/test_ffi/tests/test.js index 0af94b9065..65cb974f91 100644 --- a/test_ffi/tests/test.js +++ b/test_ffi/tests/test.js @@ -3,7 +3,7 @@ // Run using cargo test or `--v8-options=--allow-natives-syntax` -import { assertEquals } from "https://deno.land/std@0.149.0/testing/asserts.ts"; +import { assertEquals, assertNotEquals } from "https://deno.land/std@0.149.0/testing/asserts.ts"; import { assertThrows, assert, @@ -50,7 +50,8 @@ const dylib = Deno.dlopen(libPath, { result: "void", }, "return_buffer": { parameters: [], result: "buffer" }, - "is_null_ptr": { parameters: ["pointer"], result: "u8" }, + "is_null_ptr": { parameters: ["pointer"], result: "bool" }, + "is_null_buf": { name: "is_null_ptr", parameters: ["buffer"], result: "bool" }, "add_u32": { parameters: ["u32", "u32"], result: "u32" }, "add_i32": { parameters: ["i32", "i32"], result: "i32" }, "add_u64": { parameters: ["u64", "u64"], result: "u64" }, @@ -251,13 +252,56 @@ const stringPtr = Deno.UnsafePointer.of(string); const stringPtrview = new Deno.UnsafePointerView(stringPtr); console.log(stringPtrview.getCString()); console.log(stringPtrview.getCString(11)); -console.log(Boolean(dylib.symbols.is_null_ptr(ptr0))); -console.log(Boolean(dylib.symbols.is_null_ptr(null))); -console.log(Boolean(dylib.symbols.is_null_ptr(Deno.UnsafePointer.of(into)))); -const emptyBuffer = new BigUint64Array(0); -console.log(Boolean(dylib.symbols.is_null_ptr(Deno.UnsafePointer.of(emptyBuffer)))); +console.log(dylib.symbols.is_null_ptr(ptr0)); +console.log(dylib.symbols.is_null_ptr(null)); +console.log(dylib.symbols.is_null_ptr(Deno.UnsafePointer.of(into))); +const emptyBuffer = new Uint8Array(0); +console.log(dylib.symbols.is_null_ptr(Deno.UnsafePointer.of(emptyBuffer))); const emptySlice = into.subarray(6); -console.log(Boolean(dylib.symbols.is_null_ptr(Deno.UnsafePointer.of(emptySlice)))); +console.log(dylib.symbols.is_null_ptr(Deno.UnsafePointer.of(emptySlice))); + +const { is_null_buf } = symbols; +function isNullBuffer(buffer) { return is_null_buf(buffer); }; +function isNullBufferDeopt(buffer) { return is_null_buf(buffer); }; +%PrepareFunctionForOptimization(isNullBuffer); +isNullBuffer(emptyBuffer); +%NeverOptimizeFunction(isNullBufferDeopt); +%OptimizeFunctionOnNextCall(isNullBuffer); +isNullBuffer(emptyBuffer); +assertIsOptimized(isNullBuffer); + +// ==== ZERO LENGTH BUFFER TESTS ==== +assertEquals(isNullBuffer(emptyBuffer), true, "isNullBuffer(emptyBuffer) !== true"); +assertEquals(isNullBufferDeopt(emptyBuffer), true, "isNullBufferDeopt(emptyBuffer) !== true"); +assertEquals(isNullBuffer(emptySlice), false, "isNullBuffer(emptySlice) !== false"); +assertEquals(isNullBufferDeopt(emptySlice), false, "isNullBufferDeopt(emptySlice) !== false"); +assertEquals(isNullBufferDeopt(new Uint8Array()), true, "isNullBufferDeopt(new Uint8Array()) !== true"); + +// ==== V8 ZERO LENGTH BUFFER ANOMALIES ==== + +// V8 bug: inline Uint8Array creation to fast call sees non-null pointer +// https://bugs.chromium.org/p/v8/issues/detail?id=13489 +assertEquals(isNullBuffer(new Uint8Array()), false, "isNullBuffer(new Uint8Array()) !== false"); + +// Externally backed ArrayBuffer has a non-null data pointer, even though its length is zero. +const externalZeroBuffer = new Uint8Array(Deno.UnsafePointerView.getArrayBuffer(ptr0, 0)); +// However: V8 Fast calls get null pointers for zero-sized buffers. +assertEquals(isNullBuffer(externalZeroBuffer), true, "isNullBuffer(externalZeroBuffer) !== true"); +// Also: V8's `Local->Data()` method returns null pointers for zero-sized buffers. +// Using `Local->GetBackingStore()->Data()` would give the original pointer. +assertEquals(isNullBufferDeopt(externalZeroBuffer), true, "isNullBufferDeopt(externalZeroBuffer) !== true"); + +// The same pointer with a non-zero byte length for the buffer will return non-null pointers in +// both Fast call and V8 API calls. +const externalOneBuffer = new Uint8Array(Deno.UnsafePointerView.getArrayBuffer(ptr0, 1)); +assertEquals(isNullBuffer(externalOneBuffer), false, "isNullBuffer(externalOneBuffer) !== false"); +assertEquals(isNullBufferDeopt(externalOneBuffer), false, "isNullBufferDeopt(externalOneBuffer) !== false"); + +// Due to ops macro using `Local->Data()` to get the pointer for the slice that is then used to get +// the pointer of an ArrayBuffer / TypedArray, the same effect can be seen where a zero byte length buffer returns +// a null pointer as its pointer value. +assertEquals(Deno.UnsafePointer.of(externalZeroBuffer), 0, "Deno.UnsafePointer.of(externalZeroBuffer) !== 0"); +assertNotEquals(Deno.UnsafePointer.of(externalOneBuffer), 0, "Deno.UnsafePointer.of(externalOneBuffer) !== 0"); const addU32Ptr = dylib.symbols.get_add_u32_ptr(); const addU32 = new Deno.UnsafeFnPointer(addU32Ptr, { diff --git a/test_util/src/lib.rs b/test_util/src/lib.rs index 3b23af7364..b1b14c0040 100644 --- a/test_util/src/lib.rs +++ b/test_util/src/lib.rs @@ -94,6 +94,24 @@ lazy_static! { static ref GUARD: Mutex = Mutex::new(HttpServerCount::default()); } +pub fn env_vars_for_npm_tests_no_sync_download() -> Vec<(String, String)> { + vec![ + ("DENO_NODE_COMPAT_URL".to_string(), std_file_url()), + ("DENO_NPM_REGISTRY".to_string(), npm_registry_url()), + ("NO_COLOR".to_string(), "1".to_string()), + ] +} + +pub fn env_vars_for_npm_tests() -> Vec<(String, String)> { + let mut env_vars = env_vars_for_npm_tests_no_sync_download(); + env_vars.push(( + // make downloads determinstic + "DENO_UNSTABLE_NPM_SYNC_DOWNLOAD".to_string(), + "1".to_string(), + )); + env_vars +} + pub fn root_path() -> PathBuf { PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"))) .parent() diff --git a/test_util/src/lsp.rs b/test_util/src/lsp.rs index c0fd8ff1b0..b2c28268e0 100644 --- a/test_util/src/lsp.rs +++ b/test_util/src/lsp.rs @@ -159,7 +159,7 @@ pub struct LspClient { request_id: u64, start: Instant, writer: io::BufWriter, - _temp_deno_dir: TempDir, // directory will be deleted on drop + deno_dir: TempDir, } impl Drop for LspClient { @@ -255,10 +255,14 @@ impl LspClient { request_id: 1, start: Instant::now(), writer, - _temp_deno_dir: deno_dir, + deno_dir, }) } + pub fn deno_dir(&self) -> &TempDir { + &self.deno_dir + } + pub fn duration(&self) -> Duration { self.start.elapsed() } diff --git a/test_util/std b/test_util/std index c56a8c4e32..10834cd64f 160000 --- a/test_util/std +++ b/test_util/std @@ -1 +1 @@ -Subproject commit c56a8c4e3245dd9ea1a892d2f2150ddba57f29c3 +Subproject commit 10834cd64f7ed268c8151ea5b5d3aa4b4f3c036c diff --git a/tools/flamebench.js b/tools/flamebench.js index 54705d2664..7c79bd10fc 100755 --- a/tools/flamebench.js +++ b/tools/flamebench.js @@ -3,11 +3,11 @@ import { join, ROOT_PATH as ROOT } from "./util.js"; async function bashOut(subcmd) { - const { success, stdout } = await Deno.spawn("bash", { + const { success, stdout } = await new Deno.Command("bash", { args: ["-c", subcmd], stdout: "piped", stderr: "null", - }); + }).output(); // Check for failure if (!success) { @@ -20,12 +20,12 @@ async function bashOut(subcmd) { } async function bashThrough(subcmd, opts = {}) { - const { success, code } = await Deno.spawn("bash", { + const { success, code } = await new Deno.Command("bash", { ...opts, args: ["-c", subcmd], stdout: "inherit", stderr: "inherit", - }); + }).output(); // Exit process on failure if (!success) { diff --git a/tools/format.js b/tools/format.js index fe18352f36..b13159613a 100755 --- a/tools/format.js +++ b/tools/format.js @@ -5,12 +5,15 @@ import { getPrebuiltToolPath, join, ROOT_PATH } from "./util.js"; async function dprint() { const configFile = join(ROOT_PATH, ".dprint.json"); const execPath = getPrebuiltToolPath("dprint"); - const { success } = await Deno.spawn(execPath, { + const cmd = new Deno.Command(execPath, { args: ["fmt", "--config=" + configFile], stdout: "inherit", stderr: "inherit", }); - if (!success) { + + const { code } = await cmd.output(); + + if (code > 0) { throw new Error("dprint failed"); } } @@ -20,12 +23,14 @@ async function main() { await dprint(); if (Deno.args.includes("--check")) { - const { success, stdout } = await Deno.spawn("git", { + const cmd = new Deno.Command("git", { args: ["status", "-uno", "--porcelain", "--ignore-submodules"], stderr: "inherit", }); - if (!success) { + const { code, stdout } = await cmd.output(); + + if (code > 0) { throw new Error("git status failed"); } const out = new TextDecoder().decode(stdout); diff --git a/tools/lint.js b/tools/lint.js index 4e842c2b95..baa1e9c3c0 100755 --- a/tools/lint.js +++ b/tools/lint.js @@ -43,12 +43,14 @@ async function dlint() { const chunks = splitToChunks(sourceFiles, `${execPath} run`.length); for (const chunk of chunks) { - const { success } = await Deno.spawn(execPath, { + const cmd = new Deno.Command(execPath, { args: ["run", "--config=" + configFile, ...chunk], stdout: "inherit", stderr: "inherit", }); - if (!success) { + const { code } = await cmd.output(); + + if (code > 0) { throw new Error("dlint failed"); } } @@ -74,12 +76,14 @@ async function dlintPreferPrimordials() { const chunks = splitToChunks(sourceFiles, `${execPath} run`.length); for (const chunk of chunks) { - const { success } = await Deno.spawn(execPath, { + const cmd = new Deno.Command(execPath, { args: ["run", "--rule", "prefer-primordials", ...chunk], stdout: "inherit", stderr: "inherit", }); - if (!success) { + const { code } = await cmd.output(); + + if (code > 0) { throw new Error("prefer-primordials failed"); } } @@ -111,24 +115,19 @@ async function clippy() { cmd.push("--release"); } - const { success } = await Deno.spawn("cargo", { + const cargoCmd = new Deno.Command("cargo", { args: [ ...cmd, "--", "-D", "warnings", - "-A", - // https://github.com/rust-lang/rust-clippy/issues/407 - "clippy::extra_unused_lifetimes", - "-A", - // https://github.com/rust-lang/rust-clippy/issues/7271 - // False positives in core/resources.rs for lifetime elision. - "clippy::needless_lifetimes", ], stdout: "inherit", stderr: "inherit", }); - if (!success) { + const { code } = await cargoCmd.output(); + + if (code > 0) { throw new Error("clippy failed"); } } diff --git a/tools/napi/generate_symbols_lists.js b/tools/napi/generate_symbols_lists.js index fbef69edde..2da9ccff79 100755 --- a/tools/napi/generate_symbols_lists.js +++ b/tools/napi/generate_symbols_lists.js @@ -1,7 +1,7 @@ #!/usr/bin/env -S deno run --unstable --allow-read --allow-write // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. -import exports from "../../cli/napi_sym/symbol_exports.json" assert { +import exports from "../../cli/napi/sym/symbol_exports.json" assert { type: "json", }; diff --git a/tools/util.js b/tools/util.js index d164ca954e..49279df583 100644 --- a/tools/util.js +++ b/tools/util.js @@ -14,10 +14,10 @@ export { delay } from "../test_util/std/async/delay.ts"; export const ROOT_PATH = dirname(dirname(fromFileUrl(import.meta.url))); async function getFilesFromGit(baseDir, args) { - const { success, stdout } = await Deno.spawn("git", { + const { success, stdout } = await new Deno.Command("git", { stderr: "inherit", args, - }); + }).output(); const output = new TextDecoder().decode(stdout); if (!success) { throw new Error("gitLsFiles failed"); diff --git a/tools/wgpu_sync.js b/tools/wgpu_sync.js index 4d343878b6..7548c55151 100755 --- a/tools/wgpu_sync.js +++ b/tools/wgpu_sync.js @@ -9,12 +9,12 @@ const V_WGPU = "0.13"; const TARGET_DIR = join(ROOT_PATH, "ext", "webgpu"); async function bash(subcmd, opts = {}) { - const { success, code } = await Deno.spawn("bash", { + const { success, code } = await new Deno.Command("bash", { ...opts, args: ["-c", subcmd], stdout: "inherit", sdterr: "inherit", - }); + }).output(); // Exit process on failure if (!success) { diff --git a/tools/wpt/expectation.json b/tools/wpt/expectation.json index c58b8934f1..cc026e9882 100644 --- a/tools/wpt/expectation.json +++ b/tools/wpt/expectation.json @@ -2555,13 +2555,9 @@ "request-consume.any.html": true, "request-consume.any.worker.html": true, "request-disturbed.any.html": [ - "Request construction failure should not set \"bodyUsed\"", - "Input request used for creating new request became disturbed", "Input request used for creating new request became disturbed even if body is not used" ], "request-disturbed.any.worker.html": [ - "Request construction failure should not set \"bodyUsed\"", - "Input request used for creating new request became disturbed", "Input request used for creating new request became disturbed even if body is not used" ], "request-error.any.html": [ diff --git a/tools/wpt/runner.ts b/tools/wpt/runner.ts index 269e6ffd18..517ce42b5d 100644 --- a/tools/wpt/runner.ts +++ b/tools/wpt/runner.ts @@ -107,14 +107,14 @@ export async function runSingleTest( "[]", ); - const proc = Deno.spawnChild(denoBinary(), { + const proc = new Deno.Command(denoBinary(), { args, env: { NO_COLOR: "1", }, stdout: "null", stderr: "piped", - }); + }).spawn(); const cases = []; let stderr = ""; diff --git a/tools/wpt/utils.ts b/tools/wpt/utils.ts index c77effa624..7614a0c553 100644 --- a/tools/wpt/utils.ts +++ b/tools/wpt/utils.ts @@ -118,18 +118,18 @@ export function assert(condition: unknown, message: string): asserts condition { } } -export function runPy>( +export function runPy>( args: string[], options: T, -): Deno.Child { +): Deno.ChildProcess { const cmd = Deno.build.os == "windows" ? "python.exe" : "python3"; - return Deno.spawnChild(cmd, { + return new Deno.Command(cmd, { args, stdout: "inherit", stderr: "inherit", ...options, cwd: join(ROOT_PATH, "./test_util/wpt/"), - }); + }).spawn(); } export async function checkPy3Available() { @@ -148,12 +148,12 @@ export async function checkPy3Available() { export async function cargoBuild() { if (binary) return; - const { success } = await Deno.spawn("cargo", { + const { success } = await new Deno.Command("cargo", { args: ["build", ...(release ? ["--release"] : [])], cwd: ROOT_PATH, stdout: "inherit", stderr: "inherit", - }); + }).output(); assert(success, "cargo build failed"); } @@ -175,16 +175,16 @@ export async function generateRunInfo(): Promise { "darwin": "mac", "linux": "linux", }; - const proc = await Deno.spawn("git", { + const proc = await new Deno.Command("git", { args: ["rev-parse", "HEAD"], cwd: join(ROOT_PATH, "test_util", "wpt"), stderr: "inherit", - }); + }).output(); const revision = (new TextDecoder().decode(proc.stdout)).trim(); - const proc2 = await Deno.spawn(denoBinary(), { + const proc2 = await new Deno.Command(denoBinary(), { args: ["eval", "console.log(JSON.stringify(Deno.version))"], cwd: join(ROOT_PATH, "test_util", "wpt"), - }); + }).output(); const version = JSON.parse(new TextDecoder().decode(proc2.stdout)); const runInfo = { "os": oses[Deno.build.os],