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

Merge branch 'main' into update_deps

This commit is contained in:
Bartek Iwańczuk 2021-09-02 21:11:18 +02:00
commit 37982f662f
No known key found for this signature in database
GPG key ID: 0C6BCDDC3B3AD750
51 changed files with 1299 additions and 2111 deletions

View file

@ -36,9 +36,9 @@
"tools/wpt/manifest.json" "tools/wpt/manifest.json"
], ],
"plugins": [ "plugins": [
"https://plugins.dprint.dev/typescript-0.50.0.wasm", "https://plugins.dprint.dev/typescript-0.53.0.wasm",
"https://plugins.dprint.dev/json-0.12.1.wasm", "https://plugins.dprint.dev/json-0.12.3.wasm",
"https://plugins.dprint.dev/markdown-0.9.2.wasm", "https://plugins.dprint.dev/markdown-0.9.6.wasm",
"https://plugins.dprint.dev/toml-0.4.1.wasm" "https://plugins.dprint.dev/toml-0.5.1.wasm"
] ]
} }

View file

@ -38,7 +38,7 @@ jobs:
# stay mostly up-to-date in situations where a single job fails due to # stay mostly up-to-date in situations where a single job fails due to
# e.g. a flaky test. # e.g. a flaky test.
# Don't fast-fail on tag build because publishing binaries shouldn't be # Don't fast-fail on tag build because publishing binaries shouldn't be
# prevented if if any of the stages fails (which can be a false negative). # prevented if any of the stages fail (which can be a false negative).
fail-fast: ${{ github.event_name == 'pull_request' || fail-fast: ${{ github.event_name == 'pull_request' ||
(github.ref != 'refs/heads/main' && (github.ref != 'refs/heads/main' &&
!startsWith(github.ref, 'refs/tags/')) }} !startsWith(github.ref, 'refs/tags/')) }}

188
Cargo.lock generated
View file

@ -563,6 +563,7 @@ dependencies = [
"deno_doc", "deno_doc",
"deno_fetch", "deno_fetch",
"deno_ffi", "deno_ffi",
"deno_graph",
"deno_http", "deno_http",
"deno_lint", "deno_lint",
"deno_net", "deno_net",
@ -713,10 +714,12 @@ dependencies = [
[[package]] [[package]]
name = "deno_doc" name = "deno_doc"
version = "0.10.0" version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81a543b39492532835f00b94758cf2b731b50c5168e8059608246aaf8e02c229" checksum = "23c860b2359120f1565aafd4e9e5eddf7fcbdb70dc55a97719c00d327570ffce"
dependencies = [ dependencies = [
"cfg-if 1.0.0",
"deno_graph",
"futures", "futures",
"lazy_static", "lazy_static",
"regex", "regex",
@ -755,6 +758,28 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "deno_graph"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec6c70108e13d63f6fa51975f0557d5c0fec80a247c3e51f2a215ef6614b53dc"
dependencies = [
"anyhow",
"cfg-if 1.0.0",
"data-url",
"futures",
"lazy_static",
"regex",
"ring",
"serde",
"serde_json",
"swc_common",
"swc_ecmascript",
"termcolor",
"text_lines",
"url",
]
[[package]] [[package]]
name = "deno_http" name = "deno_http"
version = "0.7.0" version = "0.7.0"
@ -772,9 +797,9 @@ dependencies = [
[[package]] [[package]]
name = "deno_lint" name = "deno_lint"
version = "0.12.0" version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad9f741b34ff43cdf67f3c43d5b7824a4b6c330d1cfb644b1420d3ca68a1787d" checksum = "c0cbb4f64c7884703198d8fb0f67a900e4dfbc456efaabebc419a4d3612da064"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"derive_more", "derive_more",
@ -1043,9 +1068,9 @@ dependencies = [
[[package]] [[package]]
name = "dprint-plugin-typescript" name = "dprint-plugin-typescript"
version = "0.50.2" version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99e1bd07c904835664ed50d0c04ecd5a4f2259a156e3cd2ae5ceeab02e0c9257" checksum = "63674b5e577e3244436463aa8ab59947aba0a3d5b4de6d181c6bd7a3e190b336"
dependencies = [ dependencies = [
"dprint-core", "dprint-core",
"dprint-swc-ecma-ast-view", "dprint-swc-ecma-ast-view",
@ -1057,9 +1082,9 @@ dependencies = [
[[package]] [[package]]
name = "dprint-swc-ecma-ast-view" name = "dprint-swc-ecma-ast-view"
version = "0.25.0" version = "0.33.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31911862aff0e98a1864984450f842b108aa0f4e95aa314539605b093774d329" checksum = "c44a27f32f2bc9347d08e4b8f47db055f4df9b8d9e1236cc2036a9e95707ba7b"
dependencies = [ dependencies = [
"bumpalo", "bumpalo",
"fnv", "fnv",
@ -1067,6 +1092,7 @@ dependencies = [
"swc_atoms", "swc_atoms",
"swc_common", "swc_common",
"swc_ecmascript", "swc_ecmascript",
"text_lines",
] ]
[[package]] [[package]]
@ -1334,9 +1360,9 @@ dependencies = [
[[package]] [[package]]
name = "futures" name = "futures"
version = "0.3.16" version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1adc00f486adfc9ce99f77d717836f0c5aa84965eb0b4f051f4e83f7cab53f8b" checksum = "a12aa0eb539080d55c3f2d45a67c3b58b6b0773c1a3ca2dfec66d58c97fd66ca"
dependencies = [ dependencies = [
"futures-channel", "futures-channel",
"futures-core", "futures-core",
@ -1349,9 +1375,9 @@ dependencies = [
[[package]] [[package]]
name = "futures-channel" name = "futures-channel"
version = "0.3.16" version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74ed2411805f6e4e3d9bc904c95d5d423b89b3b25dc0250aa74729de20629ff9" checksum = "5da6ba8c3bb3c165d3c7319fc1cc8304facf1fb8db99c5de877183c08a273888"
dependencies = [ dependencies = [
"futures-core", "futures-core",
"futures-sink", "futures-sink",
@ -1359,15 +1385,15 @@ dependencies = [
[[package]] [[package]]
name = "futures-core" name = "futures-core"
version = "0.3.16" version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af51b1b4a7fdff033703db39de8802c673eb91855f2e0d47dcf3bf2c0ef01f99" checksum = "88d1c26957f23603395cd326b0ffe64124b818f4449552f960d815cfba83a53d"
[[package]] [[package]]
name = "futures-executor" name = "futures-executor"
version = "0.3.16" version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d0d535a57b87e1ae31437b892713aee90cd2d7b0ee48727cd11fc72ef54761c" checksum = "45025be030969d763025784f7f355043dc6bc74093e4ecc5000ca4dc50d8745c"
dependencies = [ dependencies = [
"futures-core", "futures-core",
"futures-task", "futures-task",
@ -1376,15 +1402,15 @@ dependencies = [
[[package]] [[package]]
name = "futures-io" name = "futures-io"
version = "0.3.16" version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b0e06c393068f3a6ef246c75cdca793d6a46347e75286933e5e75fd2fd11582" checksum = "522de2a0fe3e380f1bc577ba0474108faf3f6b18321dbf60b3b9c39a75073377"
[[package]] [[package]]
name = "futures-macro" name = "futures-macro"
version = "0.3.16" version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c54913bae956fb8df7f4dc6fc90362aa72e69148e3f39041fbe8742d21e0ac57" checksum = "18e4a4b95cea4b4ccbcf1c5675ca7c4ee4e9e75eb79944d07defde18068f79bb"
dependencies = [ dependencies = [
"autocfg 1.0.1", "autocfg 1.0.1",
"proc-macro-hack", "proc-macro-hack",
@ -1395,21 +1421,21 @@ dependencies = [
[[package]] [[package]]
name = "futures-sink" name = "futures-sink"
version = "0.3.16" version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0f30aaa67363d119812743aa5f33c201a7a66329f97d1a887022971feea4b53" checksum = "36ea153c13024fe480590b3e3d4cad89a0cfacecc24577b68f86c6ced9c2bc11"
[[package]] [[package]]
name = "futures-task" name = "futures-task"
version = "0.3.16" version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbe54a98670017f3be909561f6ad13e810d9a51f3f061b902062ca3da80799f2" checksum = "1d3d00f4eddb73e498a54394f228cd55853bdf059259e8e7bc6e69d408892e99"
[[package]] [[package]]
name = "futures-util" name = "futures-util"
version = "0.3.16" version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67eb846bfd58e44a8481a00049e82c43e0ccb5d61f8dc071057cb19249dd4d78" checksum = "36568465210a3a6ee45e1f165136d68671471a501e632e9a98d96872222b5481"
dependencies = [ dependencies = [
"autocfg 1.0.1", "autocfg 1.0.1",
"futures-channel", "futures-channel",
@ -2729,14 +2755,13 @@ dependencies = [
[[package]] [[package]]
name = "regex" name = "regex"
version = "1.4.3" version = "1.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9251239e129e16308e70d853559389de218ac275b515068abc96829d05b948a" checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461"
dependencies = [ dependencies = [
"aho-corasick", "aho-corasick",
"memchr", "memchr",
"regex-syntax", "regex-syntax",
"thread_local",
] ]
[[package]] [[package]]
@ -2925,9 +2950,9 @@ dependencies = [
[[package]] [[package]]
name = "rusty_v8" name = "rusty_v8"
version = "0.26.0" version = "0.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ced8bcb4fdc4820792030377a71cedbde5b49b340c2174ee0ea368ef244bf8f1" checksum = "81fc062fb861b82fa7ac4e1a009da873279a10180d2133574e4219d870038c1c"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"fslock", "fslock",
@ -3074,18 +3099,18 @@ dependencies = [
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.129" version = "1.0.130"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1f72836d2aa753853178eda473a3b9d8e4eefdaf20523b919677e6de489f8f1" checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.129" version = "1.0.130"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e57ae87ad533d9a56427558b516d0adac283614e347abf85b0dc0cbbf0a249f3" checksum = "d7bc1a1ab1961464eae040d96713baa5a724a8152c1222492465b54322ec508b"
dependencies = [ dependencies = [
"proc-macro2 1.0.28", "proc-macro2 1.0.28",
"quote 1.0.9", "quote 1.0.9",
@ -3094,9 +3119,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.66" version = "1.0.67"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "336b10da19a12ad094b59d870ebde26a45402e5b470add4b5fd03c5048a32127" checksum = "a7f9e390c27c3c0ce8bc5d725f6e4d30a29d26659494aa4b17535f7522c5c950"
dependencies = [ dependencies = [
"indexmap", "indexmap",
"itoa", "itoa",
@ -3129,9 +3154,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_v8" name = "serde_v8"
version = "0.9.3" version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5ce7662cda194ff443bddf146c952e83075889590838cd41df768fba7d152d0" checksum = "ae88e9b49b6d2d7c7eae9fd270111e3728ab40b421d57cf58051ce84f9fe560f"
dependencies = [ dependencies = [
"rusty_v8", "rusty_v8",
"serde", "serde",
@ -3353,9 +3378,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_bundler" name = "swc_bundler"
version = "0.50.0" version = "0.56.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "543c7f91128363277dfbfbe0ac574e654b3671717f56f7ba360f1994e020a495" checksum = "1e00938122669f1358a570dad80626ac9007053967aa3e4066440c7946609784"
dependencies = [ dependencies = [
"ahash 0.7.4", "ahash 0.7.4",
"anyhow", "anyhow",
@ -3382,9 +3407,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_common" name = "swc_common"
version = "0.11.7" version = "0.11.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2bcafc4aad3933ee8e00a560521dcf77b39f66713a073de19841c1bd2c4c49c" checksum = "0a873d7284ebc53a9051f41068dc2cb979e399a4a1fab25d9c0dee9f8db4d1f5"
dependencies = [ dependencies = [
"ahash 0.7.4", "ahash 0.7.4",
"ast_node", "ast_node",
@ -3407,9 +3432,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_ast" name = "swc_ecma_ast"
version = "0.49.5" version = "0.51.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f135a9c200f058d5bec4e63b34712f412db0d2e894bf22b8b44b0740be6607" checksum = "0541aee098b52870ef6181deae2fbe3f3025605f2e6f27b3993e6f66607a46a1"
dependencies = [ dependencies = [
"is-macro", "is-macro",
"num-bigint", "num-bigint",
@ -3421,9 +3446,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_codegen" name = "swc_ecma_codegen"
version = "0.66.3" version = "0.69.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "582151b33ccf0b17981572d0d8082c8e3259ffbab21d47078f23a68d65e9e8a0" checksum = "58e7b482064bc6386168de843b85fddb6b70fc2cd86323962821642a253fa427"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"num-bigint", "num-bigint",
@ -3450,9 +3475,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_dep_graph" name = "swc_ecma_dep_graph"
version = "0.34.1" version = "0.38.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f04ff0de9a70fa06a23e85fddd2dc077fe840905635e9ecc6211169cdf6717d" checksum = "630fe1a1464a64c64cdc9ca8c0d0a8358c66e1ca79cb8acf577e429dff56a104"
dependencies = [ dependencies = [
"swc_atoms", "swc_atoms",
"swc_common", "swc_common",
@ -3462,11 +3487,13 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_loader" name = "swc_ecma_loader"
version = "0.12.0" version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05e3b054b690e610384fc8f5d244182cbd62691423755ca1c4b05cb0bfa6b46" checksum = "2e9796ff40909d124ac382bf89fd94bb3a108e1f6a5c7786e3dd54b9fb579dff"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"fxhash",
"log",
"swc_atoms", "swc_atoms",
"swc_common", "swc_common",
"swc_ecma_ast", "swc_ecma_ast",
@ -3475,9 +3502,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_parser" name = "swc_ecma_parser"
version = "0.66.6" version = "0.69.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03e57597bc7e16e815f1634f84b9e77dedba2f3fc56ba7168d55dbeb6546e902" checksum = "c7eb1f1c556118750c7871bef5c9f37cd9cac9f5d6479b922aa026cebf1fac18"
dependencies = [ dependencies = [
"either", "either",
"enum_kind", "enum_kind",
@ -3496,9 +3523,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_transforms" name = "swc_ecma_transforms"
version = "0.63.0" version = "0.69.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f53f948b9fb8a315b1e0d5f121b8c88786feb11b7f01f8406c16301e0ad2227" checksum = "9214e4c1349c7cbdaa364fb9f67c4db3b028425be605e05fb7c387af1e788113"
dependencies = [ dependencies = [
"swc_atoms", "swc_atoms",
"swc_common", "swc_common",
@ -3516,9 +3543,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_transforms_base" name = "swc_ecma_transforms_base"
version = "0.26.3" version = "0.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db308cf88089d13235d103a53a6c5c670457ad0203c41712f26d19320c851b3f" checksum = "3b0aa724a347be8c2a14e3debdec192531a865388595114d7685f123e9780731"
dependencies = [ dependencies = [
"fxhash", "fxhash",
"once_cell", "once_cell",
@ -3535,9 +3562,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_transforms_classes" name = "swc_ecma_transforms_classes"
version = "0.12.2" version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32671ce21128abec95aae6dbb7aa03f6bc117de0ff3b3cb70022480f18fd17a9" checksum = "5f55f90a828f89127ebf063e60b3ad97c3e6c339999e9304e350f72cd3187e5c"
dependencies = [ dependencies = [
"swc_atoms", "swc_atoms",
"swc_common", "swc_common",
@ -3549,9 +3576,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_transforms_optimization" name = "swc_ecma_transforms_optimization"
version = "0.33.0" version = "0.39.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47dc701cc94f8b4b8d2b4b79b91457b91b565edffe67e2a497adcb3f48b716fe" checksum = "c28f88330eed13b1e58522ae42acd09d516ed65d3bf80b64d0bc794ffc4627b5"
dependencies = [ dependencies = [
"dashmap", "dashmap",
"fxhash", "fxhash",
@ -3571,9 +3598,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_transforms_proposal" name = "swc_ecma_transforms_proposal"
version = "0.30.0" version = "0.36.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd2ce24868d4a97bcd6f38ab7e96798c16a1efa821564e32d07d137e3d904fc7" checksum = "8f926eb4c5e1526f52da2b56d66649d64a0f77da417c30d144789fa7eb741007"
dependencies = [ dependencies = [
"either", "either",
"fxhash", "fxhash",
@ -3591,9 +3618,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_transforms_react" name = "swc_ecma_transforms_react"
version = "0.31.1" version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7174a06bfb2f507eb35dbb919679e3df73fc41f152261cbf191f1afe5e14823" checksum = "2ce5289df2c034b45edf839cc3a356dcd035102f5e591b1eb5c37204e3007006"
dependencies = [ dependencies = [
"base64 0.13.0", "base64 0.13.0",
"dashmap", "dashmap",
@ -3614,9 +3641,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_transforms_typescript" name = "swc_ecma_transforms_typescript"
version = "0.32.0" version = "0.38.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6fe1a79c928e9844f199365746b482accb6ca7a25a9d0d8b6b1bf3277a357ec" checksum = "86c22e8077c8fa6225d5d2ab4fcef223d155c1fa30304c06aaf0e6b6934396f3"
dependencies = [ dependencies = [
"fxhash", "fxhash",
"serde", "serde",
@ -3631,9 +3658,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_utils" name = "swc_ecma_utils"
version = "0.41.4" version = "0.43.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50339f726a63cde28f74ae2b4b98949bced74841ba7e02a135b915063c8e1566" checksum = "7755b2d35e93fc371186335d0cc65b1cc647c113b60e1a44ab8f679bf09521d6"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"scoped-tls", "scoped-tls",
@ -3646,9 +3673,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecma_visit" name = "swc_ecma_visit"
version = "0.35.2" version = "0.37.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d51ce688b7c984d0325261edb3ced4195790c7ac76982e269d2114ec04e3ae7c" checksum = "253528a42ad8a646ff7904e3770464f014331f7647467166a8ad92725910d85c"
dependencies = [ dependencies = [
"num-bigint", "num-bigint",
"swc_atoms", "swc_atoms",
@ -3659,9 +3686,9 @@ dependencies = [
[[package]] [[package]]
name = "swc_ecmascript" name = "swc_ecmascript"
version = "0.52.1" version = "0.60.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12c0f3969671267e85a7a387e2db40d01c0e7e6e979d7fd27bdeef501a2f6d14" checksum = "2cb79d3e236ce0118e370f75a37a85ccc527338cf8d4697a7d23419711a6169f"
dependencies = [ dependencies = [
"swc_ecma_ast", "swc_ecma_ast",
"swc_ecma_codegen", "swc_ecma_codegen",
@ -3821,6 +3848,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "288cb548dbe72b652243ea797201f3d481a0609a967980fcc5b2315ea811560a" checksum = "288cb548dbe72b652243ea797201f3d481a0609a967980fcc5b2315ea811560a"
[[package]]
name = "text_lines"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "116279ecd8fa26fbdcf20c79ee6f85a5ce325a953486e11e71c51670bdaa308f"
[[package]] [[package]]
name = "textwrap" name = "textwrap"
version = "0.11.0" version = "0.11.0"
@ -3850,15 +3883,6 @@ dependencies = [
"syn 1.0.65", "syn 1.0.65",
] ]
[[package]]
name = "thread_local"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8018d24e04c95ac8790716a5987d0fec4f8b27249ffa0f7d33f1369bdfb88cbd"
dependencies = [
"once_cell",
]
[[package]] [[package]]
name = "time" name = "time"
version = "0.1.44" version = "0.1.44"

View file

@ -44,8 +44,9 @@ winres = "0.1.11"
[dependencies] [dependencies]
deno_core = { version = "0.98.0", path = "../core" } deno_core = { version = "0.98.0", path = "../core" }
deno_doc = "0.10.0" deno_doc = "0.12.1"
deno_lint = "0.12.0" deno_graph = "0.3.1"
deno_lint = { version = "0.14.0", features = ["docs"] }
deno_runtime = { version = "0.24.0", path = "../runtime" } deno_runtime = { version = "0.24.0", path = "../runtime" }
deno_tls = { version = "0.3.0", path = "../ext/tls" } deno_tls = { version = "0.3.0", path = "../ext/tls" }
@ -57,7 +58,7 @@ data-url = "0.1.0"
dissimilar = "1.0.2" dissimilar = "1.0.2"
dprint-plugin-json = "0.12.3" dprint-plugin-json = "0.12.3"
dprint-plugin-markdown = "0.9.6" dprint-plugin-markdown = "0.9.6"
dprint-plugin-typescript = "0.50.2" dprint-plugin-typescript = "0.53.0"
encoding_rs = "0.8.28" encoding_rs = "0.8.28"
env_logger = "0.8.4" env_logger = "0.8.4"
fancy-regex = "0.7.1" fancy-regex = "0.7.1"
@ -83,9 +84,9 @@ semver-parser = "0.10.2"
serde = { version = "1.0.129", features = ["derive"] } serde = { version = "1.0.129", features = ["derive"] }
shell-escape = "0.1.5" shell-escape = "0.1.5"
sourcemap = "6.0.1" sourcemap = "6.0.1"
swc_bundler = "0.50.0" swc_bundler = "0.56.0"
swc_common = { version = "0.11.7", features = ["sourcemap"] } swc_common = { version = "0.11.9", features = ["sourcemap"] }
swc_ecmascript = { version = "0.52.1", features = ["codegen", "dep_graph", "parser", "proposal", "react", "transforms", "typescript", "visit"] } swc_ecmascript = { version = "0.60.0", features = ["codegen", "dep_graph", "parser", "proposal", "react", "transforms", "typescript", "visit"] }
tempfile = "3.2.0" tempfile = "3.2.0"
termcolor = "1.1.2" termcolor = "1.1.2"
text-size = "1.1.0" text-size = "1.1.0"

View file

@ -6,13 +6,24 @@ function benchSync(name, n, innerLoop) {
innerLoop(i); innerLoop(i);
} }
const t2 = Date.now(); const t2 = Date.now();
console.log(benchStats(name, n, t1, t2));
}
async function benchAsync(name, n, innerLoop) {
const t1 = Date.now();
for (let i = 0; i < n; i++) {
await innerLoop(i);
}
const t2 = Date.now();
console.log(benchStats(name, n, t1, t2));
}
function benchStats(name, n, t1, t2) {
const dt = (t2 - t1) / 1e3; const dt = (t2 - t1) / 1e3;
const r = n / dt; const r = n / dt;
const ns = Math.floor(dt / n * 1e9); const ns = Math.floor(dt / n * 1e9);
console.log( return `${name}:${" ".repeat(20 - name.length)}\t` +
`${name}:${" ".repeat(20 - name.length)}\t` + `n = ${n}, dt = ${dt.toFixed(3)}s, r = ${r.toFixed(0)}/s, t = ${ns}ns/op`;
`n = ${n}, dt = ${dt.toFixed(3)}s, r = ${r.toFixed(0)}/s, t = ${ns}ns/op`,
);
} }
function benchUrlParse() { function benchUrlParse() {
@ -52,7 +63,15 @@ function benchReadZero() {
Deno.close(file.rid); Deno.close(file.rid);
} }
function main() { function benchRead128k() {
return benchAsync(
"read_128k",
5e4,
() => Deno.readFile("./cli/bench/fixtures/128k.bin"),
);
}
async function main() {
// v8 builtin that's close to the upper bound non-NOPs // v8 builtin that's close to the upper bound non-NOPs
benchDateNow(); benchDateNow();
// A very lightweight op, that should be highly optimizable // A very lightweight op, that should be highly optimizable
@ -63,5 +82,6 @@ function main() {
// IO ops // IO ops
benchReadZero(); benchReadZero();
benchWriteNull(); benchWriteNull();
await benchRead128k();
} }
main(); await main();

View file

@ -12,11 +12,8 @@ for await (const conn of listener) {
(async () => { (async () => {
const requests = Deno.serveHttp(conn); const requests = Deno.serveHttp(conn);
for await (const { respondWith } of requests) { for await (const { respondWith } of requests) {
try { respondWith(new Response(body))
respondWith(new Response(body)); .catch((e) => console.log(e));
} catch {
// Ignore.
}
} }
})(); })();
} }

BIN
cli/bench/fixtures/128k.bin Normal file

Binary file not shown.

View file

@ -69,10 +69,6 @@ fn create_compiler_snapshot(
deno_broadcast_channel::get_declaration(), deno_broadcast_channel::get_declaration(),
); );
op_crate_libs.insert("deno.net", deno_net::get_declaration()); op_crate_libs.insert("deno.net", deno_net::get_declaration());
op_crate_libs
.insert("deno.net_unstable", deno_net::get_unstable_declaration());
op_crate_libs
.insert("deno.http_unstable", deno_http::get_unstable_declaration());
// ensure we invalidate the build properly. // ensure we invalidate the build properly.
for (_, path) in op_crate_libs.iter() { for (_, path) in op_crate_libs.iter() {
@ -320,14 +316,6 @@ fn main() {
"cargo:rustc-env=DENO_NET_LIB_PATH={}", "cargo:rustc-env=DENO_NET_LIB_PATH={}",
deno_net::get_declaration().display() deno_net::get_declaration().display()
); );
println!(
"cargo:rustc-env=DENO_NET_UNSTABLE_LIB_PATH={}",
deno_net::get_unstable_declaration().display()
);
println!(
"cargo:rustc-env=DENO_HTTP_UNSTABLE_LIB_PATH={}",
deno_http::get_unstable_declaration().display()
);
println!("cargo:rustc-env=TARGET={}", env::var("TARGET").unwrap()); println!("cargo:rustc-env=TARGET={}", env::var("TARGET").unwrap());
println!("cargo:rustc-env=PROFILE={}", env::var("PROFILE").unwrap()); println!("cargo:rustc-env=PROFILE={}", env::var("PROFILE").unwrap());

View file

@ -2,8 +2,6 @@
/// <reference no-default-lib="true" /> /// <reference no-default-lib="true" />
/// <reference lib="deno.ns" /> /// <reference lib="deno.ns" />
/// <reference lib="deno.net_unstable" />
/// <reference lib="deno.http_unstable" />
declare namespace Deno { declare namespace Deno {
/** /**
@ -1094,6 +1092,305 @@ declare namespace Deno {
write?: "inherit" | boolean | Array<string | URL>; write?: "inherit" | boolean | Array<string | URL>;
}; };
} }
export interface WebSocketUpgrade {
response: Response;
socket: WebSocket;
}
export interface UpgradeWebSocketOptions {
protocol?: string;
}
/** **UNSTABLE**: new API, yet to be vetted.
*
* Used to upgrade an incoming HTTP request to a WebSocket.
*
* Given a request, returns a pair of WebSocket and Response. The original
* request must be responded to with the returned response for the websocket
* upgrade to be successful.
*
* ```ts
* const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" });
* const httpConn = Deno.serveHttp(conn);
* const e = await httpConn.nextRequest();
* if (e) {
* const { socket, response } = Deno.upgradeWebSocket(e.request);
* socket.onopen = () => {
* socket.send("Hello World!");
* };
* socket.onmessage = (e) => {
* console.log(e.data);
* socket.close();
* };
* socket.onclose = () => console.log("WebSocket has been closed.");
* socket.onerror = (e) => console.error("WebSocket error:", e);
* e.respondWith(response);
* }
* ```
*
* If the request body is disturbed (read from) before the upgrade is
* completed, upgrading fails.
*
* This operation does not yet consume the request or open the websocket. This
* only happens once the returned response has been passed to `respondWith`.
*/
export function upgradeWebSocket(
request: Request,
options?: UpgradeWebSocketOptions,
): WebSocketUpgrade;
/** The type of the resource record.
* Only the listed types are supported currently. */
export type RecordType =
| "A"
| "AAAA"
| "ANAME"
| "CNAME"
| "MX"
| "PTR"
| "SRV"
| "TXT";
export interface ResolveDnsOptions {
/** The name server to be used for lookups.
* If not specified, defaults to the system configuration e.g. `/etc/resolv.conf` on Unix. */
nameServer?: {
/** The IP address of the name server */
ipAddr: string;
/** The port number the query will be sent to.
* If not specified, defaults to 53. */
port?: number;
};
}
/** If `resolveDns` is called with "MX" record type specified, it will return an array of this interface. */
export interface MXRecord {
preference: number;
exchange: string;
}
/** If `resolveDns` is called with "SRV" record type specified, it will return an array of this interface. */
export interface SRVRecord {
priority: number;
weight: number;
port: number;
target: string;
}
export function resolveDns(
query: string,
recordType: "A" | "AAAA" | "ANAME" | "CNAME" | "PTR",
options?: ResolveDnsOptions,
): Promise<string[]>;
export function resolveDns(
query: string,
recordType: "MX",
options?: ResolveDnsOptions,
): Promise<MXRecord[]>;
export function resolveDns(
query: string,
recordType: "SRV",
options?: ResolveDnsOptions,
): Promise<SRVRecord[]>;
export function resolveDns(
query: string,
recordType: "TXT",
options?: ResolveDnsOptions,
): Promise<string[][]>;
/** ** UNSTABLE**: new API, yet to be vetted.
*
* Performs DNS resolution against the given query, returning resolved records.
* Fails in the cases such as:
* - the query is in invalid format
* - the options have an invalid parameter, e.g. `nameServer.port` is beyond the range of 16-bit unsigned integer
* - timed out
*
* ```ts
* const a = await Deno.resolveDns("example.com", "A");
*
* const aaaa = await Deno.resolveDns("example.com", "AAAA", {
* nameServer: { ipAddr: "8.8.8.8", port: 1234 },
* });
* ```
*
* Requires `allow-net` permission.
*/
export function resolveDns(
query: string,
recordType: RecordType,
options?: ResolveDnsOptions,
): Promise<string[] | MXRecord[] | SRVRecord[] | string[][]>;
/** **UNSTABLE**: new API, yet to be vetted.
*
* A generic transport listener for message-oriented protocols. */
export interface DatagramConn extends AsyncIterable<[Uint8Array, Addr]> {
/** **UNSTABLE**: new API, yet to be vetted.
*
* Waits for and resolves to the next message to the `UDPConn`. */
receive(p?: Uint8Array): Promise<[Uint8Array, Addr]>;
/** UNSTABLE: new API, yet to be vetted.
*
* Sends a message to the target. */
send(p: Uint8Array, addr: Addr): Promise<number>;
/** UNSTABLE: new API, yet to be vetted.
*
* Close closes the socket. Any pending message promises will be rejected
* with errors. */
close(): void;
/** Return the address of the `UDPConn`. */
readonly addr: Addr;
[Symbol.asyncIterator](): AsyncIterableIterator<[Uint8Array, Addr]>;
}
export interface UnixListenOptions {
/** A Path to the Unix Socket. */
path: string;
}
/** **UNSTABLE**: new API, yet to be vetted.
*
* Listen announces on the local transport address.
*
* ```ts
* const listener = Deno.listen({ path: "/foo/bar.sock", transport: "unix" })
* ```
*
* Requires `allow-read` and `allow-write` permission. */
export function listen(
options: UnixListenOptions & { transport: "unix" },
): Listener;
/** **UNSTABLE**: new API, yet to be vetted
*
* Listen announces on the local transport address.
*
* ```ts
* const listener1 = Deno.listenDatagram({
* port: 80,
* transport: "udp"
* });
* const listener2 = Deno.listenDatagram({
* hostname: "golang.org",
* port: 80,
* transport: "udp"
* });
* ```
*
* Requires `allow-net` permission. */
export function listenDatagram(
options: ListenOptions & { transport: "udp" },
): DatagramConn;
/** **UNSTABLE**: new API, yet to be vetted
*
* Listen announces on the local transport address.
*
* ```ts
* const listener = Deno.listenDatagram({
* path: "/foo/bar.sock",
* transport: "unixpacket"
* });
* ```
*
* Requires `allow-read` and `allow-write` permission. */
export function listenDatagram(
options: UnixListenOptions & { transport: "unixpacket" },
): DatagramConn;
export interface UnixConnectOptions {
transport: "unix";
path: string;
}
/** **UNSTABLE**: The unix socket transport is unstable as a new API yet to
* be vetted. The TCP transport is considered stable.
*
* Connects to the hostname (default is "127.0.0.1") and port on the named
* transport (default is "tcp"), and resolves to the connection (`Conn`).
*
* ```ts
* const conn1 = await Deno.connect({ port: 80 });
* const conn2 = await Deno.connect({ hostname: "192.0.2.1", port: 80 });
* const conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
* const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
* const conn5 = await Deno.connect({ path: "/foo/bar.sock", transport: "unix" });
* ```
*
* Requires `allow-net` permission for "tcp" and `allow-read` for "unix". */
export function connect(
options: ConnectOptions | UnixConnectOptions,
): Promise<Conn>;
export interface ConnectTlsClientCertOptions {
/** PEM formatted client certificate chain. */
certChain: string;
/** PEM formatted (RSA or PKCS8) private key of client certificate. */
privateKey: string;
}
/** **UNSTABLE** New API, yet to be vetted.
*
* Create a TLS connection with an attached client certificate.
*
* ```ts
* const conn = await Deno.connectTls({
* hostname: "deno.land",
* port: 443,
* certChain: "---- BEGIN CERTIFICATE ----\n ...",
* privateKey: "---- BEGIN PRIVATE KEY ----\n ...",
* });
* ```
*
* Requires `allow-net` permission.
*/
export function connectTls(
options: ConnectTlsOptions & ConnectTlsClientCertOptions,
): Promise<Conn>;
export interface StartTlsOptions {
/** A literal IP address or host name that can be resolved to an IP address.
* If not specified, defaults to `127.0.0.1`. */
hostname?: string;
/** Server certificate file. */
certFile?: string;
}
/** **UNSTABLE**: new API, yet to be vetted.
*
* Start TLS handshake from an existing connection using
* an optional cert file, hostname (default is "127.0.0.1"). The
* cert file is optional and if not included Mozilla's root certificates will
* be used (see also https://github.com/ctz/webpki-roots for specifics)
* Using this function requires that the other end of the connection is
* prepared for TLS handshake.
*
* ```ts
* const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" });
* const tlsConn = await Deno.startTls(conn, { certFile: "./certs/my_custom_root_CA.pem", hostname: "localhost" });
* ```
*
* Requires `allow-net` permission.
*/
export function startTls(
conn: Conn,
options?: StartTlsOptions,
): Promise<Conn>;
export interface ListenTlsOptions {
/** **UNSTABLE**: new API, yet to be vetted.
*
* Application-Layer Protocol Negotiation (ALPN) protocols to announce to
* the client. If not specified, no ALPN extension will be included in the
* TLS handshake.
*/
alpnProtocols?: string[];
}
} }
declare function fetch( declare function fetch(

View file

@ -56,6 +56,8 @@ pub struct File {
/// The _final_ specifier for the file. The requested specifier and the final /// The _final_ specifier for the file. The requested specifier and the final
/// specifier maybe different for remote files that have been redirected. /// specifier maybe different for remote files that have been redirected.
pub specifier: ModuleSpecifier, pub specifier: ModuleSpecifier,
pub maybe_headers: Option<HashMap<String, String>>,
} }
/// Simple struct implementing in-process caching to prevent multiple /// Simple struct implementing in-process caching to prevent multiple
@ -137,6 +139,7 @@ fn fetch_local(specifier: &ModuleSpecifier) -> Result<File, AnyError> {
media_type, media_type,
source, source,
specifier: specifier.clone(), specifier: specifier.clone(),
maybe_headers: None,
}) })
} }
@ -274,6 +277,7 @@ impl FileFetcher {
media_type, media_type,
source, source,
specifier: specifier.clone(), specifier: specifier.clone(),
maybe_headers: Some(headers.clone()),
}) })
} }
@ -365,6 +369,7 @@ impl FileFetcher {
media_type, media_type,
source, source,
specifier: specifier.clone(), specifier: specifier.clone(),
maybe_headers: None,
}) })
} }
@ -426,6 +431,7 @@ impl FileFetcher {
media_type, media_type,
source, source,
specifier: specifier.clone(), specifier: specifier.clone(),
maybe_headers: None,
}) })
} }
/// Asynchronously fetch remote source file specified by the URL following /// Asynchronously fetch remote source file specified by the URL following
@ -894,6 +900,7 @@ mod tests {
media_type: MediaType::TypeScript, media_type: MediaType::TypeScript,
source: "some source code".to_string(), source: "some source code".to_string(),
specifier: specifier.clone(), specifier: specifier.clone(),
maybe_headers: None,
}; };
file_fetcher.insert_cached(file.clone()); file_fetcher.insert_cached(file.clone());

View file

@ -120,12 +120,12 @@ impl Reference {
fn as_lsp_range(range: &deno_lint::diagnostic::Range) -> Range { fn as_lsp_range(range: &deno_lint::diagnostic::Range) -> Range {
Range { Range {
start: Position { start: Position {
line: (range.start.line - 1) as u32, line: range.start.line_index as u32,
character: range.start.col as u32, character: range.start.column_index as u32,
}, },
end: Position { end: Position {
line: (range.end.line - 1) as u32, line: range.end.line_index as u32,
character: range.end.col as u32, character: range.end.column_index as u32,
}, },
} }
} }
@ -1172,13 +1172,13 @@ mod tests {
fn test_as_lsp_range() { fn test_as_lsp_range() {
let fixture = deno_lint::diagnostic::Range { let fixture = deno_lint::diagnostic::Range {
start: deno_lint::diagnostic::Position { start: deno_lint::diagnostic::Position {
line: 1, line_index: 0,
col: 2, column_index: 2,
byte_pos: 23, byte_pos: 23,
}, },
end: deno_lint::diagnostic::Position { end: deno_lint::diagnostic::Position {
line: 2, line_index: 1,
col: 0, column_index: 0,
byte_pos: 33, byte_pos: 33,
}, },
}; };

View file

@ -358,8 +358,6 @@ pub fn get_types(unstable: bool) -> String {
if unstable { if unstable {
types.push(crate::tsc::UNSTABLE_NS_LIB); types.push(crate::tsc::UNSTABLE_NS_LIB);
types.push(crate::tsc::DENO_NET_UNSTABLE_LIB);
types.push(crate::tsc::DENO_HTTP_UNSTABLE_LIB);
} }
types.join("\n") types.join("\n")
@ -568,6 +566,7 @@ async fn eval_command(
}, },
source: String::from_utf8(source_code)?, source: String::from_utf8(source_code)?,
specifier: main_module.clone(), specifier: main_module.clone(),
maybe_headers: None,
}; };
// Save our fake file into file fetcher cache // Save our fake file into file fetcher cache
@ -817,6 +816,7 @@ async fn run_from_stdin(flags: Flags) -> Result<(), AnyError> {
media_type: MediaType::TypeScript, media_type: MediaType::TypeScript,
source: String::from_utf8(source)?, source: String::from_utf8(source)?,
specifier: main_module.clone(), specifier: main_module.clone(),
maybe_headers: None,
}; };
// Save our fake file into file fetcher cache // Save our fake file into file fetcher cache
// to allow module access by TS compiler // to allow module access by TS compiler

View file

@ -67,6 +67,12 @@ itest!(doc {
output: "test/doc.out", 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 { itest!(markdown {
args: "test --doc --allow-all test/markdown.md", args: "test --doc --allow-all test/markdown.md",
exit_code: 1, exit_code: 1,

View file

@ -2,10 +2,10 @@ function a() {
console.log("a"); console.log("a");
} }
var O1; var O1;
(function(O1) { (function(O) {
O1[O1["A"] = 0] = "A"; O[O["A"] = 0] = "A";
O1[O1["B"] = 1] = "B"; O[O["B"] = 1] = "B";
O1[O1["C"] = 2] = "C"; O[O["C"] = 2] = "C";
})(O1 || (O1 = { })(O1 || (O1 = {
})); }));
export { O1 as O }; export { O1 as O };

View file

@ -58,7 +58,7 @@
"errors": [ "errors": [
{ {
"file_path": "[WILDCARD]malformed.js", "file_path": "[WILDCARD]malformed.js",
"message": "Expected }, got <eof> at [WILDCARD]malformed.js:4:15" "message": "Expected }, got <eof> at [WILDCARD]malformed.js:4:16"
} }
] ]
} }

5
cli/tests/testdata/test/doc_only.out vendored Normal file
View file

@ -0,0 +1,5 @@
Check [WILDCARD]/test/doc_only/mod.ts$2-5.ts
running 0 tests from [WILDCARD]/test/doc_only/mod.ts
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out ([WILDCARD])

10
cli/tests/testdata/test/doc_only/mod.ts vendored Normal file
View file

@ -0,0 +1,10 @@
/**
* ```ts
* import "./mod.ts";
* ```
*/
Deno.test("unreachable", function () {
throw new Error(
"modules that don't end with _test are scanned for documentation tests only should not be executed",
);
});

View file

@ -1,7 +1,16 @@
import { assert } from "../../../../test_util/std/testing/asserts.ts";
onmessage = function (e) { onmessage = function (e) {
if (typeof self.Deno === "undefined") { if (typeof self.Deno === "undefined") {
throw new Error("Deno namespace not available in worker"); throw new Error("Deno namespace not available in worker");
} }
assert(!Object.isFrozen(self.Deno));
const desc = Object.getOwnPropertyDescriptor(self, "Deno");
assert(desc);
assert(desc.configurable);
assert(!desc.writable);
postMessage(e.data); postMessage(e.data);
}; };

View file

@ -1,4 +1,5 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
// deno-lint-ignore-file no-window-prefix
import { assertEquals, unitTest } from "./test_util.ts"; import { assertEquals, unitTest } from "./test_util.ts";
unitTest(function addEventListenerTest() { unitTest(function addEventListenerTest() {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
// deno-lint-ignore-file no-window-prefix
import { assert, unitTest } from "./test_util.ts"; import { assert, unitTest } from "./test_util.ts";
unitTest(function globalThisExists() { unitTest(function globalThisExists() {

View file

@ -243,22 +243,45 @@ unitTest(async function testSignRSASSAKey() {
assert(signature); assert(signature);
}); });
unitTest(async function subtleCryptoHmacImportExport() {
// deno-fmt-ignore // deno-fmt-ignore
const rawKey = new Uint8Array([ const rawKey = new Uint8Array([
1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16 9, 10, 11, 12, 13, 14, 15, 16
]); ]);
const key = await crypto.subtle.importKey(
const jwk: JsonWebKey = {
kty: "oct",
// unpadded base64 for rawKey.
k: "AQIDBAUGBwgJCgsMDQ4PEA",
alg: "HS256",
ext: true,
"key_ops": ["sign"],
};
unitTest(async function subtleCryptoHmacImportExport() {
const key1 = await crypto.subtle.importKey(
"raw", "raw",
rawKey, rawKey,
{ name: "HMAC", hash: "SHA-256" }, { name: "HMAC", hash: "SHA-256" },
true, true,
["sign"], ["sign"],
); );
const actual = await crypto.subtle.sign( const key2 = await crypto.subtle.importKey(
"jwk",
jwk,
{ name: "HMAC", hash: "SHA-256" },
true,
["sign"],
);
const actual1 = await crypto.subtle.sign(
{ name: "HMAC" }, { name: "HMAC" },
key, key1,
new Uint8Array([1, 2, 3, 4]),
);
const actual2 = await crypto.subtle.sign(
{ name: "HMAC" },
key2,
new Uint8Array([1, 2, 3, 4]), new Uint8Array([1, 2, 3, 4]),
); );
// deno-fmt-ignore // deno-fmt-ignore
@ -269,10 +292,17 @@ unitTest(async function subtleCryptoHmacImportExport() {
23, 122, 222, 1, 146, 46, 182, 87, 23, 122, 222, 1, 146, 46, 182, 87,
]); ]);
assertEquals( assertEquals(
new Uint8Array(actual), new Uint8Array(actual1),
expected,
);
assertEquals(
new Uint8Array(actual2),
expected, expected,
); );
const exportedKey = await crypto.subtle.exportKey("raw", key); const exportedKey1 = await crypto.subtle.exportKey("raw", key1);
assertEquals(new Uint8Array(exportedKey), rawKey); assertEquals(new Uint8Array(exportedKey1), rawKey);
const exportedKey2 = await crypto.subtle.exportKey("jwk", key2);
assertEquals(exportedKey2, jwk);
}); });

View file

@ -5,75 +5,89 @@ use crate::colors;
use crate::file_fetcher::File; use crate::file_fetcher::File;
use crate::flags::Flags; use crate::flags::Flags;
use crate::get_types; use crate::get_types;
use crate::import_map::ImportMap;
use crate::media_type::MediaType; use crate::media_type::MediaType;
use crate::module_graph;
use crate::program_state::ProgramState; use crate::program_state::ProgramState;
use crate::specifier_handler::FetchHandler;
use crate::write_json_to_stdout; use crate::write_json_to_stdout;
use crate::write_to_stdout_ignore_sigpipe; use crate::write_to_stdout_ignore_sigpipe;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::futures::future;
use deno_core::futures::future::FutureExt; use deno_core::futures::future::FutureExt;
use deno_core::futures::Future;
use deno_core::parking_lot::Mutex;
use deno_core::resolve_url_or_path; use deno_core::resolve_url_or_path;
use deno_doc as doc; use deno_doc as doc;
use deno_doc::parser::DocFileLoader; use deno_graph::create_graph;
use deno_graph::source::LoadFuture;
use deno_graph::source::LoadResponse;
use deno_graph::source::Loader;
use deno_graph::source::Resolver;
use deno_graph::ModuleSpecifier;
use deno_runtime::permissions::Permissions; use deno_runtime::permissions::Permissions;
use std::path::PathBuf; use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc; use std::sync::Arc;
use swc_ecmascript::parser::Syntax;
type DocResult = Result<(Syntax, String), doc::DocError>;
/// When parsing lib.deno.d.ts, only `DocParser::parse_source` is used,
/// which never even references the loader, so this is just a stub for that scenario.
///
/// TODO(Liamolucko): Refactor `deno_doc` so this isn't necessary.
struct StubDocLoader; struct StubDocLoader;
impl DocFileLoader for StubDocLoader { impl Loader for StubDocLoader {
fn resolve( fn load(
&self, &mut self,
_specifier: &str, specifier: &ModuleSpecifier,
_referrer: &str, _is_dynamic: bool,
) -> Result<String, doc::DocError> { ) -> LoadFuture {
unreachable!() Box::pin(future::ready((specifier.clone(), Ok(None))))
}
fn load_source_code(
&self,
_specifier: &str,
) -> Pin<Box<dyn Future<Output = DocResult>>> {
unreachable!()
} }
} }
impl DocFileLoader for module_graph::Graph { #[derive(Debug)]
struct DocResolver {
import_map: Option<ImportMap>,
}
impl Resolver for DocResolver {
fn resolve( fn resolve(
&self, &self,
specifier: &str, specifier: &str,
referrer: &str, referrer: &ModuleSpecifier,
) -> Result<String, doc::DocError> { ) -> Result<ModuleSpecifier, AnyError> {
let referrer = if let Some(import_map) = &self.import_map {
resolve_url_or_path(referrer).expect("Expected valid specifier"); return import_map
match self.resolve(specifier, &referrer, true) { .resolve(specifier, referrer.as_str())
Ok(specifier) => Ok(specifier.to_string()), .map_err(AnyError::from);
Err(e) => Err(doc::DocError::Resolve(e.to_string())), }
let module_specifier =
deno_core::resolve_import(specifier, referrer.as_str())?;
Ok(module_specifier)
} }
} }
fn load_source_code( struct DocLoader {
&self, program_state: Arc<ProgramState>,
specifier: &str, }
) -> Pin<Box<dyn Future<Output = DocResult>>> {
let specifier = impl Loader for DocLoader {
resolve_url_or_path(specifier).expect("Expected valid specifier"); fn load(
let source = self.get_source(&specifier).expect("Unknown dependency"); &mut self,
let media_type = specifier: &ModuleSpecifier,
self.get_media_type(&specifier).expect("Unknown media type"); _is_dynamic: bool,
let syntax = ast::get_syntax(&media_type); ) -> LoadFuture {
async move { Ok((syntax, source)) }.boxed_local() let specifier = specifier.clone();
let program_state = self.program_state.clone();
async move {
let result = program_state
.file_fetcher
.fetch(&specifier, &mut Permissions::allow_all())
.await
.map(|file| {
Some(LoadResponse {
specifier: specifier.clone(),
content: Arc::new(file.source),
maybe_headers: file.maybe_headers,
})
});
(specifier.clone(), result)
}
.boxed_local()
} }
} }
@ -88,12 +102,21 @@ pub async fn print_docs(
let source_file = source_file.unwrap_or_else(|| "--builtin".to_string()); let source_file = source_file.unwrap_or_else(|| "--builtin".to_string());
let parse_result = if source_file == "--builtin" { let parse_result = if source_file == "--builtin" {
let loader = Box::new(StubDocLoader); let mut loader = StubDocLoader;
let doc_parser = doc::DocParser::new(loader, private); let source_file_specifier =
ModuleSpecifier::parse("deno://lib.deno.d.ts").unwrap();
let graph = create_graph(
source_file_specifier.clone(),
&mut loader,
None,
None,
None,
)
.await;
let doc_parser = doc::DocParser::new(graph, private);
let syntax = ast::get_syntax(&MediaType::Dts); let syntax = ast::get_syntax(&MediaType::Dts);
doc_parser.parse_source( doc_parser.parse_source(
"lib.deno.d.ts", &source_file_specifier,
syntax, syntax,
get_types(flags.unstable).as_str(), get_types(flags.unstable).as_str(),
) )
@ -109,31 +132,28 @@ pub async fn print_docs(
media_type: MediaType::TypeScript, media_type: MediaType::TypeScript,
source: format!("export * from \"{}\";", module_specifier), source: format!("export * from \"{}\";", module_specifier),
specifier: root_specifier.clone(), specifier: root_specifier.clone(),
maybe_headers: None,
}; };
// Save our fake file into file fetcher cache. // Save our fake file into file fetcher cache.
program_state.file_fetcher.insert_cached(root); program_state.file_fetcher.insert_cached(root);
let handler = Arc::new(Mutex::new(FetchHandler::new( let mut loader = DocLoader {
&program_state, program_state: program_state.clone(),
Permissions::allow_all(), };
Permissions::allow_all(), let resolver = DocResolver {
)?)); import_map: program_state.maybe_import_map.clone(),
let mut builder = module_graph::GraphBuilder::new( };
handler, let graph = create_graph(
program_state.maybe_import_map.clone(), root_specifier.clone(),
program_state.lockfile.clone(), &mut loader,
); Some(&resolver),
builder.add(&root_specifier, false).await?; None,
builder None,
.analyze_config_file(&program_state.maybe_config_file) )
.await?; .await;
let graph = builder.get_graph(); let doc_parser = doc::DocParser::new(graph, private);
doc_parser.parse_with_reexports(&root_specifier)
let doc_parser = doc::DocParser::new(Box::new(graph), private);
doc_parser
.parse_with_reexports(root_specifier.as_str())
.await
}; };
let mut doc_nodes = match parse_result { let mut doc_nodes = match parse_result {

View file

@ -239,8 +239,9 @@ impl LintReporter for PrettyLintReporter {
d.hint.as_ref(), d.hint.as_ref(),
&fmt_errors::format_location(&JsStackFrame::from_location( &fmt_errors::format_location(&JsStackFrame::from_location(
Some(d.filename.clone()), Some(d.filename.clone()),
Some(d.range.start.line as i64), Some(d.range.start.line_index as i64 + 1), // 1-indexed
Some(d.range.start.col as i64), // todo(#11111): make 1-indexed as well
Some(d.range.start.column_index as i64),
)), )),
); );
@ -277,24 +278,32 @@ pub fn format_diagnostic(
) -> String { ) -> String {
let mut lines = vec![]; let mut lines = vec![];
for i in range.start.line..=range.end.line { for (i, line) in source_lines
lines.push(source_lines[i - 1].to_string()); .iter()
if range.start.line == range.end.line { .enumerate()
.take(range.end.line_index + 1)
.skip(range.start.line_index)
{
lines.push(line.to_string());
if range.start.line_index == range.end.line_index {
lines.push(format!( lines.push(format!(
"{}{}", "{}{}",
" ".repeat(range.start.col), " ".repeat(range.start.column_index),
colors::red(&"^".repeat(range.end.col - range.start.col)) colors::red(
&"^".repeat(range.end.column_index - range.start.column_index)
)
)); ));
} else { } else {
let line_len = source_lines[i - 1].len(); let line_len = line.len();
if range.start.line == i { if range.start.line_index == i {
lines.push(format!( lines.push(format!(
"{}{}", "{}{}",
" ".repeat(range.start.col), " ".repeat(range.start.column_index),
colors::red(&"^".repeat(line_len - range.start.col)) colors::red(&"^".repeat(line_len - range.start.column_index))
)); ));
} else if range.end.line == i { } else if range.end.line_index == i {
lines.push(colors::red(&"^".repeat(range.end.col)).to_string()); lines
.push(colors::red(&"^".repeat(range.end.column_index)).to_string());
} else if line_len != 0 { } else if line_len != 0 {
lines.push(colors::red(&"^".repeat(line_len)).to_string()); lines.push(colors::red(&"^".repeat(line_len)).to_string());
} }
@ -363,9 +372,12 @@ fn sort_diagnostics(diagnostics: &mut Vec<LintDiagnostic>) {
let file_order = a.filename.cmp(&b.filename); let file_order = a.filename.cmp(&b.filename);
match file_order { match file_order {
Ordering::Equal => { Ordering::Equal => {
let line_order = a.range.start.line.cmp(&b.range.start.line); let line_order =
a.range.start.line_index.cmp(&b.range.start.line_index);
match line_order { match line_order {
Ordering::Equal => a.range.start.col.cmp(&b.range.start.col), Ordering::Equal => {
a.range.start.column_index.cmp(&b.range.start.column_index)
}
_ => line_order, _ => line_order,
} }
} }

View file

@ -262,6 +262,7 @@ async fn test_specifier(
media_type: MediaType::JavaScript, media_type: MediaType::JavaScript,
source: test_source.clone(), source: test_source.clone(),
specifier: test_specifier.clone(), specifier: test_specifier.clone(),
maybe_headers: None,
}; };
program_state.file_fetcher.insert_cached(test_file); program_state.file_fetcher.insert_cached(test_file);
@ -381,6 +382,7 @@ fn extract_files_from_regex_blocks(
media_type: file_media_type, media_type: file_media_type,
source: file_source, source: file_source,
specifier: file_specifier, specifier: file_specifier,
maybe_headers: None,
}) })
}) })
.collect(); .collect();
@ -757,9 +759,7 @@ async fn fetch_specifiers_with_test_mode(
.fetch(specifier, &mut Permissions::allow_all()) .fetch(specifier, &mut Permissions::allow_all())
.await?; .await?;
if file.media_type != MediaType::Unknown { if file.media_type == MediaType::Unknown {
*mode = TestMode::Both
} else {
*mode = TestMode::Documentation *mode = TestMode::Documentation
} }
} }

View file

@ -45,10 +45,6 @@ pub static DENO_CRYPTO_LIB: &str = include_str!(env!("DENO_CRYPTO_LIB_PATH"));
pub static DENO_BROADCAST_CHANNEL_LIB: &str = pub static DENO_BROADCAST_CHANNEL_LIB: &str =
include_str!(env!("DENO_BROADCAST_CHANNEL_LIB_PATH")); include_str!(env!("DENO_BROADCAST_CHANNEL_LIB_PATH"));
pub static DENO_NET_LIB: &str = include_str!(env!("DENO_NET_LIB_PATH")); pub static DENO_NET_LIB: &str = include_str!(env!("DENO_NET_LIB_PATH"));
pub static DENO_NET_UNSTABLE_LIB: &str =
include_str!(env!("DENO_NET_UNSTABLE_LIB_PATH"));
pub static DENO_HTTP_UNSTABLE_LIB: &str =
include_str!(env!("DENO_HTTP_UNSTABLE_LIB_PATH"));
pub static SHARED_GLOBALS_LIB: &str = pub static SHARED_GLOBALS_LIB: &str =
include_str!("dts/lib.deno.shared_globals.d.ts"); include_str!("dts/lib.deno.shared_globals.d.ts");
pub static WINDOW_LIB: &str = include_str!("dts/lib.deno.window.d.ts"); pub static WINDOW_LIB: &str = include_str!("dts/lib.deno.window.d.ts");

View file

@ -22,10 +22,10 @@ libc = "0.2.101"
log = "0.4.14" log = "0.4.14"
parking_lot = "0.11.1" parking_lot = "0.11.1"
pin-project = "1.0.7" pin-project = "1.0.7"
rusty_v8 = "0.26.0" rusty_v8 = "0.27.0"
serde = { version = "1.0.129", features = ["derive"] } serde = { version = "1.0.129", features = ["derive"] }
serde_json = { version = "1.0.66", features = ["preserve_order"] } serde_json = { version = "1.0.66", features = ["preserve_order"] }
serde_v8 = { version = "0.9.3" } serde_v8 = { version = "0.10.0" }
url = { version = "2.2.2", features = ["serde"] } url = { version = "2.2.2", features = ["serde"] }
[[example]] [[example]]

View file

@ -0,0 +1,27 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
//! This example shows you how to define ops in Rust and then call them from
//! JavaScript.
use deno_core::Extension;
use deno_core::JsRuntime;
use deno_core::RuntimeOptions;
fn main() {
let my_ext = Extension::builder()
.middleware(|name, opfn| match name {
"op_print" => deno_core::void_op_sync(),
_ => opfn,
})
.build();
// Initialize a runtime instance
let mut runtime = JsRuntime::new(RuntimeOptions {
extensions: vec![my_ext],
..Default::default()
});
// Deno.core.print() will now be a NOP
runtime
.execute_script("<usage>", r#"Deno.core.print("I'm broken")"#)
.unwrap();
}

View file

@ -79,6 +79,8 @@ pub use crate::ops_builtin::op_resources;
pub use crate::ops_json::op_async; pub use crate::ops_json::op_async;
pub use crate::ops_json::op_async_unref; pub use crate::ops_json::op_async_unref;
pub use crate::ops_json::op_sync; pub use crate::ops_json::op_sync;
pub use crate::ops_json::void_op_async;
pub use crate::ops_json::void_op_sync;
pub use crate::resources::Resource; pub use crate::resources::Resource;
pub use crate::resources::ResourceId; pub use crate::resources::ResourceId;
pub use crate::resources::ResourceTable; pub use crate::resources::ResourceTable;

View file

@ -11,6 +11,33 @@ use std::cell::RefCell;
use std::future::Future; use std::future::Future;
use std::rc::Rc; use std::rc::Rc;
/// A helper function that returns a sync NOP OpFn
///
/// It's mainly intended for embedders who want to disable ops, see ./examples/disable_ops.rs
pub fn void_op_sync() -> Box<OpFn> {
// TODO(@AaronO): use this simpler implementation after changing serde_v8 to allow all values
// to deserialize to the unit type instead of failing with `ExpectedNull`
// op_sync(|_, _: (), _: ()| Ok(()))
Box::new(move |state, _| -> Op {
let op_result = serialize_op_result(Ok(()), state);
Op::Sync(op_result)
})
}
/// A helper function that returns an async NOP OpFn
///
/// It's mainly intended for embedders who want to disable ops, see ./examples/disable_ops.rs
pub fn void_op_async() -> Box<OpFn> {
// TODO(@AaronO): use this simpler implementation after changing serde_v8 to allow all values
// to deserialize to the unit type instead of failing with `ExpectedNull`
// op_async(|_, _: (), _: ()| futures::future::ok(()))
Box::new(move |state, payload| -> Op {
let pid = payload.promise_id;
let op_result = serialize_op_result(Ok(()), state);
Op::Async(Box::pin(futures::future::ready((pid, op_result))))
})
}
/// Creates an op that passes data synchronously using JSON. /// Creates an op that passes data synchronously using JSON.
/// ///
/// The provided function `op_fn` has the following parameters: /// The provided function `op_fn` has the following parameters:

View file

@ -12,13 +12,18 @@
const core = window.Deno.core; const core = window.Deno.core;
const webidl = window.__bootstrap.webidl; const webidl = window.__bootstrap.webidl;
const { DOMException } = window.__bootstrap.domException; const { DOMException } = window.__bootstrap.domException;
const { atob, btoa } = window.__bootstrap.base64;
const { const {
ArrayPrototypeFind, ArrayPrototypeFind,
ArrayBufferIsView, ArrayPrototypeEvery,
ArrayPrototypeIncludes, ArrayPrototypeIncludes,
ArrayBuffer,
ArrayBufferIsView,
BigInt64Array, BigInt64Array,
StringPrototypeToUpperCase, StringPrototypeToUpperCase,
StringPrototypeReplace,
StringPrototypeCharCodeAt,
Symbol, Symbol,
SymbolFor, SymbolFor,
SymbolToStringTag, SymbolToStringTag,
@ -72,6 +77,10 @@
"RSA-PSS": "RsaHashedKeyGenParams", "RSA-PSS": "RsaHashedKeyGenParams",
"RSA-OAEP": "RsaHashedKeyGenParams", "RSA-OAEP": "RsaHashedKeyGenParams",
"ECDSA": "EcKeyGenParams", "ECDSA": "EcKeyGenParams",
"AES-CTR": "AesKeyGenParams",
"AES-CBC": "AesKeyGenParams",
"AES-GCM": "AesKeyGenParams",
"AES-KW": "AesKeyGenParams",
"HMAC": "HmacKeyGenParams", "HMAC": "HmacKeyGenParams",
}, },
"sign": { "sign": {
@ -100,6 +109,30 @@
}, },
}; };
// Decodes the unpadded base64 to the octet sequence containing key value `k` defined in RFC7518 Section 6.4
function decodeSymmetricKey(key) {
// Decode from base64url without `=` padding.
const base64 = StringPrototypeReplace(
StringPrototypeReplace(key, /\-/g, "+"),
/\_/g,
"/",
);
const decodedKey = atob(base64);
const keyLength = decodedKey.length;
const keyBytes = new Uint8Array(keyLength);
for (let i = 0; i < keyLength; i++) {
keyBytes[i] = StringPrototypeCharCodeAt(decodedKey, i);
}
return keyBytes;
}
function unpaddedBase64(bytes) {
const binaryString = core.decode(bytes);
const base64String = btoa(binaryString);
return StringPrototypeReplace(base64String, /=/g, "");
}
// See https://www.w3.org/TR/WebCryptoAPI/#dfn-normalize-an-algorithm // See https://www.w3.org/TR/WebCryptoAPI/#dfn-normalize-an-algorithm
// 18.4.4 // 18.4.4
function normalizeAlgorithm(algorithm, op) { function normalizeAlgorithm(algorithm, op) {
@ -631,7 +664,7 @@
prefix, prefix,
context: "Argument 1", context: "Argument 1",
}); });
keyData = webidl.converters.BufferSource(keyData, { keyData = webidl.converters["BufferSource or JsonWebKey"](keyData, {
prefix, prefix,
context: "Argument 2", context: "Argument 2",
}); });
@ -649,6 +682,8 @@
}); });
// 2. // 2.
if (format !== "jwk") {
if (ArrayBufferIsView(keyData) || keyData instanceof ArrayBuffer) {
if (ArrayBufferIsView(keyData)) { if (ArrayBufferIsView(keyData)) {
keyData = new Uint8Array( keyData = new Uint8Array(
keyData.buffer, keyData.buffer,
@ -659,12 +694,20 @@
keyData = new Uint8Array(keyData); keyData = new Uint8Array(keyData);
} }
keyData = TypedArrayPrototypeSlice(keyData); keyData = TypedArrayPrototypeSlice(keyData);
} else {
throw new TypeError("keyData is a JsonWebKey");
}
} else {
if (ArrayBufferIsView(keyData) || keyData instanceof ArrayBuffer) {
throw new TypeError("keyData is not a JsonWebKey");
}
}
const normalizedAlgorithm = normalizeAlgorithm(algorithm, "importKey"); const normalizedAlgorithm = normalizeAlgorithm(algorithm, "importKey");
switch (normalizedAlgorithm.name) { switch (normalizedAlgorithm.name) {
// https://w3c.github.io/webcrypto/#hmac-operations
case "HMAC": { case "HMAC": {
// 2.
if ( if (
ArrayPrototypeFind( ArrayPrototypeFind(
keyUsages, keyUsages,
@ -674,17 +717,140 @@
throw new DOMException("Invalid key usages", "SyntaxError"); throw new DOMException("Invalid key usages", "SyntaxError");
} }
// 3.
let hash;
let data;
// 4. https://w3c.github.io/webcrypto/#hmac-operations
switch (format) { switch (format) {
case "raw": { case "raw": {
const hash = normalizedAlgorithm.hash; data = keyData;
hash = normalizedAlgorithm.hash;
break;
}
case "jwk": {
// TODO(@littledivy): Why does the spec validate JWK twice?
const jwk = keyData;
// 2.
if (jwk.kty !== "oct") {
throw new DOMException(
"`kty` member of JsonWebKey must be `oct`",
"DataError",
);
}
// Section 6.4.1 of RFC7518
if (!jwk.k) {
throw new DOMException(
"`k` member of JsonWebKey must be present",
"DataError",
);
}
// 4.
data = decodeSymmetricKey(jwk.k);
// 5. // 5.
let length = keyData.byteLength * 8; hash = normalizedAlgorithm.hash;
// 6.
switch (hash.name) {
case "SHA-1": {
if (jwk.alg !== undefined && jwk.alg !== "HS1") {
throw new DOMException(
"`alg` member of JsonWebKey must be `HS1`",
"DataError",
);
}
break;
}
case "SHA-256": {
if (jwk.alg !== undefined && jwk.alg !== "HS256") {
throw new DOMException(
"`alg` member of JsonWebKey must be `HS256`",
"DataError",
);
}
break;
}
case "SHA-384": {
if (jwk.alg !== undefined && jwk.alg !== "HS384") {
throw new DOMException(
"`alg` member of JsonWebKey must be `HS384`",
"DataError",
);
}
break;
}
case "SHA-512": {
if (jwk.alg !== undefined && jwk.alg !== "HS512") {
throw new DOMException(
"`alg` member of JsonWebKey must be `HS512`",
"DataError",
);
}
break;
}
default:
throw new TypeError("unreachable");
}
// 7.
if (keyUsages.length > 0 && jwk.use && jwk.use !== "sign") {
throw new DOMException(
"`use` member of JsonWebKey must be `sign`",
"DataError",
);
}
// 8.
// Section 4.3 of RFC7517
if (jwk.key_ops) {
if (
ArrayPrototypeFind(
jwk.key_ops,
(u) => !ArrayPrototypeIncludes(recognisedUsages, u),
) !== undefined
) {
throw new DOMException(
"`key_ops` member of JsonWebKey is invalid",
"DataError",
);
}
if (
!ArrayPrototypeEvery(
jwk.key_ops,
(u) => ArrayPrototypeIncludes(keyUsages, u),
)
) {
throw new DOMException(
"`key_ops` member of JsonWebKey is invalid",
"DataError",
);
}
}
// 9.
if (jwk.ext === false && extractable == true) {
throw new DOMException(
"`ext` member of JsonWebKey is invalid",
"DataError",
);
}
break;
}
default:
throw new DOMException("Not implemented", "NotSupportedError");
}
// 5.
let length = data.byteLength * 8;
// 6. // 6.
if (length === 0) { if (length === 0) {
throw new DOMException("Key length is zero", "DataError"); throw new DOMException("Key length is zero", "DataError");
} }
if (normalizeAlgorithm.length) {
// 7. // 7.
if (normalizedAlgorithm.length !== undefined) {
if ( if (
normalizedAlgorithm.length > length || normalizedAlgorithm.length > length ||
normalizedAlgorithm.length <= (length - 8) normalizedAlgorithm.length <= (length - 8)
@ -694,7 +860,7 @@
"DataError", "DataError",
); );
} }
length = normalizeAlgorithm.length; length = normalizedAlgorithm.length;
} }
if (keyUsages.length == 0) { if (keyUsages.length == 0) {
@ -704,7 +870,7 @@
const handle = {}; const handle = {};
WeakMapPrototypeSet(KEY_STORE, handle, { WeakMapPrototypeSet(KEY_STORE, handle, {
type: "raw", type: "raw",
data: keyData, data,
}); });
const algorithm = { const algorithm = {
@ -723,11 +889,6 @@
return key; return key;
} }
// TODO(@littledivy): jwk
default:
throw new DOMException("Not implemented", "NotSupportedError");
}
}
// TODO(@littledivy): RSASSA-PKCS1-v1_5 // TODO(@littledivy): RSASSA-PKCS1-v1_5
// TODO(@littledivy): RSA-PSS // TODO(@littledivy): RSA-PSS
// TODO(@littledivy): ECDSA // TODO(@littledivy): ECDSA
@ -820,10 +981,48 @@
// 4-5. // 4-5.
return bits.buffer; return bits.buffer;
} }
// TODO(@littledivy): jwk case "jwk": {
// 1-3.
const jwk = {
kty: "oct",
k: unpaddedBase64(innerKey.data),
};
// 4.
const algorithm = key[_algorithm];
// 5.
const hash = algorithm.hash;
// 6.
switch (hash.name) {
case "SHA-1":
jwk.alg = "HS1";
break;
case "SHA-256":
jwk.alg = "HS256";
break;
case "SHA-384":
jwk.alg = "HS384";
break;
case "SHA-512":
jwk.alg = "HS512";
break;
default:
throw new DOMException(
"Hash algorithm not supported",
"NotSupportedError",
);
}
// 7.
jwk.key_ops = key.usages;
// 8.
jwk.ext = key[_extractable];
// 9.
return jwk;
}
default: default:
throw new DOMException("Not implemented", "NotSupportedError"); throw new DOMException("Not implemented", "NotSupportedError");
} }
// TODO(@littledivy): Redundant break but deno_lint complains without it
break;
} }
// TODO(@littledivy): RSASSA-PKCS1-v1_5 // TODO(@littledivy): RSASSA-PKCS1-v1_5
// TODO(@littledivy): RSA-PSS // TODO(@littledivy): RSA-PSS
@ -1220,10 +1419,40 @@
return { publicKey, privateKey }; return { publicKey, privateKey };
} }
// TODO(lucacasonato): ECDH // TODO(lucacasonato): ECDH
// TODO(lucacasonato): AES-CTR case "AES-CTR":
// TODO(lucacasonato): AES-CBC case "AES-CBC":
// TODO(lucacasonato): AES-GCM case "AES-GCM": {
// TODO(lucacasonato): AES-KW // 1.
if (
ArrayPrototypeFind(
usages,
(u) =>
!ArrayPrototypeIncludes([
"encrypt",
"decrypt",
"wrapKey",
"unwrapKey",
], u),
) !== undefined
) {
throw new DOMException("Invalid key usages", "SyntaxError");
}
return generateKeyAES(normalizedAlgorithm, extractable, usages);
}
case "AES-KW": {
// 1.
if (
ArrayPrototypeFind(
usages,
(u) => !ArrayPrototypeIncludes(["wrapKey", "unwrapKey"], u),
) !== undefined
) {
throw new DOMException("Invalid key usages", "SyntaxError");
}
return generateKeyAES(normalizedAlgorithm, extractable, usages);
}
case "HMAC": { case "HMAC": {
// 1. // 1.
if ( if (
@ -1278,6 +1507,42 @@
} }
} }
async function generateKeyAES(normalizedAlgorithm, extractable, usages) {
// 2.
if (!ArrayPrototypeIncludes([128, 192, 256], normalizedAlgorithm.length)) {
throw new DOMException("Invalid key length", "OperationError");
}
// 3.
const keyData = await core.opAsync("op_crypto_generate_key", {
name: normalizedAlgorithm.name,
length: normalizedAlgorithm.length,
});
const handle = {};
WeakMapPrototypeSet(KEY_STORE, handle, {
type: "raw",
data: keyData,
});
// 6-8.
const algorithm = {
name: normalizedAlgorithm.name,
length: normalizedAlgorithm.length,
};
// 9-11.
const key = constructKey(
"secret",
extractable,
usages,
algorithm,
handle,
);
// 12.
return key;
}
async function deriveBits(normalizedAlgorithm, baseKey, length) { async function deriveBits(normalizedAlgorithm, baseKey, length) {
switch (normalizedAlgorithm.name) { switch (normalizedAlgorithm.name) {
case "PBKDF2": { case "PBKDF2": {

View file

@ -9,6 +9,7 @@
((window) => { ((window) => {
const webidl = window.__bootstrap.webidl; const webidl = window.__bootstrap.webidl;
const { CryptoKey } = window.__bootstrap.crypto; const { CryptoKey } = window.__bootstrap.crypto;
const { ArrayBufferIsView, ArrayBuffer } = window.__bootstrap.primordials;
webidl.converters.AlgorithmIdentifier = (V, opts) => { webidl.converters.AlgorithmIdentifier = (V, opts) => {
// Union for (object or DOMString) // Union for (object or DOMString)
@ -18,6 +19,14 @@
return webidl.converters.DOMString(V, opts); return webidl.converters.DOMString(V, opts);
}; };
webidl.converters["BufferSource or JsonWebKey"] = (V, opts) => {
// Union for (BufferSource or JsonWebKey)
if (ArrayBufferIsView(V) || V instanceof ArrayBuffer) {
return webidl.converters.BufferSource(V, opts);
}
return webidl.converters.JsonWebKey(V, opts);
};
webidl.converters.KeyType = webidl.createEnumConverter("KeyType", [ webidl.converters.KeyType = webidl.createEnumConverter("KeyType", [
"public", "public",
"private", "private",
@ -108,6 +117,19 @@
webidl.converters.EcKeyGenParams = webidl webidl.converters.EcKeyGenParams = webidl
.createDictionaryConverter("EcKeyGenParams", dictEcKeyGenParams); .createDictionaryConverter("EcKeyGenParams", dictEcKeyGenParams);
const dictAesKeyGenParams = [
...dictAlgorithm,
{
key: "length",
converter: (V, opts) =>
webidl.converters["unsigned short"](V, { ...opts, enforceRange: true }),
required: true,
},
];
webidl.converters.AesKeyGenParams = webidl
.createDictionaryConverter("AesKeyGenParams", dictAesKeyGenParams);
const dictHmacKeyGenParams = [ const dictHmacKeyGenParams = [
...dictAlgorithm, ...dictAlgorithm,
{ {
@ -178,6 +200,115 @@
webidl.converters.HmacImportParams = webidl webidl.converters.HmacImportParams = webidl
.createDictionaryConverter("HmacImportParams", dictHmacImportParams); .createDictionaryConverter("HmacImportParams", dictHmacImportParams);
const dictRsaOtherPrimesInfo = [
{
key: "r",
converter: webidl.converters["DOMString"],
},
{
key: "d",
converter: webidl.converters["DOMString"],
},
{
key: "t",
converter: webidl.converters["DOMString"],
},
];
webidl.converters.RsaOtherPrimesInfo = webidl.createDictionaryConverter(
"RsaOtherPrimesInfo",
dictRsaOtherPrimesInfo,
);
webidl.converters["sequence<RsaOtherPrimesInfo>"] = webidl
.createSequenceConverter(
webidl.converters.RsaOtherPrimesInfo,
);
const dictJsonWebKey = [
// Sections 4.2 and 4.3 of RFC7517.
// https://datatracker.ietf.org/doc/html/rfc7517#section-4
{
key: "kty",
converter: webidl.converters["DOMString"],
},
{
key: "use",
converter: webidl.converters["DOMString"],
},
{
key: "key_ops",
converter: webidl.converters["sequence<DOMString>"],
},
{
key: "alg",
converter: webidl.converters["DOMString"],
},
// JSON Web Key Parameters Registration
{
key: "ext",
converter: webidl.converters["boolean"],
},
// Section 6 of RFC7518 JSON Web Algorithms
// https://datatracker.ietf.org/doc/html/rfc7518#section-6
{
key: "crv",
converter: webidl.converters["DOMString"],
},
{
key: "x",
converter: webidl.converters["DOMString"],
},
{
key: "y",
converter: webidl.converters["DOMString"],
},
{
key: "d",
converter: webidl.converters["DOMString"],
},
{
key: "n",
converter: webidl.converters["DOMString"],
},
{
key: "e",
converter: webidl.converters["DOMString"],
},
{
key: "p",
converter: webidl.converters["DOMString"],
},
{
key: "q",
converter: webidl.converters["DOMString"],
},
{
key: "dp",
converter: webidl.converters["DOMString"],
},
{
key: "dq",
converter: webidl.converters["DOMString"],
},
{
key: "qi",
converter: webidl.converters["DOMString"],
},
{
key: "oth",
converter: webidl.converters["sequence<RsaOtherPrimesInfo>"],
},
{
key: "k",
converter: webidl.converters["DOMString"],
},
];
webidl.converters.JsonWebKey = webidl.createDictionaryConverter(
"JsonWebKey",
dictJsonWebKey,
);
const dictPbkdf2Params = [ const dictPbkdf2Params = [
...dictAlgorithm, ...dictAlgorithm,
{ {

View file

@ -25,9 +25,37 @@ type KeyUsage =
| "unwrapKey" | "unwrapKey"
| "verify" | "verify"
| "wrapKey"; | "wrapKey";
type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki";
type NamedCurve = string; type NamedCurve = string;
interface RsaOtherPrimesInfo {
d?: string;
r?: string;
t?: string;
}
interface JsonWebKey {
alg?: string;
crv?: string;
d?: string;
dp?: string;
dq?: string;
e?: string;
ext?: boolean;
k?: string;
// deno-lint-ignore camelcase
key_ops?: string[];
kty?: string;
n?: string;
oth?: RsaOtherPrimesInfo[];
p?: string;
q?: string;
qi?: string;
use?: string;
x?: string;
y?: string;
}
interface HmacKeyGenParams extends Algorithm { interface HmacKeyGenParams extends Algorithm {
hash: HashAlgorithmIdentifier; hash: HashAlgorithmIdentifier;
length?: number; length?: number;
@ -122,6 +150,13 @@ interface SubtleCrypto {
extractable: boolean, extractable: boolean,
keyUsages: KeyUsage[], keyUsages: KeyUsage[],
): Promise<CryptoKeyPair | CryptoKey>; ): Promise<CryptoKeyPair | CryptoKey>;
importKey(
format: "jwk",
keyData: JsonWebKey,
algorithm: AlgorithmIdentifier | HmacImportParams,
extractable: boolean,
keyUsages: KeyUsage[],
): Promise<CryptoKey>;
importKey( importKey(
format: "raw", format: "raw",
keyData: BufferSource, keyData: BufferSource,
@ -129,7 +164,11 @@ interface SubtleCrypto {
extractable: boolean, extractable: boolean,
keyUsages: KeyUsage[], keyUsages: KeyUsage[],
): Promise<CryptoKey>; ): Promise<CryptoKey>;
exportKey(format: "raw", key: CryptoKey): Promise<ArrayBuffer>; exportKey(format: "jwk", key: CryptoKey): Promise<JsonWebKey>;
exportKey(
format: Exclude<KeyFormat, "jwk">,
key: CryptoKey,
): Promise<ArrayBuffer>;
sign( sign(
algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams,
key: CryptoKey, key: CryptoKey,

View file

@ -180,6 +180,18 @@ pub async fn op_crypto_generate_key(
private_key private_key
} }
Algorithm::AesCtr
| Algorithm::AesCbc
| Algorithm::AesGcm
| Algorithm::AesKw => {
let length = args.length.ok_or_else(not_supported)?;
let mut key_data = vec![0u8; length];
let rng = RingRand::SystemRandom::new();
rng.fill(&mut key_data).map_err(|_| {
custom_error("DOMExceptionOperationError", "Key generation failed")
})?;
key_data
}
Algorithm::Hmac => { Algorithm::Hmac => {
let hash: HmacAlgorithm = args.hash.ok_or_else(not_supported)?.into(); let hash: HmacAlgorithm = args.hash.ok_or_else(not_supported)?.into();

View file

@ -1,4 +0,0 @@
# deno_http
This crate implements server-side HTTP based on primitives from the
[Fetch API](https://fetch.spec.whatwg.org/).

View file

@ -1,53 +0,0 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
declare namespace Deno {
export interface WebSocketUpgrade {
response: Response;
socket: WebSocket;
}
export interface UpgradeWebSocketOptions {
protocol?: string;
}
/** **UNSTABLE**: new API, yet to be vetted.
*
* Used to upgrade an incoming HTTP request to a WebSocket.
*
* Given a request, returns a pair of WebSocket and Response. The original
* request must be responded to with the returned response for the websocket
* upgrade to be successful.
*
* ```ts
* const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" });
* const httpConn = Deno.serveHttp(conn);
* const e = await httpConn.nextRequest();
* if (e) {
* const { socket, response } = Deno.upgradeWebSocket(e.request);
* socket.onopen = () => {
* socket.send("Hello World!");
* };
* socket.onmessage = (e) => {
* console.log(e.data);
* socket.close();
* };
* socket.onclose = () => console.log("WebSocket has been closed.");
* socket.onerror = (e) => console.error("WebSocket error:", e.message);
* e.respondWith(response);
* }
* ```
*
* If the request body is disturbed (read from) before the upgrade is
* completed, upgrading fails.
*
* This operation does not yet consume the request or open the websocket. This
* only happens once the returned response has been passed to `respondWith`.
*/
export function upgradeWebSocket(
request: Request,
options?: UpgradeWebSocketOptions,
): WebSocketUpgrade;
}

View file

@ -34,7 +34,6 @@ use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
use std::future::Future; use std::future::Future;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::PathBuf;
use std::pin::Pin; use std::pin::Pin;
use std::rc::Rc; use std::rc::Rc;
use std::task::Context; use std::task::Context;
@ -45,10 +44,6 @@ use tokio::io::AsyncWrite;
use tokio::sync::oneshot; use tokio::sync::oneshot;
use tokio_util::io::StreamReader; use tokio_util::io::StreamReader;
pub fn get_unstable_declaration() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_http.unstable.d.ts")
}
pub fn init() -> Extension { pub fn init() -> Extension {
Extension::builder() Extension::builder()
.js(include_js_files!( .js(include_js_files!(

View file

@ -1,258 +0,0 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
declare namespace Deno {
/** The type of the resource record.
* Only the listed types are supported currently. */
export type RecordType =
| "A"
| "AAAA"
| "ANAME"
| "CNAME"
| "MX"
| "PTR"
| "SRV"
| "TXT";
export interface ResolveDnsOptions {
/** The name server to be used for lookups.
* If not specified, defaults to the system configuration e.g. `/etc/resolv.conf` on Unix. */
nameServer?: {
/** The IP address of the name server */
ipAddr: string;
/** The port number the query will be sent to.
* If not specified, defaults to 53. */
port?: number;
};
}
/** If `resolveDns` is called with "MX" record type specified, it will return an array of this interface. */
export interface MXRecord {
preference: number;
exchange: string;
}
/** If `resolveDns` is called with "SRV" record type specified, it will return an array of this interface. */
export interface SRVRecord {
priority: number;
weight: number;
port: number;
target: string;
}
export function resolveDns(
query: string,
recordType: "A" | "AAAA" | "ANAME" | "CNAME" | "PTR",
options?: ResolveDnsOptions,
): Promise<string[]>;
export function resolveDns(
query: string,
recordType: "MX",
options?: ResolveDnsOptions,
): Promise<MXRecord[]>;
export function resolveDns(
query: string,
recordType: "SRV",
options?: ResolveDnsOptions,
): Promise<SRVRecord[]>;
export function resolveDns(
query: string,
recordType: "TXT",
options?: ResolveDnsOptions,
): Promise<string[][]>;
/** ** UNSTABLE**: new API, yet to be vetted.
*
* Performs DNS resolution against the given query, returning resolved records.
* Fails in the cases such as:
* - the query is in invalid format
* - the options have an invalid parameter, e.g. `nameServer.port` is beyond the range of 16-bit unsigned integer
* - timed out
*
* ```ts
* const a = await Deno.resolveDns("example.com", "A");
*
* const aaaa = await Deno.resolveDns("example.com", "AAAA", {
* nameServer: { ipAddr: "8.8.8.8", port: 1234 },
* });
* ```
*
* Requires `allow-net` permission.
*/
export function resolveDns(
query: string,
recordType: RecordType,
options?: ResolveDnsOptions,
): Promise<string[] | MXRecord[] | SRVRecord[] | string[][]>;
/** **UNSTABLE**: new API, yet to be vetted.
*
* A generic transport listener for message-oriented protocols. */
export interface DatagramConn extends AsyncIterable<[Uint8Array, Addr]> {
/** **UNSTABLE**: new API, yet to be vetted.
*
* Waits for and resolves to the next message to the `UDPConn`. */
receive(p?: Uint8Array): Promise<[Uint8Array, Addr]>;
/** UNSTABLE: new API, yet to be vetted.
*
* Sends a message to the target. */
send(p: Uint8Array, addr: Addr): Promise<number>;
/** UNSTABLE: new API, yet to be vetted.
*
* Close closes the socket. Any pending message promises will be rejected
* with errors. */
close(): void;
/** Return the address of the `UDPConn`. */
readonly addr: Addr;
[Symbol.asyncIterator](): AsyncIterableIterator<[Uint8Array, Addr]>;
}
export interface UnixListenOptions {
/** A Path to the Unix Socket. */
path: string;
}
/** **UNSTABLE**: new API, yet to be vetted.
*
* Listen announces on the local transport address.
*
* ```ts
* const listener = Deno.listen({ path: "/foo/bar.sock", transport: "unix" })
* ```
*
* Requires `allow-read` and `allow-write` permission. */
export function listen(
options: UnixListenOptions & { transport: "unix" },
): Listener;
/** **UNSTABLE**: new API, yet to be vetted
*
* Listen announces on the local transport address.
*
* ```ts
* const listener1 = Deno.listenDatagram({
* port: 80,
* transport: "udp"
* });
* const listener2 = Deno.listenDatagram({
* hostname: "golang.org",
* port: 80,
* transport: "udp"
* });
* ```
*
* Requires `allow-net` permission. */
export function listenDatagram(
options: ListenOptions & { transport: "udp" },
): DatagramConn;
/** **UNSTABLE**: new API, yet to be vetted
*
* Listen announces on the local transport address.
*
* ```ts
* const listener = Deno.listenDatagram({
* path: "/foo/bar.sock",
* transport: "unixpacket"
* });
* ```
*
* Requires `allow-read` and `allow-write` permission. */
export function listenDatagram(
options: UnixListenOptions & { transport: "unixpacket" },
): DatagramConn;
export interface UnixConnectOptions {
transport: "unix";
path: string;
}
/** **UNSTABLE**: The unix socket transport is unstable as a new API yet to
* be vetted. The TCP transport is considered stable.
*
* Connects to the hostname (default is "127.0.0.1") and port on the named
* transport (default is "tcp"), and resolves to the connection (`Conn`).
*
* ```ts
* const conn1 = await Deno.connect({ port: 80 });
* const conn2 = await Deno.connect({ hostname: "192.0.2.1", port: 80 });
* const conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
* const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
* const conn5 = await Deno.connect({ path: "/foo/bar.sock", transport: "unix" });
* ```
*
* Requires `allow-net` permission for "tcp" and `allow-read` for "unix". */
export function connect(
options: ConnectOptions | UnixConnectOptions,
): Promise<Conn>;
export interface ConnectTlsClientCertOptions {
/** PEM formatted client certificate chain. */
certChain: string;
/** PEM formatted (RSA or PKCS8) private key of client certificate. */
privateKey: string;
}
/** **UNSTABLE** New API, yet to be vetted.
*
* Create a TLS connection with an attached client certificate.
*
* ```ts
* const conn = await Deno.connectTls({
* hostname: "deno.land",
* port: 443,
* certChain: "---- BEGIN CERTIFICATE ----\n ...",
* privateKey: "---- BEGIN PRIVATE KEY ----\n ...",
* });
* ```
*
* Requires `allow-net` permission.
*/
export function connectTls(
options: ConnectTlsOptions & ConnectTlsClientCertOptions,
): Promise<Conn>;
export interface StartTlsOptions {
/** A literal IP address or host name that can be resolved to an IP address.
* If not specified, defaults to `127.0.0.1`. */
hostname?: string;
/** Server certificate file. */
certFile?: string;
}
/** **UNSTABLE**: new API, yet to be vetted.
*
* Start TLS handshake from an existing connection using
* an optional cert file, hostname (default is "127.0.0.1"). The
* cert file is optional and if not included Mozilla's root certificates will
* be used (see also https://github.com/ctz/webpki-roots for specifics)
* Using this function requires that the other end of the connection is
* prepared for TLS handshake.
*
* ```ts
* const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" });
* const tlsConn = await Deno.startTls(conn, { certFile: "./certs/my_custom_root_CA.pem", hostname: "localhost" });
* ```
*
* Requires `allow-net` permission.
*/
export function startTls(
conn: Conn,
options?: StartTlsOptions,
): Promise<Conn>;
export interface ListenTlsOptions {
/** **UNSTABLE**: new API, yet to be vetted.
*
* Application-Layer Protocol Negotiation (ALPN) protocols to announce to
* the client. If not specified, no ALPN extension will be included in the
* TLS handshake.
*/
alpnProtocols?: string[];
}
}

View file

@ -85,10 +85,6 @@ pub fn get_declaration() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_net.d.ts") PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_net.d.ts")
} }
pub fn get_unstable_declaration() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_net.unstable.d.ts")
}
#[derive(Clone)] #[derive(Clone)]
pub struct DefaultTlsOptions { pub struct DefaultTlsOptions {
pub root_cert_store: Option<RootCertStore>, pub root_cert_store: Option<RootCertStore>,

View file

@ -140,17 +140,15 @@ fn get_hyper_error_class(_error: &hyper::Error) -> &'static str {
fn get_nix_error_class(error: &nix::Error) -> &'static str { fn get_nix_error_class(error: &nix::Error) -> &'static str {
use nix::errno::Errno::*; use nix::errno::Errno::*;
match error { match error {
nix::Error::Sys(ECHILD) => "NotFound", nix::Error::ECHILD => "NotFound",
nix::Error::Sys(EINVAL) => "TypeError", nix::Error::EINVAL => "TypeError",
nix::Error::Sys(ENOENT) => "NotFound", nix::Error::ENOENT => "NotFound",
nix::Error::Sys(ENOTTY) => "BadResource", nix::Error::ENOTTY => "BadResource",
nix::Error::Sys(EPERM) => "PermissionDenied", nix::Error::EPERM => "PermissionDenied",
nix::Error::Sys(ESRCH) => "NotFound", nix::Error::ESRCH => "NotFound",
nix::Error::Sys(UnknownErrno) => "Error", nix::Error::Sys::UnknownErrno => "Error",
nix::Error::Sys(_) => "Error", nix::Error::ENOTSUP => unreachable!(),
nix::Error::InvalidPath => "TypeError", _ => "Error",
nix::Error::InvalidUtf8 => "InvalidData",
nix::Error::UnsupportedOperation => unreachable!(),
} }
} }

View file

@ -3,7 +3,6 @@
((window) => { ((window) => {
const { const {
ObjectDefineProperty,
StringPrototypeReplace, StringPrototypeReplace,
TypeError, TypeError,
Promise, Promise,
@ -55,18 +54,6 @@
return promise; return promise;
} }
function immutableDefine(
o,
p,
value,
) {
ObjectDefineProperty(o, p, {
value,
configurable: false,
writable: false,
});
}
// Keep in sync with `fromFileUrl()` in `std/path/win32.ts`. // Keep in sync with `fromFileUrl()` in `std/path/win32.ts`.
function pathFromURLWin32(url) { function pathFromURLWin32(url) {
let p = StringPrototypeReplace( let p = StringPrototypeReplace(
@ -164,7 +151,6 @@
createResolvable, createResolvable,
assert, assert,
AssertionError, AssertionError,
immutableDefine,
pathFromURL, pathFromURL,
writable, writable,
nonEnumerable, nonEnumerable,

View file

@ -695,8 +695,7 @@ delete Object.prototype.__proto__;
}); });
// Setup `Deno` global - we're actually overriding already // Setup `Deno` global - we're actually overriding already
// existing global `Deno` with `Deno` namespace from "./deno.ts". // existing global `Deno` with `Deno` namespace from "./deno.ts".
util.immutableDefine(globalThis, "Deno", finalDenoNs); ObjectDefineProperty(globalThis, "Deno", util.readOnly(finalDenoNs));
ObjectFreeze(globalThis.Deno);
ObjectFreeze(globalThis.Deno.core); ObjectFreeze(globalThis.Deno.core);
signals.setSignals(); signals.setSignals();
} else { } else {

View file

@ -7,3 +7,5 @@ const workspace = await DenoWorkspace.load();
for (const crate of workspace.getDependencyCrates()) { for (const crate of workspace.getDependencyCrates()) {
await crate.increment("minor"); await crate.increment("minor");
} }
await workspace.updateLockFile();

View file

@ -13,6 +13,7 @@ const originalVersion = cliCrate.version;
// increment the version // increment the version
await cliCrate.increment(getVersionIncrement()); await cliCrate.increment(getVersionIncrement());
await workspace.updateLockFile();
// output the Releases.md markdown text // output the Releases.md markdown text
console.log( console.log(

View file

@ -33,10 +33,34 @@ export async function getMetadata(directory: string) {
return JSON.parse(result!) as CargoMetadata; return JSON.parse(result!) as CargoMetadata;
} }
export async function publishCrate(directory: string) { export function publishCrate(directory: string) {
return runCargoSubCommand({
directory,
args: ["publish"],
});
}
export function build(directory: string) {
return runCargoSubCommand({
directory,
args: ["build", "-vv"],
});
}
export function check(directory: string) {
return runCargoSubCommand({
directory,
args: ["check"],
});
}
async function runCargoSubCommand(params: {
args: string[];
directory: string;
}) {
const p = Deno.run({ const p = Deno.run({
cwd: directory, cwd: params.directory,
cmd: ["cargo", "publish"], cmd: ["cargo", ...params.args],
stderr: "inherit", stderr: "inherit",
stdout: "inherit", stdout: "inherit",
}); });

View file

@ -2,12 +2,7 @@
import * as path from "https://deno.land/std@0.105.0/path/mod.ts"; import * as path from "https://deno.land/std@0.105.0/path/mod.ts";
import * as semver from "https://deno.land/x/semver@v1.4.0/mod.ts"; import * as semver from "https://deno.land/x/semver@v1.4.0/mod.ts";
import { import * as cargo from "./cargo.ts";
CargoMetadata,
CargoPackageMetadata,
getMetadata,
publishCrate,
} from "./cargo.ts";
import { getCratesIoMetadata } from "./crates_io.ts"; import { getCratesIoMetadata } from "./crates_io.ts";
import { withRetries } from "./helpers.ts"; import { withRetries } from "./helpers.ts";
@ -21,10 +16,12 @@ export class DenoWorkspace {
} }
static async load(): Promise<DenoWorkspace> { static async load(): Promise<DenoWorkspace> {
return new DenoWorkspace(await getMetadata(DenoWorkspace.rootDirPath)); return new DenoWorkspace(
await cargo.getMetadata(DenoWorkspace.rootDirPath),
);
} }
private constructor(metadata: CargoMetadata) { private constructor(metadata: cargo.CargoMetadata) {
const crates = []; const crates = [];
for (const memberId of metadata.workspace_members) { for (const memberId of metadata.workspace_members) {
const pkg = metadata.packages.find((pkg) => pkg.id === memberId); const pkg = metadata.packages.find((pkg) => pkg.id === memberId);
@ -82,14 +79,22 @@ export class DenoWorkspace {
} }
return crate; return crate;
} }
build() {
return cargo.build(DenoWorkspace.rootDirPath);
}
updateLockFile() {
return cargo.check(DenoWorkspace.rootDirPath);
}
} }
export class DenoWorkspaceCrate { export class DenoWorkspaceCrate {
#workspace: DenoWorkspace; #workspace: DenoWorkspace;
#pkg: CargoPackageMetadata; #pkg: cargo.CargoPackageMetadata;
#isUpdatingManifest = false; #isUpdatingManifest = false;
constructor(workspace: DenoWorkspace, pkg: CargoPackageMetadata) { constructor(workspace: DenoWorkspace, pkg: cargo.CargoPackageMetadata) {
this.#workspace = workspace; this.#workspace = workspace;
this.#pkg = pkg; this.#pkg = pkg;
} }
@ -141,7 +146,7 @@ export class DenoWorkspaceCrate {
// times before failing hard. // times before failing hard.
return await withRetries({ return await withRetries({
action: async () => { action: async () => {
await publishCrate(this.directoryPath); await cargo.publishCrate(this.directoryPath);
return true; return true;
}, },
retryCount: 3, retryCount: 3,
@ -149,6 +154,14 @@ export class DenoWorkspaceCrate {
}); });
} }
build() {
return cargo.build(this.directoryPath);
}
updateLockFile() {
return cargo.check(this.directoryPath);
}
increment(part: "major" | "minor" | "patch") { increment(part: "major" | "minor" | "patch") {
const newVersion = semver.parse(this.version)!.inc(part).toString(); const newVersion = semver.parse(this.version)!.inc(part).toString();
return this.setVersion(newVersion); return this.setVersion(newVersion);

File diff suppressed because it is too large Load diff