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

Merge branch 'main' into open-flag-on-serve

This commit is contained in:
HasanAlrimawi 2024-11-20 10:02:05 +02:00 committed by GitHub
commit 47c063544b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
144 changed files with 1679 additions and 423 deletions

View file

@ -31,6 +31,8 @@
"cli/tsc/dts/lib.scripthost.d.ts",
"cli/tsc/dts/lib.webworker*.d.ts",
"cli/tsc/dts/typescript.d.ts",
"cli/tools/doc/prism.css",
"cli/tools/doc/prism.js",
"ext/websocket/autobahn/reports",
"gh-pages",
"target",

252
Cargo.lock generated
View file

@ -128,6 +128,19 @@ version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f"
[[package]]
name = "ammonia"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ab99eae5ee58501ab236beb6f20f6ca39be615267b014899c89b2f0bc18a459"
dependencies = [
"html5ever",
"maplit",
"once_cell",
"tendril",
"url",
]
[[package]]
name = "android_system_properties"
version = "0.1.5"
@ -882,9 +895,9 @@ checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
[[package]]
name = "comrak"
version = "0.28.0"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c93ab3577cca16b4a1d80a88c2e0cd8b6e969e51696f0bbb0d1dcb0157109832"
checksum = "d8c32ff8b21372fab0e9ecc4e42536055702dc5faa418362bffd1544f9d12637"
dependencies = [
"caseless",
"derive_builder",
@ -1278,6 +1291,7 @@ dependencies = [
"sha2",
"shell-escape",
"spki",
"sqlformat",
"strsim",
"tar",
"tempfile",
@ -1452,9 +1466,9 @@ dependencies = [
[[package]]
name = "deno_core"
version = "0.320.0"
version = "0.321.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f285eed7b072749f9c3a9c4cf2c9ebb06462a2c22afec94892a6684c38f32696"
checksum = "cd2a54cda74cdc187d5fc2d23370a45cf09f912caf566dd1cd24a50157d809c7"
dependencies = [
"anyhow",
"bincode",
@ -1466,6 +1480,7 @@ dependencies = [
"deno_ops",
"deno_unsync",
"futures",
"indexmap 2.3.0",
"libc",
"memoffset",
"parking_lot",
@ -1480,6 +1495,7 @@ dependencies = [
"tokio",
"url",
"v8",
"wasm_dep_analyzer",
]
[[package]]
@ -1540,27 +1556,33 @@ dependencies = [
[[package]]
name = "deno_doc"
version = "0.156.0"
version = "0.160.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2585b98d6ad76dae30bf2d7b6d71b8363cae041158b8780d14a2f4fe17590a61"
checksum = "db2baa33e5d1ed235209c2990f5fe9644bac6b9e7bcb789dd92894f907b09ad7"
dependencies = [
"ammonia",
"anyhow",
"cfg-if",
"comrak",
"deno_ast",
"deno_graph",
"deno_path_util",
"futures",
"handlebars",
"html-escape",
"import_map",
"indexmap 2.3.0",
"itoa",
"js-sys",
"lazy_static",
"percent-encoding",
"regex",
"serde",
"serde-wasm-bindgen",
"serde_json",
"syntect",
"termcolor",
"url",
"wasm-bindgen",
]
[[package]]
@ -1642,9 +1664,9 @@ dependencies = [
[[package]]
name = "deno_graph"
version = "0.84.1"
version = "0.85.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd4f4a14aa069087be41c2998077b0453f0191747898f96e6343f700abfc2c18"
checksum = "9d097305aba3f119781fe82b4d5a85a1ad10c586a388ee4d754e5bf82901cc5c"
dependencies = [
"anyhow",
"async-trait",
@ -1667,6 +1689,7 @@ dependencies = [
"thiserror",
"twox-hash",
"url",
"wasm_dep_analyzer",
]
[[package]]
@ -1960,9 +1983,9 @@ dependencies = [
[[package]]
name = "deno_ops"
version = "0.196.0"
version = "0.197.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d35c75ae05062f37ec2ae5fd1d99b2dcdfa0aef70844d3706759b8775056c5f6"
checksum = "37a8825d92301cf445727c43f17fee2a20fcdf4370004339965156ae7c56c97e"
dependencies = [
"proc-macro-rules",
"proc-macro2",
@ -3226,6 +3249,16 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
name = "futf"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843"
dependencies = [
"mac",
"new_debug_unreachable",
]
[[package]]
name = "futures"
version = "0.3.30"
@ -3753,6 +3786,20 @@ dependencies = [
"utf8-width",
]
[[package]]
name = "html5ever"
version = "0.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c13771afe0e6e846f1e67d038d4cb29998a6779f93c809212e4e9c32efd244d4"
dependencies = [
"log",
"mac",
"markup5ever",
"proc-macro2",
"quote",
"syn 2.0.87",
]
[[package]]
name = "http"
version = "0.2.12"
@ -4465,6 +4512,12 @@ dependencies = [
"serde_repr",
]
[[package]]
name = "mac"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
[[package]]
name = "malloc_buf"
version = "0.0.6"
@ -4487,6 +4540,26 @@ dependencies = [
"tiny_pretty",
]
[[package]]
name = "maplit"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
[[package]]
name = "markup5ever"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16ce3abbeba692c8b8441d036ef91aea6df8da2c6b6e21c7e14d3c18e526be45"
dependencies = [
"log",
"phf",
"phf_codegen",
"string_cache",
"string_cache_codegen",
"tendril",
]
[[package]]
name = "markup_fmt"
version = "0.15.0"
@ -4899,28 +4972,6 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
[[package]]
name = "onig"
version = "6.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c4b31c8722ad9171c6d77d3557db078cab2bd50afcc9d09c8b315c59df8ca4f"
dependencies = [
"bitflags 1.3.2",
"libc",
"once_cell",
"onig_sys",
]
[[package]]
name = "onig_sys"
version = "69.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b829e3d7e9cc74c7e315ee8edb185bf4190da5acde74afd7fc59c35b1f086e7"
dependencies = [
"cc",
"pkg-config",
]
[[package]]
name = "opaque-debug"
version = "0.3.1"
@ -5266,7 +5317,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc"
dependencies = [
"phf_macros",
"phf_shared",
"phf_shared 0.11.2",
]
[[package]]
name = "phf_codegen"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a"
dependencies = [
"phf_generator 0.11.2",
"phf_shared 0.11.2",
]
[[package]]
name = "phf_generator"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6"
dependencies = [
"phf_shared 0.10.0",
"rand",
]
[[package]]
@ -5275,7 +5346,7 @@ version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0"
dependencies = [
"phf_shared",
"phf_shared 0.11.2",
"rand",
]
@ -5285,13 +5356,22 @@ version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3444646e286606587e49f3bcf1679b8cef1dc2c5ecc29ddacaffc305180d464b"
dependencies = [
"phf_generator",
"phf_shared",
"phf_generator 0.11.2",
"phf_shared 0.11.2",
"proc-macro2",
"quote",
"syn 2.0.87",
]
[[package]]
name = "phf_shared"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096"
dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.11.2"
@ -5414,6 +5494,12 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "precomputed-hash"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "pretty_assertions"
version = "1.4.0"
@ -6364,6 +6450,17 @@ dependencies = [
"serde",
]
[[package]]
name = "serde-wasm-bindgen"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3b143e2833c57ab9ad3ea280d21fd34e285a42837aeb0ee301f4f41890fa00e"
dependencies = [
"js-sys",
"serde",
"wasm-bindgen",
]
[[package]]
name = "serde_bytes"
version = "0.11.14"
@ -6422,9 +6519,9 @@ dependencies = [
[[package]]
name = "serde_v8"
version = "0.229.0"
version = "0.230.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e1dbbda82d67a393ea96f75d8383bc41fcd0bba43164aeaab599e1c2c2d46d7"
checksum = "b5a783242d2af51d6955cc04bf2b64adb643ab588b61e9573c908a69dabf8c2f"
dependencies = [
"num-bigint",
"serde",
@ -6700,6 +6797,17 @@ dependencies = [
"der",
]
[[package]]
name = "sqlformat"
version = "0.3.1"
source = "git+https://github.com/shssoichiro/sqlformat-rs.git?rev=827d639#827d639bef94d8e5a5a0e29b41185c8d572f24e6"
dependencies = [
"nom 7.1.3",
"once_cell",
"regex",
"unicode_categories",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
@ -6725,6 +6833,32 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "string_cache"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f91138e76242f575eb1d3b38b4f1362f10d3a43f47d182a5b359af488a02293b"
dependencies = [
"new_debug_unreachable",
"once_cell",
"parking_lot",
"phf_shared 0.10.0",
"precomputed-hash",
"serde",
]
[[package]]
name = "string_cache_codegen"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988"
dependencies = [
"phf_generator 0.10.0",
"phf_shared 0.10.0",
"proc-macro2",
"quote",
]
[[package]]
name = "string_enum"
version = "0.4.4"
@ -7283,26 +7417,6 @@ dependencies = [
"syn 2.0.87",
]
[[package]]
name = "syntect"
version = "5.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "874dcfa363995604333cf947ae9f751ca3af4522c60886774c4963943b4746b1"
dependencies = [
"bincode",
"bitflags 1.3.2",
"flate2",
"fnv",
"once_cell",
"onig",
"regex-syntax",
"serde",
"serde_derive",
"serde_json",
"thiserror",
"walkdir",
]
[[package]]
name = "tap"
version = "1.0.1"
@ -7332,6 +7446,17 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "tendril"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0"
dependencies = [
"futf",
"mac",
"utf-8",
]
[[package]]
name = "termcolor"
version = "1.4.1"
@ -8167,6 +8292,15 @@ dependencies = [
"web-sys",
]
[[package]]
name = "wasm_dep_analyzer"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f270206a91783fd90625c8bb0d8fbd459d0b1d1bf209b656f713f01ae7c04b8"
dependencies = [
"thiserror",
]
[[package]]
name = "web-sys"
version = "0.3.69"

View file

@ -46,7 +46,7 @@ repository = "https://github.com/denoland/deno"
[workspace.dependencies]
deno_ast = { version = "=0.43.3", features = ["transpiling"] }
deno_core = { version = "0.320.0" }
deno_core = { version = "0.321.0" }
deno_bench_util = { version = "0.171.0", path = "./bench_util" }
deno_config = { version = "=0.39.1", features = ["workspace", "sync"] }

View file

@ -72,8 +72,8 @@ deno_ast = { workspace = true, features = ["bundler", "cjs", "codegen", "proposa
deno_cache_dir.workspace = true
deno_config.workspace = true
deno_core = { workspace = true, features = ["include_js_files_for_snapshotting"] }
deno_doc = { version = "0.156.0", default-features = false, features = ["rust", "html", "syntect"] }
deno_graph = { version = "=0.84.1" }
deno_doc = { version = "0.160.0", features = ["rust", "comrak"] }
deno_graph = { version = "=0.85.0" }
deno_lint = { version = "=0.68.0", features = ["docs"] }
deno_lockfile.workspace = true
deno_npm.workspace = true
@ -151,6 +151,8 @@ serde_repr.workspace = true
sha2.workspace = true
shell-escape = "=0.1.5"
spki = { version = "0.7", features = ["pem"] }
# NOTE(bartlomieju): for now using github URL, because 0.3.2 with important fixes hasn't been released yet.
sqlformat = { git = "https://github.com/shssoichiro/sqlformat-rs.git", rev = "827d639" }
strsim = "0.11.1"
tar.workspace = true
tempfile.workspace = true

View file

@ -70,7 +70,41 @@ pub fn deno_json_deps(
let values = imports_values(config.json.imports.as_ref())
.into_iter()
.chain(scope_values(config.json.scopes.as_ref()));
values_to_set(values)
let mut set = values_to_set(values);
if let Some(serde_json::Value::Object(compiler_options)) =
&config.json.compiler_options
{
// add jsxImportSource
if let Some(serde_json::Value::String(value)) =
compiler_options.get("jsxImportSource")
{
if let Some(dep_req) = value_to_dep_req(value) {
set.insert(dep_req);
}
}
// add jsxImportSourceTypes
if let Some(serde_json::Value::String(value)) =
compiler_options.get("jsxImportSourceTypes")
{
if let Some(dep_req) = value_to_dep_req(value) {
set.insert(dep_req);
}
}
// add the dependencies in the types array
if let Some(serde_json::Value::Array(types)) = compiler_options.get("types")
{
for value in types {
if let serde_json::Value::String(value) = value {
if let Some(dep_req) = value_to_dep_req(value) {
set.insert(dep_req);
}
}
}
}
}
set
}
fn imports_values(value: Option<&serde_json::Value>) -> Vec<&String> {
@ -98,15 +132,23 @@ fn values_to_set<'a>(
) -> HashSet<JsrDepPackageReq> {
let mut entries = HashSet::new();
for value in values {
if let Ok(req_ref) = JsrPackageReqReference::from_str(value) {
entries.insert(JsrDepPackageReq::jsr(req_ref.into_inner().req));
} else if let Ok(req_ref) = NpmPackageReqReference::from_str(value) {
entries.insert(JsrDepPackageReq::npm(req_ref.into_inner().req));
if let Some(dep_req) = value_to_dep_req(value) {
entries.insert(dep_req);
}
}
entries
}
fn value_to_dep_req(value: &str) -> Option<JsrDepPackageReq> {
if let Ok(req_ref) = JsrPackageReqReference::from_str(value) {
Some(JsrDepPackageReq::jsr(req_ref.into_inner().req))
} else if let Ok(req_ref) = NpmPackageReqReference::from_str(value) {
Some(JsrDepPackageReq::npm(req_ref.into_inner().req))
} else {
None
}
}
pub fn check_warn_tsconfig(ts_config: &TsConfigForEmit) {
if let Some(ignored_options) = &ts_config.maybe_ignored_options {
log::warn!("{}", ignored_options);

View file

@ -210,6 +210,7 @@ pub struct FmtFlags {
pub no_semicolons: Option<bool>,
pub watch: Option<WatchFlags>,
pub unstable_component: bool,
pub unstable_sql: bool,
}
impl FmtFlags {
@ -381,6 +382,7 @@ pub struct TaskFlags {
pub cwd: Option<String>,
pub task: Option<String>,
pub is_run: bool,
pub eval: bool,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
@ -429,6 +431,7 @@ pub struct PublishFlags {
pub allow_slow_types: bool,
pub allow_dirty: bool,
pub no_provenance: bool,
pub set_version: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
@ -1386,13 +1389,13 @@ pub fn flags_from_vec(args: Vec<OsString>) -> clap::error::Result<Flags> {
"repl" => repl_parse(&mut flags, &mut m)?,
"run" => run_parse(&mut flags, &mut m, app, false)?,
"serve" => serve_parse(&mut flags, &mut m, app)?,
"task" => task_parse(&mut flags, &mut m),
"task" => task_parse(&mut flags, &mut m, app)?,
"test" => test_parse(&mut flags, &mut m)?,
"types" => types_parse(&mut flags, &mut m),
"uninstall" => uninstall_parse(&mut flags, &mut m),
"upgrade" => upgrade_parse(&mut flags, &mut m),
"vendor" => vendor_parse(&mut flags, &mut m),
"publish" => publish_parse(&mut flags, &mut m),
"publish" => publish_parse(&mut flags, &mut m)?,
_ => unreachable!(),
}
} else {
@ -1910,10 +1913,10 @@ On the first invocation with deno will download the proper binary and cache it i
Arg::new("include")
.long("include")
.help(
cstr!("Includes an additional module in the compiled executable's module graph.
cstr!("Includes an additional module or file/directory in the compiled executable.
<p(245)>Use this flag if a dynamically imported module or a web worker main module
fails to load in the executable. This flag can be passed multiple times,
to include multiple additional modules.</>",
fails to load in the executable or to embed a file or directory in the executable.
This flag can be passed multiple times, to include multiple additional modules.</>",
))
.action(ArgAction::Append)
.value_hint(ValueHint::FilePath)
@ -2293,7 +2296,7 @@ Ignore formatting a file by adding an ignore comment at the top of the file:
.value_parser([
"ts", "tsx", "js", "jsx", "md", "json", "jsonc", "css", "scss",
"sass", "less", "html", "svelte", "vue", "astro", "yml", "yaml",
"ipynb",
"ipynb", "sql"
])
.help_heading(FMT_HEADING).requires("files"),
)
@ -2412,6 +2415,14 @@ Ignore formatting a file by adding an ignore comment at the top of the file:
.help_heading(FMT_HEADING)
.hide(true),
)
.arg(
Arg::new("unstable-sql")
.long("unstable-sql")
.help("Enable formatting SQL files.")
.value_parser(FalseyValueParser::new())
.action(ArgAction::SetTrue)
.help_heading(FMT_HEADING),
)
})
}
@ -2923,7 +2934,10 @@ fn task_subcommand() -> Command {
<p(245)>deno task build</>
List all available tasks:
<p(245)>deno task</>"
<p(245)>deno task</>
Evaluate a task from string
<p(245)>deno task --eval \"echo $(pwd)\"</>"
),
UnstableArgsConfig::ResolutionAndRuntime,
)
@ -2939,6 +2953,13 @@ List all available tasks:
.help("Specify the directory to run the task in")
.value_hint(ValueHint::DirPath),
)
.arg(
Arg::new("eval")
.long("eval")
.help(
"Evaluate the passed value as if, it was a task in a configuration file",
).action(ArgAction::SetTrue)
)
.arg(node_modules_dir_arg())
})
}
@ -3218,12 +3239,12 @@ fn publish_subcommand() -> Command {
command("publish", "Publish the current working directory's package or workspace to JSR", UnstableArgsConfig::ResolutionOnly)
.defer(|cmd| {
cmd
.arg(
Arg::new("token")
.long("token")
.help("The API token to use when publishing. If unset, interactive authentication is be used")
.help_heading(PUBLISH_HEADING)
)
.arg(
Arg::new("token")
.long("token")
.help("The API token to use when publishing. If unset, interactive authentication is be used")
.help_heading(PUBLISH_HEADING)
)
.arg(config_arg())
.arg(no_config_arg())
.arg(
@ -3231,29 +3252,38 @@ fn publish_subcommand() -> Command {
.long("dry-run")
.help("Prepare the package for publishing performing all checks and validations without uploading")
.action(ArgAction::SetTrue)
.help_heading(PUBLISH_HEADING),
.help_heading(PUBLISH_HEADING),
)
.arg(
Arg::new("allow-slow-types")
.long("allow-slow-types")
.help("Allow publishing with slow types")
.action(ArgAction::SetTrue)
.help_heading(PUBLISH_HEADING),
.help_heading(PUBLISH_HEADING),
)
.arg(
Arg::new("allow-dirty")
.long("allow-dirty")
.help("Allow publishing if the repository has uncommitted changed")
.action(ArgAction::SetTrue)
.help_heading(PUBLISH_HEADING),
).arg(
Arg::new("no-provenance")
.long("no-provenance")
.help(cstr!("Disable provenance attestation.
.help_heading(PUBLISH_HEADING),
)
.arg(
Arg::new("no-provenance")
.long("no-provenance")
.help(cstr!("Disable provenance attestation.
<p(245)>Enabled by default on Github actions, publicly links the package to where it was built and published from.</>"))
.action(ArgAction::SetTrue)
.help_heading(PUBLISH_HEADING)
)
.action(ArgAction::SetTrue)
.help_heading(PUBLISH_HEADING)
)
.arg(
Arg::new("set-version")
.long("set-version")
.help("Set version for a package to be published.
<p(245)>This flag can be used while publishing individual packages and cannot be used in a workspace.</>")
.value_name("VERSION")
.help_heading(PUBLISH_HEADING)
)
.arg(check_arg(/* type checks by default */ true))
.arg(no_check_arg())
})
@ -4636,6 +4666,7 @@ fn fmt_parse(
let prose_wrap = matches.remove_one::<String>("prose-wrap");
let no_semicolons = matches.remove_one::<bool>("no-semicolons");
let unstable_component = matches.get_flag("unstable-component");
let unstable_sql = matches.get_flag("unstable-sql");
flags.subcommand = DenoSubcommand::Fmt(FmtFlags {
check: matches.get_flag("check"),
@ -4648,6 +4679,7 @@ fn fmt_parse(
no_semicolons,
watch: watch_arg_parse(matches)?,
unstable_component,
unstable_sql,
});
Ok(())
}
@ -5049,7 +5081,11 @@ fn serve_parse(
Ok(())
}
fn task_parse(flags: &mut Flags, matches: &mut ArgMatches) {
fn task_parse(
flags: &mut Flags,
matches: &mut ArgMatches,
mut app: Command,
) -> clap::error::Result<()> {
flags.config_flag = matches
.remove_one::<String>("config")
.map(ConfigFlag::Path)
@ -5062,6 +5098,7 @@ fn task_parse(flags: &mut Flags, matches: &mut ArgMatches) {
cwd: matches.remove_one::<String>("cwd"),
task: None,
is_run: false,
eval: matches.get_flag("eval"),
};
if let Some((task, mut matches)) = matches.remove_subcommand() {
@ -5074,9 +5111,15 @@ fn task_parse(flags: &mut Flags, matches: &mut ArgMatches) {
.flatten()
.filter_map(|arg| arg.into_string().ok()),
);
} else if task_flags.eval {
return Err(app.find_subcommand_mut("task").unwrap().error(
clap::error::ErrorKind::MissingRequiredArgument,
"[TASK] must be specified when using --eval",
));
}
flags.subcommand = DenoSubcommand::Task(task_flags);
Ok(())
}
fn parallel_arg_parse(matches: &mut ArgMatches) -> Option<NonZeroUsize> {
@ -5222,7 +5265,10 @@ fn vendor_parse(flags: &mut Flags, _matches: &mut ArgMatches) {
flags.subcommand = DenoSubcommand::Vendor
}
fn publish_parse(flags: &mut Flags, matches: &mut ArgMatches) {
fn publish_parse(
flags: &mut Flags,
matches: &mut ArgMatches,
) -> clap::error::Result<()> {
flags.type_check_mode = TypeCheckMode::Local; // local by default
unstable_args_parse(flags, matches, UnstableArgsConfig::ResolutionOnly);
no_check_arg_parse(flags, matches);
@ -5235,7 +5281,10 @@ fn publish_parse(flags: &mut Flags, matches: &mut ArgMatches) {
allow_slow_types: matches.get_flag("allow-slow-types"),
allow_dirty: matches.get_flag("allow-dirty"),
no_provenance: matches.get_flag("no-provenance"),
set_version: matches.remove_one::<String>("set-version"),
});
Ok(())
}
fn compile_args_parse(
@ -6569,6 +6618,7 @@ mod tests {
prose_wrap: None,
no_semicolons: None,
unstable_component: false,
unstable_sql: false,
watch: Default::default(),
}),
..Flags::default()
@ -6592,6 +6642,7 @@ mod tests {
prose_wrap: None,
no_semicolons: None,
unstable_component: false,
unstable_sql: false,
watch: Default::default(),
}),
..Flags::default()
@ -6615,6 +6666,7 @@ mod tests {
prose_wrap: None,
no_semicolons: None,
unstable_component: false,
unstable_sql: false,
watch: Default::default(),
}),
..Flags::default()
@ -6638,6 +6690,7 @@ mod tests {
prose_wrap: None,
no_semicolons: None,
unstable_component: false,
unstable_sql: false,
watch: Some(Default::default()),
}),
..Flags::default()
@ -6652,7 +6705,8 @@ mod tests {
"--unstable-css",
"--unstable-html",
"--unstable-component",
"--unstable-yaml"
"--unstable-yaml",
"--unstable-sql"
]);
assert_eq!(
r.unwrap(),
@ -6670,6 +6724,7 @@ mod tests {
prose_wrap: None,
no_semicolons: None,
unstable_component: true,
unstable_sql: true,
watch: Some(WatchFlags {
hmr: false,
no_clear_screen: true,
@ -6704,6 +6759,7 @@ mod tests {
prose_wrap: None,
no_semicolons: None,
unstable_component: false,
unstable_sql: false,
watch: Some(Default::default()),
}),
..Flags::default()
@ -6727,6 +6783,7 @@ mod tests {
prose_wrap: None,
no_semicolons: None,
unstable_component: false,
unstable_sql: false,
watch: Default::default(),
}),
config_flag: ConfigFlag::Path("deno.jsonc".to_string()),
@ -6758,6 +6815,7 @@ mod tests {
prose_wrap: None,
no_semicolons: None,
unstable_component: false,
unstable_sql: false,
watch: Some(Default::default()),
}),
config_flag: ConfigFlag::Path("deno.jsonc".to_string()),
@ -6794,6 +6852,7 @@ mod tests {
prose_wrap: Some("never".to_string()),
no_semicolons: Some(true),
unstable_component: false,
unstable_sql: false,
watch: Default::default(),
}),
..Flags::default()
@ -6824,6 +6883,7 @@ mod tests {
prose_wrap: None,
no_semicolons: Some(false),
unstable_component: false,
unstable_sql: false,
watch: Default::default(),
}),
..Flags::default()
@ -6849,6 +6909,7 @@ mod tests {
prose_wrap: None,
no_semicolons: None,
unstable_component: false,
unstable_sql: false,
watch: Default::default(),
}),
ext: Some("html".to_string()),
@ -10239,6 +10300,7 @@ mod tests {
cwd: None,
task: Some("build".to_string()),
is_run: false,
eval: false,
}),
argv: svec!["hello", "world"],
..Flags::default()
@ -10253,6 +10315,7 @@ mod tests {
cwd: None,
task: Some("build".to_string()),
is_run: false,
eval: false,
}),
..Flags::default()
}
@ -10266,10 +10329,28 @@ mod tests {
cwd: Some("foo".to_string()),
task: Some("build".to_string()),
is_run: false,
eval: false,
}),
..Flags::default()
}
);
let r = flags_from_vec(svec!["deno", "task", "--eval", "echo 1"]);
assert_eq!(
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Task(TaskFlags {
cwd: None,
task: Some("echo 1".to_string()),
is_run: false,
eval: true,
}),
..Flags::default()
}
);
let r = flags_from_vec(svec!["deno", "task", "--eval"]);
assert!(r.is_err());
}
#[test]
@ -10291,6 +10372,7 @@ mod tests {
cwd: None,
task: Some("build".to_string()),
is_run: false,
eval: false,
}),
argv: svec!["--", "hello", "world"],
config_flag: ConfigFlag::Path("deno.json".to_owned()),
@ -10308,6 +10390,7 @@ mod tests {
cwd: Some("foo".to_string()),
task: Some("build".to_string()),
is_run: false,
eval: false,
}),
argv: svec!["--", "hello", "world"],
..Flags::default()
@ -10326,6 +10409,7 @@ mod tests {
cwd: None,
task: Some("build".to_string()),
is_run: false,
eval: false,
}),
argv: svec!["--"],
..Flags::default()
@ -10343,6 +10427,7 @@ mod tests {
cwd: None,
task: Some("build".to_string()),
is_run: false,
eval: false,
}),
argv: svec!["-1", "--test"],
..Flags::default()
@ -10360,6 +10445,7 @@ mod tests {
cwd: None,
task: Some("build".to_string()),
is_run: false,
eval: false,
}),
argv: svec!["--test"],
..Flags::default()
@ -10378,6 +10464,7 @@ mod tests {
cwd: None,
task: Some("build".to_string()),
is_run: false,
eval: false,
}),
log_level: Some(log::Level::Error),
..Flags::default()
@ -10395,6 +10482,7 @@ mod tests {
cwd: None,
task: None,
is_run: false,
eval: false,
}),
..Flags::default()
}
@ -10411,6 +10499,7 @@ mod tests {
cwd: None,
task: None,
is_run: false,
eval: false,
}),
config_flag: ConfigFlag::Path("deno.jsonc".to_string()),
..Flags::default()
@ -10428,6 +10517,7 @@ mod tests {
cwd: None,
task: None,
is_run: false,
eval: false,
}),
config_flag: ConfigFlag::Path("deno.jsonc".to_string()),
..Flags::default()
@ -10750,6 +10840,7 @@ mod tests {
"--allow-slow-types",
"--allow-dirty",
"--token=asdf",
"--set-version=1.0.1",
]);
assert_eq!(
r.unwrap(),
@ -10760,6 +10851,7 @@ mod tests {
allow_slow_types: true,
allow_dirty: true,
no_provenance: true,
set_version: Some("1.0.1".to_string()),
}),
type_check_mode: TypeCheckMode::Local,
..Flags::default()

View file

@ -126,11 +126,7 @@ impl CliLockfile {
maybe_deno_json: Option<&ConfigFile>,
) -> HashSet<JsrDepPackageReq> {
maybe_deno_json
.map(|c| {
crate::args::deno_json::deno_json_deps(c)
.into_iter()
.collect()
})
.map(crate::args::deno_json::deno_json_deps)
.unwrap_or_default()
}

View file

@ -289,6 +289,7 @@ impl BenchOptions {
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct UnstableFmtOptions {
pub component: bool,
pub sql: bool,
}
#[derive(Clone, Debug)]
@ -322,6 +323,7 @@ impl FmtOptions {
options: resolve_fmt_options(fmt_flags, fmt_config.options),
unstable: UnstableFmtOptions {
component: unstable.component || fmt_flags.unstable_component,
sql: unstable.sql || fmt_flags.unstable_sql,
},
files: fmt_config.files,
}
@ -1319,6 +1321,7 @@ impl CliOptions {
let workspace = self.workspace();
UnstableFmtOptions {
component: workspace.has_unstable("fmt-component"),
sql: workspace.has_unstable("fmt-sql"),
}
}
@ -1545,6 +1548,10 @@ impl CliOptions {
}) => Url::parse(&flags.module_url)
.ok()
.map(|url| vec![Cow::Owned(url)]),
DenoSubcommand::Doc(DocFlags {
source_files: DocSourceFileFlag::Paths(paths),
..
}) => Some(files_to_urls(paths)),
_ => None,
})
.unwrap_or_default();
@ -1667,6 +1674,7 @@ impl CliOptions {
"byonm",
"bare-node-builtins",
"fmt-component",
"fmt-sql",
])
.collect();

View file

@ -38,6 +38,7 @@ fn get_module_graph_error_class(err: &ModuleGraphError) -> &'static str {
ModuleGraphError::ModuleError(err) => match err {
ModuleError::InvalidTypeAssertion { .. } => "SyntaxError",
ModuleError::ParseErr(_, diagnostic) => get_diagnostic_class(diagnostic),
ModuleError::WasmParseErr(..) => "SyntaxError",
ModuleError::UnsupportedMediaType { .. }
| ModuleError::UnsupportedImportAttributeType { .. } => "TypeError",
ModuleError::Missing(_, _) | ModuleError::MissingDynamic(_, _) => {

View file

@ -884,6 +884,7 @@ impl CliFactory {
let cli_options = self.cli_options()?;
Ok(DenoCompileBinaryWriter::new(
self.cjs_tracker()?,
self.cli_options()?,
self.deno_dir()?,
self.emitter()?,
self.file_fetcher()?,

View file

@ -883,8 +883,13 @@ impl FileSystemDocuments {
let doc = if specifier.scheme() == "file" {
let path = url_to_file_path(specifier).ok()?;
let bytes = fs::read(path).ok()?;
let content =
deno_graph::source::decode_owned_source(specifier, bytes, None).ok()?;
let content = bytes_to_content(
specifier,
MediaType::from_specifier(specifier),
bytes,
None,
)
.ok()?;
Document::new(
specifier.clone(),
content.into(),
@ -923,19 +928,24 @@ impl FileSystemDocuments {
specifier,
Some(&cached_file.metadata.headers),
);
let content = deno_graph::source::decode_owned_source(
let media_type = resolve_media_type(
specifier,
Some(&cached_file.metadata.headers),
None,
);
let content = bytes_to_content(
specifier,
media_type,
cached_file.content,
maybe_charset,
)
.ok()?;
let maybe_headers = Some(cached_file.metadata.headers);
Document::new(
specifier.clone(),
content.into(),
None,
None,
maybe_headers,
Some(cached_file.metadata.headers),
is_cjs_resolver,
resolver.clone(),
config.clone(),
@ -1706,6 +1716,24 @@ fn analyze_module(
}
}
fn bytes_to_content(
specifier: &ModuleSpecifier,
media_type: MediaType,
bytes: Vec<u8>,
maybe_charset: Option<&str>,
) -> Result<String, AnyError> {
if media_type == MediaType::Wasm {
// we use the dts representation for Wasm modules
Ok(deno_graph::source::wasm::wasm_module_to_dts(&bytes)?)
} else {
Ok(deno_graph::source::decode_owned_source(
specifier,
bytes,
maybe_charset,
)?)
}
}
#[cfg(test)]
mod tests {
use super::*;

View file

@ -1405,6 +1405,9 @@ impl Inner {
component: config_data
.map(|d| d.unstable.contains("fmt-component"))
.unwrap_or(false),
sql: config_data
.map(|d| d.unstable.contains("fmt-sql"))
.unwrap_or(false),
};
let document = document.clone();
move || {

View file

@ -5609,7 +5609,7 @@ mod tests {
let (_tx, rx) = mpsc::unbounded_channel();
let state =
State::new(state_snapshot, Default::default(), Default::default(), rx);
let mut op_state = OpState::new(None);
let mut op_state = OpState::new(None, None);
op_state.put(state);
op_state
}

View file

@ -238,6 +238,7 @@ async fn run_subcommand(flags: Arc<Flags>) -> Result<i32, AnyError> {
cwd: None,
task: Some(run_flags.script.clone()),
is_run: true,
eval: false,
};
new_flags.subcommand = DenoSubcommand::Task(task_flags.clone());
let result = tools::task::execute_script(Arc::new(new_flags), task_flags.clone()).await;

View file

@ -66,6 +66,7 @@ use deno_graph::JsonModule;
use deno_graph::Module;
use deno_graph::ModuleGraph;
use deno_graph::Resolution;
use deno_graph::WasmModule;
use deno_runtime::code_cache;
use deno_runtime::deno_fs::FileSystem;
use deno_runtime::deno_node::create_host_defined_options;
@ -368,7 +369,9 @@ impl<TGraphContainer: ModuleGraphContainer>
requested_module_type: RequestedModuleType,
) -> Result<ModuleSource, AnyError> {
let code_source = self.load_code_source(specifier, maybe_referrer).await?;
let code = if self.shared.is_inspecting {
let code = if self.shared.is_inspecting
|| code_source.media_type == MediaType::Wasm
{
// we need the code with the source map in order for
// it to work with --inspect or --inspect-brk
code_source.code
@ -378,6 +381,7 @@ impl<TGraphContainer: ModuleGraphContainer>
};
let module_type = match code_source.media_type {
MediaType::Json => ModuleType::Json,
MediaType::Wasm => ModuleType::Wasm,
_ => ModuleType::JavaScript,
};
@ -474,21 +478,6 @@ impl<TGraphContainer: ModuleGraphContainer>
raw_specifier: &str,
referrer: &ModuleSpecifier,
) -> Result<ModuleSpecifier, AnyError> {
if self.shared.in_npm_pkg_checker.in_npm_package(referrer) {
return Ok(
self
.shared
.node_resolver
.resolve(
raw_specifier,
referrer,
self.shared.cjs_tracker.get_referrer_kind(referrer),
NodeResolutionMode::Execution,
)?
.into_url(),
);
}
let graph = self.graph_container.graph();
let resolution = match graph.get(referrer) {
Some(Module::Js(module)) => module
@ -560,6 +549,7 @@ impl<TGraphContainer: ModuleGraphContainer>
Some(Module::Node(module)) => module.specifier.clone(),
Some(Module::Js(module)) => module.specifier.clone(),
Some(Module::Json(module)) => module.specifier.clone(),
Some(Module::Wasm(module)) => module.specifier.clone(),
Some(Module::External(module)) => {
node::resolve_specifier_into_node_modules(
&module.specifier,
@ -731,6 +721,13 @@ impl<TGraphContainer: ModuleGraphContainer>
media_type: *media_type,
})))
}
Some(deno_graph::Module::Wasm(WasmModule {
source, specifier, ..
})) => Ok(Some(CodeOrDeferredEmit::Code(ModuleCodeStringSource {
code: ModuleSourceCode::Bytes(source.clone().into()),
found_url: specifier.clone(),
media_type: MediaType::Wasm,
}))),
Some(
deno_graph::Module::External(_)
| deno_graph::Module::Node(_)

View file

@ -557,6 +557,7 @@
"ffi",
"fs",
"fmt-component",
"fmt-sql",
"http",
"kv",
"net",

View file

@ -201,7 +201,8 @@ fn write_binary_bytes(
compile_flags: &CompileFlags,
) -> Result<(), AnyError> {
let data_section_bytes =
serialize_binary_data_section(metadata, npm_snapshot, remote_modules, vfs)?;
serialize_binary_data_section(metadata, npm_snapshot, remote_modules, vfs)
.context("Serializing binary data section.")?;
let target = compile_flags.resolve_target();
if target.contains("linux") {
@ -364,6 +365,7 @@ pub fn extract_standalone(
pub struct DenoCompileBinaryWriter<'a> {
cjs_tracker: &'a CjsTracker,
cli_options: &'a CliOptions,
deno_dir: &'a DenoDir,
emitter: &'a Emitter,
file_fetcher: &'a FileFetcher,
@ -377,6 +379,7 @@ impl<'a> DenoCompileBinaryWriter<'a> {
#[allow(clippy::too_many_arguments)]
pub fn new(
cjs_tracker: &'a CjsTracker,
cli_options: &'a CliOptions,
deno_dir: &'a DenoDir,
emitter: &'a Emitter,
file_fetcher: &'a FileFetcher,
@ -387,6 +390,7 @@ impl<'a> DenoCompileBinaryWriter<'a> {
) -> Self {
Self {
cjs_tracker,
cli_options,
deno_dir,
emitter,
file_fetcher,
@ -403,8 +407,8 @@ impl<'a> DenoCompileBinaryWriter<'a> {
graph: &ModuleGraph,
root_dir_url: StandaloneRelativeFileBaseUrl<'_>,
entrypoint: &ModuleSpecifier,
include_files: &[ModuleSpecifier],
compile_flags: &CompileFlags,
cli_options: &CliOptions,
) -> Result<(), AnyError> {
// Select base binary based on target
let mut original_binary = self.get_base_binary(compile_flags).await?;
@ -417,7 +421,8 @@ impl<'a> DenoCompileBinaryWriter<'a> {
target,
)
}
set_windows_binary_to_gui(&mut original_binary)?;
set_windows_binary_to_gui(&mut original_binary)
.context("Setting windows binary to GUI.")?;
}
if compile_flags.icon.is_some() {
let target = compile_flags.resolve_target();
@ -435,7 +440,7 @@ impl<'a> DenoCompileBinaryWriter<'a> {
graph,
root_dir_url,
entrypoint,
cli_options,
include_files,
compile_flags,
)
.await
@ -478,10 +483,14 @@ impl<'a> DenoCompileBinaryWriter<'a> {
if !binary_path.exists() {
self
.download_base_binary(&download_directory, &binary_path_suffix)
.await?;
.await
.context("Setting up base binary.")?;
}
let archive_data = std::fs::read(binary_path)?;
let read_file = |path: &Path| -> Result<Vec<u8>, AnyError> {
std::fs::read(path).with_context(|| format!("Reading {}", path.display()))
};
let archive_data = read_file(&binary_path)?;
let temp_dir = tempfile::TempDir::new()?;
let base_binary_path = archive::unpack_into_dir(archive::UnpackArgs {
exe_name: "denort",
@ -490,7 +499,7 @@ impl<'a> DenoCompileBinaryWriter<'a> {
is_windows: target.contains("windows"),
dest_path: temp_dir.path(),
})?;
let base_binary = std::fs::read(base_binary_path)?;
let base_binary = read_file(&base_binary_path)?;
drop(temp_dir); // delete the temp dir
Ok(base_binary)
}
@ -518,15 +527,19 @@ impl<'a> DenoCompileBinaryWriter<'a> {
let bytes = match maybe_bytes {
Some(bytes) => bytes,
None => {
log::info!("Download could not be found, aborting");
deno_runtime::exit(1);
bail!("Download could not be found, aborting");
}
};
std::fs::create_dir_all(output_directory)?;
let create_dir_all = |dir: &Path| {
std::fs::create_dir_all(dir)
.with_context(|| format!("Creating {}", dir.display()))
};
create_dir_all(output_directory)?;
let output_path = output_directory.join(binary_path_suffix);
std::fs::create_dir_all(output_path.parent().unwrap())?;
tokio::fs::write(output_path, bytes).await?;
create_dir_all(output_path.parent().unwrap())?;
std::fs::write(&output_path, bytes)
.with_context(|| format!("Writing {}", output_path.display()))?;
Ok(())
}
@ -540,73 +553,87 @@ impl<'a> DenoCompileBinaryWriter<'a> {
graph: &ModuleGraph,
root_dir_url: StandaloneRelativeFileBaseUrl<'_>,
entrypoint: &ModuleSpecifier,
cli_options: &CliOptions,
include_files: &[ModuleSpecifier],
compile_flags: &CompileFlags,
) -> Result<(), AnyError> {
let ca_data = match cli_options.ca_data() {
let ca_data = match self.cli_options.ca_data() {
Some(CaData::File(ca_file)) => Some(
std::fs::read(ca_file)
.with_context(|| format!("Reading: {ca_file}"))?,
std::fs::read(ca_file).with_context(|| format!("Reading {ca_file}"))?,
),
Some(CaData::Bytes(bytes)) => Some(bytes.clone()),
None => None,
};
let root_path = root_dir_url.inner().to_file_path().unwrap();
let (maybe_npm_vfs, node_modules, npm_snapshot) = match self
.npm_resolver
.as_inner()
{
InnerCliNpmResolverRef::Managed(managed) => {
let snapshot =
managed.serialized_valid_snapshot_for_system(&self.npm_system_info);
if !snapshot.as_serialized().packages.is_empty() {
let npm_vfs_builder = self.build_npm_vfs(&root_path, cli_options)?;
let (maybe_npm_vfs, node_modules, npm_snapshot) =
match self.npm_resolver.as_inner() {
InnerCliNpmResolverRef::Managed(managed) => {
let snapshot =
managed.serialized_valid_snapshot_for_system(&self.npm_system_info);
if !snapshot.as_serialized().packages.is_empty() {
let npm_vfs_builder = self
.build_npm_vfs(&root_path)
.context("Building npm vfs.")?;
(
Some(npm_vfs_builder),
Some(NodeModules::Managed {
node_modules_dir: self
.npm_resolver
.root_node_modules_path()
.map(|path| {
root_dir_url
.specifier_key(
&ModuleSpecifier::from_directory_path(path).unwrap(),
)
.into_owned()
}),
}),
Some(snapshot),
)
} else {
(None, None, None)
}
}
InnerCliNpmResolverRef::Byonm(resolver) => {
let npm_vfs_builder = self.build_npm_vfs(&root_path)?;
(
Some(npm_vfs_builder),
Some(NodeModules::Managed {
node_modules_dir: self.npm_resolver.root_node_modules_path().map(
|path| {
Some(NodeModules::Byonm {
root_node_modules_dir: resolver.root_node_modules_path().map(
|node_modules_dir| {
root_dir_url
.specifier_key(
&ModuleSpecifier::from_directory_path(path).unwrap(),
&ModuleSpecifier::from_directory_path(node_modules_dir)
.unwrap(),
)
.into_owned()
},
),
}),
Some(snapshot),
None,
)
} else {
(None, None, None)
}
}
InnerCliNpmResolverRef::Byonm(resolver) => {
let npm_vfs_builder = self.build_npm_vfs(&root_path, cli_options)?;
(
Some(npm_vfs_builder),
Some(NodeModules::Byonm {
root_node_modules_dir: resolver.root_node_modules_path().map(
|node_modules_dir| {
root_dir_url
.specifier_key(
&ModuleSpecifier::from_directory_path(node_modules_dir)
.unwrap(),
)
.into_owned()
},
),
}),
None,
)
}
};
};
let mut vfs = if let Some(npm_vfs) = maybe_npm_vfs {
npm_vfs
} else {
VfsBuilder::new(root_path.clone())?
};
for include_file in include_files {
let path = deno_path_util::url_to_file_path(include_file)?;
if path.is_dir() {
// TODO(#26941): we should analyze if any of these are
// modules in order to include their dependencies
vfs
.add_dir_recursive(&path)
.with_context(|| format!("Including {}", path.display()))?;
} else {
vfs
.add_file_at_path(&path)
.with_context(|| format!("Including {}", path.display()))?;
}
}
let mut remote_modules_store = RemoteModulesStoreBuilder::default();
let mut code_cache_key_hasher = if cli_options.code_cache_enabled() {
let mut code_cache_key_hasher = if self.cli_options.code_cache_enabled() {
Some(FastInsecureHasher::new_deno_versioned())
} else {
None
@ -648,6 +675,9 @@ impl<'a> DenoCompileBinaryWriter<'a> {
deno_graph::Module::Json(m) => {
(Some(m.source.as_bytes().to_vec()), m.media_type)
}
deno_graph::Module::Wasm(m) => {
(Some(m.source.to_vec()), MediaType::Wasm)
}
deno_graph::Module::Npm(_)
| deno_graph::Module::Node(_)
| deno_graph::Module::External(_) => (None, MediaType::Unknown),
@ -671,7 +701,7 @@ impl<'a> DenoCompileBinaryWriter<'a> {
}
remote_modules_store.add_redirects(&graph.redirects);
let env_vars_from_env_file = match cli_options.env_file_name() {
let env_vars_from_env_file = match self.cli_options.env_file_name() {
Some(env_filenames) => {
let mut aggregated_env_vars = IndexMap::new();
for env_filename in env_filenames.iter().rev() {
@ -687,16 +717,17 @@ impl<'a> DenoCompileBinaryWriter<'a> {
let metadata = Metadata {
argv: compile_flags.args.clone(),
seed: cli_options.seed(),
seed: self.cli_options.seed(),
code_cache_key: code_cache_key_hasher.map(|h| h.finish()),
location: cli_options.location_flag().clone(),
permissions: cli_options.permission_flags().clone(),
v8_flags: cli_options.v8_flags().clone(),
unsafely_ignore_certificate_errors: cli_options
location: self.cli_options.location_flag().clone(),
permissions: self.cli_options.permission_flags().clone(),
v8_flags: self.cli_options.v8_flags().clone(),
unsafely_ignore_certificate_errors: self
.cli_options
.unsafely_ignore_certificate_errors()
.clone(),
log_level: cli_options.log_level(),
ca_stores: cli_options.ca_stores().clone(),
log_level: self.cli_options.log_level(),
ca_stores: self.cli_options.ca_stores().clone(),
ca_data,
env_vars_from_env_file,
entrypoint_key: root_dir_url.specifier_key(entrypoint).into_owned(),
@ -739,11 +770,11 @@ impl<'a> DenoCompileBinaryWriter<'a> {
node_modules,
unstable_config: UnstableConfig {
legacy_flag_enabled: false,
bare_node_builtins: cli_options.unstable_bare_node_builtins(),
sloppy_imports: cli_options.unstable_sloppy_imports(),
features: cli_options.unstable_features(),
bare_node_builtins: self.cli_options.unstable_bare_node_builtins(),
sloppy_imports: self.cli_options.unstable_sloppy_imports(),
features: self.cli_options.unstable_features(),
},
otel_config: cli_options.otel_config(),
otel_config: self.cli_options.otel_config(),
};
write_binary_bytes(
@ -755,13 +786,10 @@ impl<'a> DenoCompileBinaryWriter<'a> {
vfs,
compile_flags,
)
.context("Writing binary bytes")
}
fn build_npm_vfs(
&self,
root_path: &Path,
cli_options: &CliOptions,
) -> Result<VfsBuilder, AnyError> {
fn build_npm_vfs(&self, root_path: &Path) -> Result<VfsBuilder, AnyError> {
fn maybe_warn_different_system(system_info: &NpmSystemInfo) {
if system_info != &NpmSystemInfo::default() {
log::warn!("{} The node_modules directory may be incompatible with the target system.", crate::colors::yellow("Warning"));
@ -838,13 +866,18 @@ impl<'a> DenoCompileBinaryWriter<'a> {
InnerCliNpmResolverRef::Byonm(_) => {
maybe_warn_different_system(&self.npm_system_info);
let mut builder = VfsBuilder::new(root_path.to_path_buf())?;
for pkg_json in cli_options.workspace().package_jsons() {
for pkg_json in self.cli_options.workspace().package_jsons() {
builder.add_file_at_path(&pkg_json.path)?;
}
// traverse and add all the node_modules directories in the workspace
let mut pending_dirs = VecDeque::new();
pending_dirs.push_back(
cli_options.workspace().root_dir().to_file_path().unwrap(),
self
.cli_options
.workspace()
.root_dir()
.to_file_path()
.unwrap(),
);
while let Some(pending_dir) = pending_dirs.pop_front() {
let mut entries = fs::read_dir(&pending_dir)

View file

@ -51,7 +51,8 @@ pub struct VfsBuilder {
impl VfsBuilder {
pub fn new(root_path: PathBuf) -> Result<Self, AnyError> {
let root_path = canonicalize_path(&root_path)?;
let root_path = canonicalize_path(&root_path)
.with_context(|| format!("Canonicalizing {}", root_path.display()))?;
log::debug!("Building vfs with root '{}'", root_path.display());
Ok(Self {
root_dir: VirtualDirectory {

View file

@ -483,20 +483,32 @@ fn resolve_execution_path_from_npx_shim(
static SCRIPT_PATH_RE: Lazy<Regex> =
lazy_regex::lazy_regex!(r#""\$basedir\/([^"]+)" "\$@""#);
if text.starts_with("#!/usr/bin/env node") {
// launch this file itself because it's a JS file
Some(file_path)
} else {
// Search for...
// > "$basedir/../next/dist/bin/next" "$@"
// ...which is what it will look like on Windows
SCRIPT_PATH_RE
.captures(text)
.and_then(|c| c.get(1))
.map(|relative_path| {
file_path.parent().unwrap().join(relative_path.as_str())
})
let maybe_first_line = {
let index = text.find("\n")?;
Some(&text[0..index])
};
if let Some(first_line) = maybe_first_line {
// NOTE(bartlomieju): this is not perfect, but handle two most common scenarios
// where Node is run without any args. If there are args then we use `NodeCommand`
// struct.
if first_line == "#!/usr/bin/env node"
|| first_line == "#!/usr/bin/env -S node"
{
// launch this file itself because it's a JS file
return Some(file_path);
}
}
// Search for...
// > "$basedir/../next/dist/bin/next" "$@"
// ...which is what it will look like on Windows
SCRIPT_PATH_RE
.captures(text)
.and_then(|c| c.get(1))
.map(|relative_path| {
file_path.parent().unwrap().join(relative_path.as_str())
})
}
fn resolve_managed_npm_commands(
@ -564,6 +576,16 @@ mod test {
let unix_shim = r#"#!/usr/bin/env node
"use strict";
console.log('Hi!');
"#;
let path = PathBuf::from("/node_modules/.bin/example");
assert_eq!(
resolve_execution_path_from_npx_shim(path.clone(), unix_shim).unwrap(),
path
);
// example shim on unix
let unix_shim = r#"#!/usr/bin/env -S node
"use strict";
console.log('Hi!');
"#;
let path = PathBuf::from("/node_modules/.bin/example");
assert_eq!(

View file

@ -380,6 +380,11 @@ fn get_check_hash(
hasher.write_str(module.specifier.as_str());
hasher.write_str(&module.source);
}
Module::Wasm(module) => {
has_file_to_type_check = true;
hasher.write_str(module.specifier.as_str());
hasher.write_str(&module.source_dts);
}
Module::External(module) => {
hasher.write_str(module.specifier.as_str());
}
@ -437,6 +442,7 @@ fn get_tsc_roots(
| MediaType::SourceMap
| MediaType::Unknown => None,
},
Module::Wasm(module) => Some((module.specifier.clone(), MediaType::Dmts)),
Module::External(_)
| Module::Node(_)
| Module::Npm(_)

View file

@ -7,6 +7,7 @@ use crate::factory::CliFactory;
use crate::http_util::HttpClientProvider;
use crate::standalone::binary::StandaloneRelativeFileBaseUrl;
use crate::standalone::is_standalone_binary;
use deno_ast::MediaType;
use deno_ast::ModuleSpecifier;
use deno_core::anyhow::bail;
use deno_core::anyhow::Context;
@ -31,15 +32,12 @@ pub async fn compile(
let module_graph_creator = factory.module_graph_creator().await?;
let binary_writer = factory.create_compile_binary_writer().await?;
let http_client = factory.http_client_provider();
let module_specifier = cli_options.resolve_main_module()?;
let module_roots = {
let mut vec = Vec::with_capacity(compile_flags.include.len() + 1);
vec.push(module_specifier.clone());
for side_module in &compile_flags.include {
vec.push(resolve_url_or_path(side_module, cli_options.initial_cwd())?);
}
vec
};
let entrypoint = cli_options.resolve_main_module()?;
let (module_roots, include_files) = get_module_roots_and_include_files(
entrypoint,
&compile_flags,
cli_options.initial_cwd(),
)?;
// this is not supported, so show a warning about it, but don't error in order
// to allow someone to still run `deno compile` when this is in a deno.json
@ -82,18 +80,22 @@ pub async fn compile(
check_warn_tsconfig(&ts_config_for_emit);
let root_dir_url = resolve_root_dir_from_specifiers(
cli_options.workspace().root_dir(),
graph.specifiers().map(|(s, _)| s).chain(
cli_options
.node_modules_dir_path()
.and_then(|p| ModuleSpecifier::from_directory_path(p).ok())
.iter(),
),
graph
.specifiers()
.map(|(s, _)| s)
.chain(
cli_options
.node_modules_dir_path()
.and_then(|p| ModuleSpecifier::from_directory_path(p).ok())
.iter(),
)
.chain(include_files.iter()),
);
log::debug!("Binary root dir: {}", root_dir_url);
log::info!(
"{} {} to {}",
colors::green("Compile"),
module_specifier.to_string(),
entrypoint,
output_path.display(),
);
validate_output_path(&output_path)?;
@ -118,9 +120,9 @@ pub async fn compile(
file,
&graph,
StandaloneRelativeFileBaseUrl::from(&root_dir_url),
module_specifier,
entrypoint,
&include_files,
&compile_flags,
cli_options,
)
.await
.with_context(|| {
@ -212,6 +214,48 @@ fn validate_output_path(output_path: &Path) -> Result<(), AnyError> {
Ok(())
}
fn get_module_roots_and_include_files(
entrypoint: &ModuleSpecifier,
compile_flags: &CompileFlags,
initial_cwd: &Path,
) -> Result<(Vec<ModuleSpecifier>, Vec<ModuleSpecifier>), AnyError> {
fn is_module_graph_module(url: &ModuleSpecifier) -> bool {
if url.scheme() != "file" {
return true;
}
let media_type = MediaType::from_specifier(url);
match media_type {
MediaType::JavaScript
| MediaType::Jsx
| MediaType::Mjs
| MediaType::Cjs
| MediaType::TypeScript
| MediaType::Mts
| MediaType::Cts
| MediaType::Dts
| MediaType::Dmts
| MediaType::Dcts
| MediaType::Tsx
| MediaType::Json
| MediaType::Wasm => true,
MediaType::Css | MediaType::SourceMap | MediaType::Unknown => false,
}
}
let mut module_roots = Vec::with_capacity(compile_flags.include.len() + 1);
let mut include_files = Vec::with_capacity(compile_flags.include.len());
module_roots.push(entrypoint.clone());
for side_module in &compile_flags.include {
let url = resolve_url_or_path(side_module, initial_cwd)?;
if is_module_graph_module(&url) {
module_roots.push(url);
} else {
include_files.push(url);
}
}
Ok((module_roots, include_files))
}
async fn resolve_compile_executable_output_path(
http_client_provider: &HttpClientProvider,
compile_flags: &CompileFlags,

View file

@ -21,6 +21,8 @@ use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_doc as doc;
use deno_doc::html::UrlResolveKind;
use deno_doc::html::UsageComposer;
use deno_doc::html::UsageComposerEntry;
use deno_graph::source::NullFileSystem;
use deno_graph::EsParser;
use deno_graph::GraphKind;
@ -35,6 +37,9 @@ use std::sync::Arc;
const JSON_SCHEMA_VERSION: u8 = 1;
const PRISM_CSS: &str = include_str!("./doc/prism.css");
const PRISM_JS: &str = include_str!("./doc/prism.js");
async fn generate_doc_nodes_for_builtin_types(
doc_flags: DocFlags,
parser: &dyn EsParser,
@ -312,10 +317,6 @@ impl deno_doc::html::HrefResolver for DocResolver {
None
}
fn resolve_usage(&self, current_resolve: UrlResolveKind) -> Option<String> {
current_resolve.get_file().map(|file| file.path.to_string())
}
fn resolve_source(&self, location: &deno_doc::Location) -> Option<String> {
Some(location.filename.to_string())
}
@ -350,105 +351,30 @@ impl deno_doc::html::HrefResolver for DocResolver {
}
}
struct DenoDocResolver(bool);
struct DocComposer;
impl deno_doc::html::HrefResolver for DenoDocResolver {
fn resolve_path(
impl UsageComposer for DocComposer {
fn is_single_mode(&self) -> bool {
true
}
fn compose(
&self,
current: UrlResolveKind,
target: UrlResolveKind,
) -> String {
let path = deno_doc::html::href_path_resolve(current, target);
if self.0 {
if let Some(path) = path
.strip_suffix("index.html")
.or_else(|| path.strip_suffix(".html"))
{
return path.to_owned();
}
}
path
}
fn resolve_global_symbol(&self, _symbol: &[String]) -> Option<String> {
None
}
fn resolve_import_href(
&self,
_symbol: &[String],
_src: &str,
) -> Option<String> {
None
}
fn resolve_usage(&self, _current_resolve: UrlResolveKind) -> Option<String> {
None
}
fn resolve_source(&self, _location: &deno_doc::Location) -> Option<String> {
None
}
fn resolve_external_jsdoc_module(
&self,
_module: &str,
_symbol: Option<&str>,
) -> Option<(String, String)> {
None
}
}
struct NodeDocResolver(bool);
impl deno_doc::html::HrefResolver for NodeDocResolver {
fn resolve_path(
&self,
current: UrlResolveKind,
target: UrlResolveKind,
) -> String {
let path = deno_doc::html::href_path_resolve(current, target);
if self.0 {
if let Some(path) = path
.strip_suffix("index.html")
.or_else(|| path.strip_suffix(".html"))
{
return path.to_owned();
}
}
path
}
fn resolve_global_symbol(&self, _symbol: &[String]) -> Option<String> {
None
}
fn resolve_import_href(
&self,
_symbol: &[String],
_src: &str,
) -> Option<String> {
None
}
fn resolve_usage(&self, current_resolve: UrlResolveKind) -> Option<String> {
current_resolve: UrlResolveKind,
usage_to_md: deno_doc::html::UsageToMd,
) -> IndexMap<UsageComposerEntry, String> {
current_resolve
.get_file()
.map(|file| format!("node:{}", file.path))
}
fn resolve_source(&self, _location: &deno_doc::Location) -> Option<String> {
None
}
fn resolve_external_jsdoc_module(
&self,
_module: &str,
_symbol: Option<&str>,
) -> Option<(String, String)> {
None
.map(|current_file| {
IndexMap::from([(
UsageComposerEntry {
name: "".to_string(),
icon: None,
},
usage_to_md(current_file.path.as_str(), None),
)])
})
.unwrap_or_default()
}
}
@ -461,30 +387,10 @@ fn generate_docs_directory(
let cwd = std::env::current_dir().context("Failed to get CWD")?;
let output_dir_resolved = cwd.join(&html_options.output);
let internal_env = std::env::var("DENO_INTERNAL_HTML_DOCS").ok();
let href_resolver: Rc<dyn deno_doc::html::HrefResolver> = if internal_env
.as_ref()
.is_some_and(|internal_html_docs| internal_html_docs == "node")
{
Rc::new(NodeDocResolver(html_options.strip_trailing_html))
} else if internal_env
.as_ref()
.is_some_and(|internal_html_docs| internal_html_docs == "deno")
|| deno_ns.is_empty()
{
Rc::new(DenoDocResolver(html_options.strip_trailing_html))
} else {
Rc::new(DocResolver {
deno_ns,
strip_trailing_html: html_options.strip_trailing_html,
})
};
let category_docs =
if let Some(category_docs_path) = &html_options.category_docs_path {
let content = std::fs::read(category_docs_path)?;
Some(deno_core::serde_json::from_slice(&content)?)
Some(serde_json::from_slice(&content)?)
} else {
None
};
@ -493,7 +399,7 @@ fn generate_docs_directory(
&html_options.symbol_redirect_map_path
{
let content = std::fs::read(symbol_redirect_map_path)?;
Some(deno_core::serde_json::from_slice(&content)?)
Some(serde_json::from_slice(&content)?)
} else {
None
};
@ -502,7 +408,7 @@ fn generate_docs_directory(
&html_options.default_symbol_map_path
{
let content = std::fs::read(default_symbol_map_path)?;
Some(deno_core::serde_json::from_slice(&content)?)
Some(serde_json::from_slice(&content)?)
} else {
None
};
@ -511,17 +417,59 @@ fn generate_docs_directory(
package_name: html_options.name.clone(),
main_entrypoint: None,
rewrite_map,
href_resolver,
usage_composer: None,
href_resolver: Rc::new(DocResolver {
deno_ns,
strip_trailing_html: html_options.strip_trailing_html,
}),
usage_composer: Rc::new(DocComposer),
category_docs,
disable_search: internal_env.is_some(),
disable_search: false,
symbol_redirect_map,
default_symbol_map,
markdown_renderer: deno_doc::html::comrak::create_renderer(
None,
Some(Box::new(|ammonia| {
ammonia.add_allowed_classes(
"code",
&[
"language-ts",
"language-tsx",
"language-typescript",
"language-js",
"language-jsx",
"language-javascript",
"language-bash",
"language-shell",
"language-md",
"language-markdown",
"language-rs",
"language-rust",
"language-html",
"language-xml",
"language-css",
"language-json",
"language-regex",
"language-svg",
],
);
})),
None,
),
markdown_stripper: Rc::new(deno_doc::html::comrak::strip),
head_inject: Some(Rc::new(|root| {
format!(
r#"<link href="{root}{}" rel="stylesheet" /><link href="{root}prism.css" rel="stylesheet" /><script src="{root}prism.js"></script>"#,
deno_doc::html::comrak::COMRAK_STYLESHEET_FILENAME
)
})),
};
let files = deno_doc::html::generate(options, doc_nodes_by_url)
let mut files = deno_doc::html::generate(options, doc_nodes_by_url)
.context("Failed to generate HTML documentation")?;
files.insert("prism.js".to_string(), PRISM_JS.to_string());
files.insert("prism.css".to_string(), PRISM_CSS.to_string());
let path = &output_dir_resolved;
let _ = std::fs::remove_dir_all(path);
std::fs::create_dir(path)

3
cli/tools/doc/prism.css Normal file
View file

@ -0,0 +1,3 @@
/* PrismJS 1.29.0
https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript+bash+json+markdown+regex+rust+typescript */
code[class*=language-],pre[class*=language-]{color:#000;background:0 0;text-shadow:0 1px #fff;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-] ::selection,code[class*=language-]::selection,pre[class*=language-] ::selection,pre[class*=language-]::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.token.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#9a6e3a;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.class-name,.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}

15
cli/tools/doc/prism.js Normal file

File diff suppressed because one or more lines are too long

View file

@ -272,6 +272,7 @@ fn format_markdown(
| "njk"
| "yml"
| "yaml"
| "sql"
) {
// It's important to tell dprint proper file extension, otherwise
// it might parse the file twice.
@ -301,6 +302,13 @@ fn format_markdown(
}
}
"yml" | "yaml" => format_yaml(text, fmt_options),
"sql" => {
if unstable_options.sql {
format_sql(text, fmt_options)
} else {
Ok(None)
}
}
_ => {
let mut codeblock_config =
get_resolved_typescript_config(fmt_options);
@ -503,7 +511,48 @@ pub fn format_html(
})
}
/// Formats a single TS, TSX, JS, JSX, JSONC, JSON, MD, or IPYNB file.
pub fn format_sql(
file_text: &str,
fmt_options: &FmtOptionsConfig,
) -> Result<Option<String>, AnyError> {
let ignore_file = file_text
.lines()
.take_while(|line| line.starts_with("--"))
.any(|line| {
line
.strip_prefix("--")
.unwrap()
.trim()
.starts_with("deno-fmt-ignore-file")
});
if ignore_file {
return Ok(None);
}
let mut formatted_str = sqlformat::format(
file_text,
&sqlformat::QueryParams::None,
&sqlformat::FormatOptions {
ignore_case_convert: None,
indent: if fmt_options.use_tabs.unwrap_or_default() {
sqlformat::Indent::Tabs
} else {
sqlformat::Indent::Spaces(fmt_options.indent_width.unwrap_or(2))
},
// leave one blank line between queries.
lines_between_queries: 2,
uppercase: Some(true),
},
);
// Add single new line to the end of file.
formatted_str.push('\n');
Ok(Some(formatted_str))
}
/// Formats a single TS, TSX, JS, JSX, JSONC, JSON, MD, IPYNB or SQL file.
pub fn format_file(
file_path: &Path,
file_text: &str,
@ -538,6 +587,13 @@ pub fn format_file(
format_file(file_path, &file_text, fmt_options, unstable_options, None)
},
),
"sql" => {
if unstable_options.sql {
format_sql(file_text, fmt_options)
} else {
Ok(None)
}
}
_ => {
let config = get_resolved_typescript_config(fmt_options);
dprint_plugin_typescript::format_text(
@ -1209,6 +1265,7 @@ fn is_supported_ext_fmt(path: &Path) -> bool {
| "yml"
| "yaml"
| "ipynb"
| "sql"
)
})
}
@ -1269,6 +1326,11 @@ mod test {
assert!(is_supported_ext_fmt(Path::new("foo.yaml")));
assert!(is_supported_ext_fmt(Path::new("foo.YaML")));
assert!(is_supported_ext_fmt(Path::new("foo.ipynb")));
assert!(is_supported_ext_fmt(Path::new("foo.sql")));
assert!(is_supported_ext_fmt(Path::new("foo.Sql")));
assert!(is_supported_ext_fmt(Path::new("foo.sQl")));
assert!(is_supported_ext_fmt(Path::new("foo.sqL")));
assert!(is_supported_ext_fmt(Path::new("foo.SQL")));
}
#[test]

View file

@ -126,6 +126,7 @@ fn print_cache_info(
let registry_cache = dir.registries_folder_path();
let mut origin_dir = dir.origin_data_folder_path();
let deno_dir = dir.root_path_for_display().to_string();
let web_cache_dir = crate::worker::get_cache_storage_dir();
if let Some(location) = &location {
origin_dir =
@ -143,6 +144,7 @@ fn print_cache_info(
"typescriptCache": typescript_cache,
"registryCache": registry_cache,
"originStorage": origin_dir,
"webCacheStorage": web_cache_dir,
});
if location.is_some() {
@ -177,6 +179,11 @@ fn print_cache_info(
colors::bold("Origin storage:"),
origin_dir.display()
);
println!(
"{} {}",
colors::bold("Web cache storage:"),
web_cache_dir.display()
);
if location.is_some() {
println!(
"{} {}",
@ -446,6 +453,7 @@ impl<'a> GraphDisplayContext<'a> {
let maybe_cache_info = match root {
Module::Js(module) => module.maybe_cache_info.as_ref(),
Module::Json(module) => module.maybe_cache_info.as_ref(),
Module::Wasm(module) => module.maybe_cache_info.as_ref(),
Module::Node(_) | Module::Npm(_) | Module::External(_) => None,
};
if let Some(cache_info) = maybe_cache_info {
@ -468,6 +476,7 @@ impl<'a> GraphDisplayContext<'a> {
let size = match m {
Module::Js(module) => module.size(),
Module::Json(module) => module.size(),
Module::Wasm(module) => module.size(),
Module::Node(_) | Module::Npm(_) | Module::External(_) => 0,
};
size as f64
@ -567,6 +576,7 @@ impl<'a> GraphDisplayContext<'a> {
Specifier(_) => match module {
Module::Js(module) => Some(module.size() as u64),
Module::Json(module) => Some(module.size() as u64),
Module::Wasm(module) => Some(module.size() as u64),
Module::Node(_) | Module::Npm(_) | Module::External(_) => None,
},
};
@ -580,8 +590,8 @@ impl<'a> GraphDisplayContext<'a> {
Package(package) => {
tree_node.children.extend(self.build_npm_deps(package));
}
Specifier(_) => {
if let Some(module) = module.js() {
Specifier(_) => match module {
Module::Js(module) => {
if let Some(types_dep) = &module.maybe_types_dependency {
if let Some(child) =
self.build_resolved_info(&types_dep.dependency, true)
@ -593,7 +603,16 @@ impl<'a> GraphDisplayContext<'a> {
tree_node.children.extend(self.build_dep_info(dep));
}
}
}
Module::Wasm(module) => {
for dep in module.dependencies.values() {
tree_node.children.extend(self.build_dep_info(dep));
}
}
Module::Json(_)
| Module::Npm(_)
| Module::Node(_)
| Module::External(_) => {}
},
}
}
tree_node
@ -658,7 +677,7 @@ impl<'a> GraphDisplayContext<'a> {
};
self.build_error_msg(specifier, message.as_ref())
}
ModuleError::ParseErr(_, _) => {
ModuleError::ParseErr(_, _) | ModuleError::WasmParseErr(_, _) => {
self.build_error_msg(specifier, "(parsing error)")
}
ModuleError::UnsupportedImportAttributeType { .. } => {

View file

@ -12,6 +12,7 @@ use std::sync::Arc;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use deno_ast::ModuleSpecifier;
use deno_config::deno_json::ConfigFile;
use deno_config::workspace::JsrPackageConfig;
use deno_config::workspace::PackageJsonDepResolution;
use deno_config::workspace::Workspace;
@ -90,13 +91,14 @@ pub async fn publish(
let cli_options = cli_factory.cli_options()?;
let directory_path = cli_options.initial_cwd();
let publish_configs = cli_options.start_dir.jsr_packages_for_publish();
let mut publish_configs = cli_options.start_dir.jsr_packages_for_publish();
if publish_configs.is_empty() {
match cli_options.start_dir.maybe_deno_json() {
Some(deno_json) => {
debug_assert!(!deno_json.is_package());
error_missing_exports_field(deno_json)?;
bail!(
"Missing 'name', 'version' and 'exports' field in '{}'.",
"Missing 'name' or 'exports' field in '{}'.",
deno_json.specifier
);
}
@ -108,6 +110,18 @@ pub async fn publish(
}
}
}
if let Some(version) = &publish_flags.set_version {
if publish_configs.len() > 1 {
bail!("Cannot use --set-version when publishing a workspace. Change your cwd to an individual package instead.");
}
if let Some(publish_config) = publish_configs.get_mut(0) {
let mut config_file = publish_config.config_file.as_ref().clone();
config_file.json.version = Some(version.clone());
publish_config.config_file = Arc::new(config_file);
}
}
let specifier_unfurler = Arc::new(SpecifierUnfurler::new(
if cli_options.unstable_sloppy_imports() {
Some(CliSloppyImportsResolver::new(SloppyImportsCachedFs::new(
@ -404,43 +418,15 @@ impl PublishPreparer {
graph: Arc<deno_graph::ModuleGraph>,
diagnostics_collector: &PublishDiagnosticsCollector,
) -> Result<Rc<PreparedPublishPackage>, AnyError> {
static SUGGESTED_ENTRYPOINTS: [&str; 4] =
["mod.ts", "mod.js", "index.ts", "index.js"];
let deno_json = &package.config_file;
let config_path = deno_json.specifier.to_file_path().unwrap();
let root_dir = config_path.parent().unwrap().to_path_buf();
let Some(version) = deno_json.json.version.clone() else {
bail!("{} is missing 'version' field", deno_json.specifier);
};
if deno_json.json.exports.is_none() {
let mut suggested_entrypoint = None;
for entrypoint in SUGGESTED_ENTRYPOINTS {
if root_dir.join(entrypoint).exists() {
suggested_entrypoint = Some(entrypoint);
break;
}
}
let exports_content = format!(
r#"{{
"name": "{}",
"version": "{}",
"exports": "{}"
}}"#,
package.name,
version,
suggested_entrypoint.unwrap_or("<path_to_entrypoint>")
);
bail!(
"You did not specify an entrypoint to \"{}\" package in {}. Add `exports` mapping in the configuration file, eg:\n{}",
package.name,
deno_json.specifier,
exports_content
);
}
let version = deno_json.json.version.clone().ok_or_else(|| {
deno_core::anyhow::anyhow!(
"{} is missing 'version' field",
deno_json.specifier
)
})?;
let Some(name_no_at) = package.name.strip_prefix('@') else {
bail!("Invalid package name, use '@<scope_name>/<package_name> format");
};
@ -1107,9 +1093,9 @@ fn collect_excluded_module_diagnostics(
let graph_specifiers = graph
.modules()
.filter_map(|m| match m {
deno_graph::Module::Js(_) | deno_graph::Module::Json(_) => {
Some(m.specifier())
}
deno_graph::Module::Js(_)
| deno_graph::Module::Json(_)
| deno_graph::Module::Wasm(_) => Some(m.specifier()),
deno_graph::Module::Npm(_)
| deno_graph::Module::Node(_)
| deno_graph::Module::External(_) => None,
@ -1272,6 +1258,36 @@ fn has_license_file<'a>(
})
}
fn error_missing_exports_field(deno_json: &ConfigFile) -> Result<(), AnyError> {
static SUGGESTED_ENTRYPOINTS: [&str; 4] =
["mod.ts", "mod.js", "index.ts", "index.js"];
let mut suggested_entrypoint = None;
for entrypoint in SUGGESTED_ENTRYPOINTS {
if deno_json.dir_path().join(entrypoint).exists() {
suggested_entrypoint = Some(entrypoint);
break;
}
}
let exports_content = format!(
r#"{{
"name": "{}",
"version": "{}",
"exports": "{}"
}}"#,
deno_json.json.name.as_deref().unwrap_or("@scope/name"),
deno_json.json.name.as_deref().unwrap_or("0.0.0"),
suggested_entrypoint.unwrap_or("<path_to_entrypoint>")
);
bail!(
"You did not specify an entrypoint in {}. Add `exports` mapping in the configuration file, eg:\n{}",
deno_json.specifier,
exports_content
);
}
#[allow(clippy::print_stderr)]
fn ring_bell() {
// ASCII code for the bell character.

View file

@ -42,7 +42,7 @@ pub async fn execute_script(
let factory = CliFactory::from_flags(flags);
let cli_options = factory.cli_options()?;
let start_dir = &cli_options.start_dir;
if !start_dir.has_deno_or_pkg_json() {
if !start_dir.has_deno_or_pkg_json() && !task_flags.eval {
bail!("deno task couldn't find deno.json(c). See https://docs.deno.com/go/config")
}
let force_use_pkg_json =
@ -90,6 +90,19 @@ pub async fn execute_script(
concurrency: no_of_concurrent_tasks.into(),
};
if task_flags.eval {
return task_runner
.run_deno_task(
&Url::from_directory_path(cli_options.initial_cwd()).unwrap(),
&"".to_string(),
&TaskDefinition {
command: task_flags.task.as_ref().unwrap().to_string(),
dependencies: vec![],
description: None,
},
)
.await;
}
task_runner.run_task(task_name).await
}

View file

@ -450,6 +450,12 @@ delete Object.prototype.__proto__;
// We specify the resolution mode to be CommonJS for some npm files and this
// diagnostic gets generated even though we're using custom module resolution.
1452,
// Module '...' cannot be imported using this construct. The specifier only resolves to an
// ES module, which cannot be imported with 'require'.
1471,
// TS1479: The current file is a CommonJS module whose imports will produce 'require' calls;
// however, the referenced file is an ECMAScript module and cannot be imported with 'require'.
1479,
// TS2306: File '.../index.d.ts' is not a module.
// We get this for `x-typescript-types` declaration files which don't export
// anything. We prefer to treat these as modules with no exports.

View file

@ -4535,7 +4535,7 @@ declare namespace Deno {
/** The object that is returned from a {@linkcode Deno.upgradeWebSocket}
* request.
*
* @category Web Sockets */
* @category WebSockets */
export interface WebSocketUpgrade {
/** The response object that represents the HTTP response to the client,
* which should be used to the {@linkcode RequestEvent} `.respondWith()` for
@ -4549,7 +4549,7 @@ declare namespace Deno {
/** Options which can be set when performing a
* {@linkcode Deno.upgradeWebSocket} upgrade of a {@linkcode Request}
*
* @category Web Sockets */
* @category WebSockets */
export interface UpgradeWebSocketOptions {
/** Sets the `.protocol` property on the client side web socket to the
* value provided here, which should be one of the strings specified in the
@ -4597,7 +4597,7 @@ declare namespace Deno {
* This operation does not yet consume the request or open the websocket. This
* only happens once the returned response has been passed to `respondWith()`.
*
* @category Web Sockets
* @category WebSockets
*/
export function upgradeWebSocket(
request: Request,

View file

@ -650,6 +650,10 @@ fn op_load_inner(
media_type = MediaType::Json;
Some(Cow::Borrowed(&*module.source))
}
Module::Wasm(module) => {
media_type = MediaType::Dts;
Some(Cow::Borrowed(&*module.source_dts))
}
Module::Npm(_) | Module::Node(_) => None,
Module::External(module) => {
// means it's Deno code importing an npm module
@ -889,6 +893,9 @@ fn resolve_graph_specifier_types(
Some(Module::Json(module)) => {
Ok(Some((module.specifier.clone(), module.media_type)))
}
Some(Module::Wasm(module)) => {
Ok(Some((module.specifier.clone(), MediaType::Dmts)))
}
Some(Module::Npm(module)) => {
if let Some(npm) = &state.maybe_npm.as_ref() {
let package_folder = npm
@ -1196,7 +1203,7 @@ mod tests {
.context("Unable to get CWD")
.unwrap(),
);
let mut op_state = OpState::new(None);
let mut op_state = OpState::new(None, None);
op_state.put(state);
op_state
}

View file

@ -393,6 +393,13 @@ impl CliMainWorker {
}
}
// TODO(bartlomieju): this should be moved to some other place, added to avoid string
// duplication between worker setups and `deno info` output.
pub fn get_cache_storage_dir() -> PathBuf {
// Note: we currently use temp_dir() to avoid managing storage size.
std::env::temp_dir().join("deno_cache")
}
#[derive(Clone)]
pub struct CliMainWorkerFactory {
shared: Arc<SharedWorkerState>,
@ -529,10 +536,7 @@ impl CliMainWorkerFactory {
});
let cache_storage_dir = maybe_storage_key.map(|key| {
// TODO(@satyarohith): storage quota management
// Note: we currently use temp_dir() to avoid managing storage size.
std::env::temp_dir()
.join("deno_cache")
.join(checksum::gen(&[key.as_bytes()]))
get_cache_storage_dir().join(checksum::gen(&[key.as_bytes()]))
});
// TODO(bartlomieju): this is cruft, update FeatureChecker to spit out
@ -729,10 +733,7 @@ fn create_web_worker_callback(
.resolve_storage_key(&args.main_module);
let cache_storage_dir = maybe_storage_key.map(|key| {
// TODO(@satyarohith): storage quota management
// Note: we currently use temp_dir() to avoid managing storage size.
std::env::temp_dir()
.join("deno_cache")
.join(checksum::gen(&[key.as_bytes()]))
get_cache_storage_dir().join(checksum::gen(&[key.as_bytes()]))
});
// TODO(bartlomieju): this is cruft, update FeatureChecker to spit out

View file

@ -1086,12 +1086,10 @@ function loadESMFromCJS(module, filename, code) {
module.exports = namespace;
}
Module._extensions[".mjs"] = Module._extensions[".mts"] = function (
module,
filename,
) {
loadESMFromCJS(module, filename);
};
Module._extensions[".mjs"] =
Module._extensions[".mts"] =
Module._extensions[".wasm"] =
loadESMFromCJS;
function stripBOM(content) {
if (StringPrototypeCharCodeAt(content, 0) === 0xfeff) {

View file

@ -202,7 +202,7 @@ impl<TEnv: NodeResolverEnv> NodeResolver<TEnv> {
mode: NodeResolutionMode,
) -> Result<Url, NodeResolveError> {
if should_be_treated_as_relative_or_absolute_path(specifier) {
Ok(referrer.join(specifier).map_err(|err| {
Ok(node_join_url(referrer, specifier).map_err(|err| {
NodeResolveRelativeJoinError {
path: specifier.to_string(),
base: referrer.clone(),
@ -1763,6 +1763,17 @@ fn get_module_name_from_builtin_node_module_specifier(
Some(specifier)
}
/// Node is more lenient joining paths than the url crate is,
/// so this function handles that.
fn node_join_url(url: &Url, path: &str) -> Result<Url, url::ParseError> {
if let Some(suffix) = path.strip_prefix(".//") {
// specifier had two leading slashes
url.join(&format!("./{}", suffix))
} else {
url.join(path)
}
}
#[cfg(test)]
mod tests {
use serde_json::json;

View file

@ -78,7 +78,7 @@ pub fn validate_import_attributes_callback(
for (key, value) in attributes {
let msg = if key != "type" {
Some(format!("\"{key}\" attribute is not supported."))
} else if value != "json" {
} else if value != "json" && value != "$$deno-core-internal-wasm-module" {
Some(format!("\"{value}\" is not a valid module type."))
} else {
None

View file

@ -61,6 +61,12 @@ fn fmt_test() {
let badly_formatted_yaml = t.path().join("badly_formatted.yaml");
badly_formatted_original_yaml.copy(&badly_formatted_yaml);
let fixed_sql = testdata_fmt_dir.join("badly_formatted_fixed.sql");
let badly_formatted_original_sql =
testdata_fmt_dir.join("badly_formatted.sql");
let badly_formatted_sql = t.path().join("badly_formatted.sql");
badly_formatted_original_sql.copy(&badly_formatted_sql);
// First, check formatting by ignoring the badly formatted file.
let output = context
.new_command()
@ -71,11 +77,12 @@ fn fmt_test() {
"--unstable-html".to_string(),
"--unstable-component".to_string(),
"--unstable-yaml".to_string(),
"--unstable-sql".to_string(),
format!(
"--ignore={badly_formatted_js},{badly_formatted_md},{badly_formatted_json},{badly_formatted_css},{badly_formatted_html},{badly_formatted_component},{badly_formatted_yaml},{badly_formatted_ipynb}",
"--ignore={badly_formatted_js},{badly_formatted_md},{badly_formatted_json},{badly_formatted_css},{badly_formatted_html},{badly_formatted_component},{badly_formatted_yaml},{badly_formatted_ipynb},{badly_formatted_sql}",
),
format!(
"--check {badly_formatted_js} {badly_formatted_md} {badly_formatted_json} {badly_formatted_css} {badly_formatted_html} {badly_formatted_component} {badly_formatted_yaml} {badly_formatted_ipynb}",
"--check {badly_formatted_js} {badly_formatted_md} {badly_formatted_json} {badly_formatted_css} {badly_formatted_html} {badly_formatted_component} {badly_formatted_yaml} {badly_formatted_ipynb} {badly_formatted_sql}",
),
])
.run();
@ -95,6 +102,7 @@ fn fmt_test() {
"--unstable-html".to_string(),
"--unstable-component".to_string(),
"--unstable-yaml".to_string(),
"--unstable-sql".to_string(),
badly_formatted_js.to_string(),
badly_formatted_md.to_string(),
badly_formatted_json.to_string(),
@ -103,6 +111,7 @@ fn fmt_test() {
badly_formatted_component.to_string(),
badly_formatted_yaml.to_string(),
badly_formatted_ipynb.to_string(),
badly_formatted_sql.to_string(),
])
.run();
@ -119,6 +128,7 @@ fn fmt_test() {
"--unstable-html".to_string(),
"--unstable-component".to_string(),
"--unstable-yaml".to_string(),
"--unstable-sql".to_string(),
badly_formatted_js.to_string(),
badly_formatted_md.to_string(),
badly_formatted_json.to_string(),
@ -127,6 +137,7 @@ fn fmt_test() {
badly_formatted_component.to_string(),
badly_formatted_yaml.to_string(),
badly_formatted_ipynb.to_string(),
badly_formatted_sql.to_string(),
])
.run();
@ -141,6 +152,7 @@ fn fmt_test() {
let expected_component = fixed_component.read_to_string();
let expected_yaml = fixed_yaml.read_to_string();
let expected_ipynb = fixed_ipynb.read_to_string();
let expected_sql = fixed_sql.read_to_string();
let actual_js = badly_formatted_js.read_to_string();
let actual_md = badly_formatted_md.read_to_string();
let actual_json = badly_formatted_json.read_to_string();
@ -149,6 +161,7 @@ fn fmt_test() {
let actual_component = badly_formatted_component.read_to_string();
let actual_yaml = badly_formatted_yaml.read_to_string();
let actual_ipynb = badly_formatted_ipynb.read_to_string();
let actual_sql = badly_formatted_sql.read_to_string();
assert_eq!(expected_js, actual_js);
assert_eq!(expected_md, actual_md);
assert_eq!(expected_json, actual_json);
@ -157,6 +170,7 @@ fn fmt_test() {
assert_eq!(expected_component, actual_component);
assert_eq!(expected_yaml, actual_yaml);
assert_eq!(expected_ipynb, actual_ipynb);
assert_eq!(expected_sql, actual_sql);
}
#[test]

View file

@ -5427,7 +5427,8 @@ fn lsp_code_actions_deno_cache() {
let res =
client
.write_request( "textDocument/codeAction",
.write_request(
"textDocument/codeAction",
json!({
"textDocument": {
"uri": "file:///a/file.ts"
@ -5453,8 +5454,7 @@ fn lsp_code_actions_deno_cache() {
"only": ["quickfix"]
}
}),
)
;
);
assert_eq!(
res,
json!([{
@ -16516,3 +16516,47 @@ fn lsp_jsdoc_named_example() {
}),
);
}
#[test]
fn lsp_wasm_module() {
let context = TestContextBuilder::new()
.use_temp_cwd()
.use_http_server()
.build();
let mut client = context.new_lsp_command().build();
client.initialize_default();
client.did_open(json!({
"textDocument": {
"uri": "file:///a/file.ts",
"languageId": "typescript",
"version": 1,
"text": "import { add } from \"http://localhost:4545/wasm/math.wasm\";\nadd(1, '');\n"
}
}));
client.write_request(
"workspace/executeCommand",
json!({
"command": "deno.cache",
"arguments": [[], "file:///a/file.ts"],
}),
);
let diagnostics = client.read_diagnostics();
assert_eq!(
json!(diagnostics.all()),
json!([
{
"range": {
"start": { "line": 1, "character": 7 },
"end": { "line": 1, "character": 9 }
},
"severity": 1,
"code": 2345,
"source": "deno-ts",
"message": "Argument of type 'string' is not assignable to parameter of type 'number'."
}
])
);
client.shutdown();
}

View file

@ -0,0 +1,2 @@
// node.js will resolve this as ./other.js
export * from ".//other.js";

View file

@ -0,0 +1,3 @@
export function add(a, b) {
return a + b;
}

View file

@ -0,0 +1,6 @@
{
"name": "@denotest/specifier-two-slashes",
"version": "1.0.0",
"type": "module",
"main": "index.js"
}

View file

@ -0,0 +1,5 @@
{
"args": "check --allow-import main.ts",
"output": "check.out",
"exitCode": 1
}

View file

@ -0,0 +1,6 @@
Download http://localhost:4545/wasm/math.wasm
Check file:///[WILDLINE]/main.ts
error: TS2345 [ERROR]: Argument of type 'string' is not assignable to parameter of type 'number'.
console.log(add(1, ""));
~~
at file:///[WILDLINE]/main.ts:3:20

View file

@ -0,0 +1,3 @@
import { add } from "http://localhost:4545/wasm/math.wasm";
console.log(add(1, ""));

View file

@ -0,0 +1,41 @@
{
"tempDir": true,
"tests": {
"success": {
"steps": [{
"if": "unix",
"args": "compile --allow-read=data-file.txt --include data-file.txt --output main main.js",
"output": "[WILDCARD]"
}, {
"if": "unix",
"commandName": "./main",
"args": [],
"output": "output.out",
"exitCode": 0
}, {
"if": "windows",
"args": "compile --allow-read=data-file.txt --include data-file.txt --output main.exe main.js",
"output": "[WILDCARD]"
}, {
"if": "windows",
"commandName": "./main.exe",
"args": [],
"output": "output.out",
"exitCode": 0
}]
},
"non_existent": {
"steps": [{
"if": "unix",
"args": "compile --include does_not_exist.txt --output main main.js",
"output": "non_existent.out",
"exitCode": 1
}, {
"if": "windows",
"args": "compile --include does_not_exist.txt --output main.exe main.js",
"output": "non_existent.out",
"exitCode": 1
}]
}
}
}

View file

@ -0,0 +1 @@
Hi

View file

@ -0,0 +1 @@
console.log(Deno.readTextFileSync("./data-file.txt").trim());

View file

@ -0,0 +1,6 @@
Compile file:///[WILDLINE]/main.js to [WILDLINE]
error: Writing deno compile executable to temporary file 'main[WILDLINE]'
Caused by:
0: Including [WILDLINE]does_not_exist.txt
1: [WILDLINE]

View file

@ -0,0 +1 @@
Hi

View file

@ -0,0 +1,24 @@
{
"tempDir": true,
"steps": [{
"if": "unix",
"args": "compile --allow-read=data --include data --output main main.js",
"output": "[WILDCARD]"
}, {
"if": "unix",
"commandName": "./main",
"args": [],
"output": "output.out",
"exitCode": 0
}, {
"if": "windows",
"args": "compile --allow-read=data --include data --output main.exe main.js",
"output": "[WILDCARD]"
}, {
"if": "windows",
"commandName": "./main.exe",
"args": [],
"output": "output.out",
"exitCode": 0
}]
}

View file

@ -0,0 +1 @@
a

View file

@ -0,0 +1 @@
b

View file

@ -0,0 +1,8 @@
const dataDir = import.meta.dirname + "/data";
const files = Array.from(
Deno.readDirSync(dataDir).map((entry) => dataDir + "/" + entry.name),
);
files.sort();
for (const file of files) {
console.log(Deno.readTextFileSync(file).trim());
}

View file

@ -0,0 +1,2 @@
a
b

View file

@ -1 +1 @@
Written 12 files to "./docs/"
Written 15 files to "./docs/"

View file

@ -0,0 +1,4 @@
{
"args": "doc http://localhost:4545/wasm/math.wasm",
"output": "doc.out"
}

View file

@ -0,0 +1,21 @@
Download http://localhost:4545/wasm/math.wasm
Defined in http://localhost:4545/wasm/math.wasm:2:1
function add(arg0: number, arg1: number): number
Defined in http://localhost:4545/wasm/math.wasm:3:1
function subtract(arg0: number, arg1: number): number
Defined in http://localhost:4545/wasm/math.wasm:4:22
const __data_end: number
Defined in http://localhost:4545/wasm/math.wasm:5:22
const __heap_base: number
Defined in http://localhost:4545/wasm/math.wasm:1:22
const memory: WebAssembly.Memory

View file

@ -0,0 +1,25 @@
{
"tempDir": true,
"tests": {
"nothing": {
"args": "fmt",
"output": "Checked 7 files\n"
},
"flag": {
"args": "fmt --unstable-sql",
"output": "[UNORDERED_START]\n[WILDLINE]badly_formatted.sql\n[WILDLINE]well_formatted.sql\n[WILDLINE]wrong_file_ignore.sql\n[UNORDERED_END]\nChecked 7 files\n"
},
"config_file": {
"steps": [{
"args": [
"eval",
"Deno.writeTextFile('deno.json', '{\\n \"unstable\": [\"fmt-sql\"]\\n}\\n')"
],
"output": "[WILDCARD]"
}, {
"args": "fmt",
"output": "[UNORDERED_START]\n[WILDLINE]badly_formatted.sql\n[WILDLINE]well_formatted.sql\n[WILDLINE]wrong_file_ignore.sql\n[UNORDERED_END]\nChecked 8 files\n"
}]
}
}
}

View file

@ -0,0 +1 @@
select *;

View file

@ -0,0 +1,3 @@
-- deno-fmt-ignore-file
foo%!

View file

@ -0,0 +1,3 @@
--deno-fmt-ignore-file
foo%!

View file

@ -0,0 +1,6 @@
-- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
-- incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
-- quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
-- deno-fmt-ignore-file
foo%!

View file

@ -0,0 +1,3 @@
-- deno-fmt-ignore-file Foo bar biz
foo%!

View file

@ -0,0 +1,4 @@
SELECT
*
FROM
foo;

View file

@ -0,0 +1,6 @@
-- File ignore directive only works if it's in the first cluster
-- of comment, ie. there are no empty lines after the first n-leading lines.
-- deno-fmt-ignore-file
foo

View file

@ -4,3 +4,4 @@ npm modules cache: [WILDCARD]npm
Emitted modules cache: [WILDCARD]gen
Language server registries cache: [WILDCARD]registries
Origin storage: [WILDCARD]location_data
Web cache storage: [WILDCARD]deno_cache

View file

@ -4,4 +4,5 @@ npm modules cache: [WILDCARD]npm
Emitted modules cache: [WILDCARD]gen
Language server registries cache: [WILDCARD]registries
Origin storage: [WILDCARD]location_data[WILDCARD]
Web cache storage: [WILDCARD]deno_cache
Local Storage: [WILDCARD]location_data[WILDCARD]local_storage

View file

@ -5,5 +5,6 @@
"npmCache": "[WILDCARD]npm",
"typescriptCache": "[WILDCARD]gen",
"registryCache": "[WILDCARD]registries",
"originStorage": "[WILDCARD]location_data"
"originStorage": "[WILDCARD]location_data",
"webCacheStorage": [WILDCARD]deno_cache"
}

View file

@ -0,0 +1,4 @@
{
"args": "info --allow-import main.js",
"output": "main.out"
}

View file

@ -0,0 +1,7 @@
import {
add,
subtract,
} from "http://localhost:4545/wasm/math_with_import.wasm";
console.log(add(1, 2));
console.log(subtract(100, 50));

View file

@ -0,0 +1,10 @@
Download http://localhost:4545/wasm/math_with_import.wasm
Download http://localhost:4545/wasm/math.ts
local: [WILDLINE]main.js
type: JavaScript
dependencies: 2 unique
size: [WILDLINE]
file:///[WILDLINE]/main.js ([WILDLINE])
└─┬ http://localhost:4545/wasm/math_with_import.wasm ([WILDLINE])
└── http://localhost:4545/wasm/math.ts ([WILDLINE])

View file

@ -0,0 +1,13 @@
{
"tempDir": true,
"steps": [{
"args": "run index.tsx",
"output": "index.out"
}, {
"args": [
"eval",
"console.log(Deno.readTextFileSync('deno.lock').trim())"
],
"output": "deno.lock.out"
}]
}

View file

@ -0,0 +1,10 @@
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "npm:react",
"jsxImportSourceTypes": "npm:@types/react",
"types": [
"npm:@types/node"
]
}
}

View file

@ -0,0 +1,30 @@
{
"version": "4",
"specifiers": {
"npm:react@*": "18.2.0"
},
"npm": {
"js-tokens@4.0.0": {
"integrity": "[WILDLINE]"
},
"loose-envify@1.4.0": {
"integrity": "[WILDLINE]",
"dependencies": [
"js-tokens"
]
},
"react@18.2.0": {
"integrity": "[WILDLINE]",
"dependencies": [
"loose-envify"
]
}
},
"workspace": {
"dependencies": [
"npm:@types/node@*",
"npm:@types/react@*",
"npm:react@*"
]
}
}

View file

@ -0,0 +1,7 @@
Download http://localhost:4260/react
Download http://localhost:4260/loose-envify
Download http://localhost:4260/js-tokens
Download http://localhost:4260/react/react-18.2.0.tgz
Download http://localhost:4260/loose-envify/loose-envify-1.4.0.tgz
Download http://localhost:4260/js-tokens/js-tokens-4.0.0.tgz
1

View file

@ -0,0 +1 @@
console.log(1);

View file

@ -0,0 +1,4 @@
{
"args": "run --quiet main.ts",
"output": "3\n"
}

View file

@ -0,0 +1,3 @@
import { add } from "npm:@denotest/specifier-two-slashes";
console.log(add(1, 2));

View file

@ -0,0 +1,5 @@
{
"args": "publish --token 'sadfasdf'",
"output": "publish.out",
"exitCode": 1
}

View file

@ -0,0 +1,7 @@
{
"name": "@foo/bar",
"version": "1.0.0",
"imports": {
"@std/http": "./std_http.ts"
}
}

View file

@ -0,0 +1,3 @@
export function add(a: number, b: number): number {
return a + b;
}

View file

@ -0,0 +1,8 @@
Warning "exports" field should be specified when specifying a "name".
at file:///[WILDLINE]/deno.json
error: You did not specify an entrypoint in file:///[WILDLINE]/deno.json. Add `exports` mapping in the configuration file, eg:
{
"name": "@foo/bar",
"version": "@foo/bar",
"exports": "mod.ts"
}

View file

@ -0,0 +1,5 @@
{
"args": "publish --set-version 1.1.0 --token 'sadfasdf'",
"output": "error_set_version.out",
"exitCode": 1
}

View file

@ -0,0 +1,8 @@
{
"workspace": {
"members": [
"packages/package1",
"packages/package2"
]
}
}

View file

@ -0,0 +1 @@
error: Cannot use --set-version when publishing a workspace. Change your cwd to an individual package instead.

View file

@ -0,0 +1,7 @@
{
"name": "@foo/package1",
"version": "1.0.0",
"exports": {
".": "./mod.ts"
}
}

View file

@ -0,0 +1,3 @@
export function package1() {
return "package1";
}

View file

@ -0,0 +1,7 @@
{
"name": "@foo/package2",
"version": "1.0.0",
"exports": {
".": "./mod.ts"
}
}

View file

@ -0,0 +1,3 @@
export function package2() {
return "package2";
}

View file

@ -0,0 +1,4 @@
{
"args": "publish --set-version 1.1.0 --token 'sadfasdf'",
"output": "successful_set_version.out"
}

View file

@ -0,0 +1,10 @@
{
"name": "@foo/bar",
"version": "1.0.0",
"exports": {
".": "./mod.ts"
},
"imports": {
"@std/http": "./std_http.ts"
}
}

View file

@ -0,0 +1,7 @@
import http from "@std/http";
export function foobar(): { fileServer(): void } {
return {
fileServer: http.fileServer,
};
}

View file

@ -0,0 +1,6 @@
// temp until we get jsr:@std/http in the test server
export default {
fileServer() {
console.log("Hi");
},
};

View file

@ -0,0 +1,6 @@
Check file:///[WILDCARD]/success/mod.ts
Checking for slow types in the public API...
Check file:///[WILDCARD]/success/mod.ts
Publishing @foo/bar@1.1.0 ...
Successfully published @foo/bar@1.1.0
Visit http://127.0.0.1:4250/@foo/bar@1.1.0 for details

View file

@ -0,0 +1,12 @@
{
"steps": [{
"args": "run -A setup.ts",
"output": "[WILDCARD]"
}, {
"args": "run -A --check main.cts",
"output": "main.out"
}, {
"args": "run -A --check main.cjs",
"output": "main.out"
}]
}

View file

@ -0,0 +1,5 @@
// @ts-check
const { add, subtract } = require("./math.wasm");
console.log(add(1, 2));
console.log(subtract(9, 3));

View file

@ -0,0 +1,4 @@
import WasmModule = require("./math.wasm");
console.log(WasmModule.add(1, 2));
console.log(WasmModule.subtract(9, 3));

View file

@ -0,0 +1,3 @@
Check file:///[WILDLINE]
3
6

Some files were not shown because too many files have changed in this diff Show more