- Deno 1.8 Release Notes
- Original author: Deno official
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: Hoarfroster
- Proofread by zenblo
Today we officially released Deno 1.8.0. We added a number of new features to this release, while also improving its stability:
-
Experimental support for the WebGPU API: provides a path to accelerate machine learning using the GPU in Deno out of the box.
-
Built-in internationalization API enablement: All JS Intl apis now support out-of-the-box.
-
Improved coverage tools: Coverage tools now support output of reports in LCOV format.
-
The import mapping capability is now stable: we have published a rewrite of Web-compatible dependencies.
-
Support for importing private modules: Importing remote modules on your private server by using authentication tokens.
If you already have Deno installed, you can upgrade to version 1.8 directly by running the Deno upgrade command. If you are using Deno for the first time, you can obtain it as follows:
#Using Shell (macOS and Linux):
curl -fsSL https://deno.land/x/install/install.sh | sh
#Using PowerShell (Windows) :
iwr https://deno.land/x/install/install.ps1 -useb | iex
#Use the Homebrew (macOS) :
brew install deno
#Use the run (Windows) :
scoop install deno
# Using Chocolatey (Windows):
choco install deno
Copy the code
New features and changes
Experimental support for the WebGPU API
The WebGPU API provides developers with a lower-level, high-performance, cross-architecture way to write applications running on GPU hardware in JavaScript. It is a viable alternative to WebGL for Web applications, and while the final specification is not yet finalized, it is currently supported by Firefox, Chromium and Safari, as well as Deno.
With this API, we can access rendering and general GPU computing directly from inside Deno. Once we have the porting done and the functionality is stable and unmarked, this approach will give us portable access to GPU resources on the Web, servers, and developers’ devices.
Gpus allow developers to implement highly parallel numerical algorithms that are not limited to graphics rendering and gaming. The effective use of gpus in machine learning makes it possible to run more complex neural networks — what we call deep learning — using gpus more effectively. The rapid development of computer vision, translation, image generation, reinforcement learning and other aspects are all due to the effective use of GPU hardware.
Today, most neural networks are written in Python, and computing is moved to gpus. However, we believe that JavaScript (rather than Python) can also be used as an ideal language for expressing mathematical ideas if the proper infrastructure exists. The off-the-shelf WebGPU support we provide in Deno is a step in this direction. Our goal is to run Tensorflow.js on Deno with GPU acceleration. We expect this to happen in the coming weeks and months.
This is a basic example that demonstrates how to access a connected GPU device and read the name and supported functionality:
/ / use ` deno run - run unstable ` https://deno.land/posts/v1.8/webgpu_discover.ts
// Try to get an adapter from UserAgent
const adapter = await navigator.gpu.requestAdapter();
if (adapter) {
// Print some basic information about the adapter
console.log('Found adapter:${adapter.name}`);
const features = [...adapter.features.values()];
console.log('Supported functions:${features.join(",")}`);
} else {
console.error("No adapter found.");
}
Copy the code
Here is a small example of a GPU rendering shader rendering a red triangle on a simple green background:
$deno run --unstable --allow-write=output.png https://raw.githubusercontent.com/crowlKats/webgpu-examples/f3b979f57fd471b11a28c5b0c91d0447221ba77b/hello-triangle/mod. ts
Copy the code
Note the use of WebAssembly on the output PNG. For more information visit the GitHub repository: crowlKats/ WebGPU-Examples.
The final PR pull request was 15.5K lines of code, and it took us a full five months to review and merge into the warehouse. We are very grateful to crowlKats for leading the introduction of WebGPU in Deno. We would also like to thank all the contributors to the Deno WebGPU project for their wGPU and GFX-RS enhancements. We would also like to thank Kvark for his contribution to the WebGPu specification and for his leadership in the development of wGPU and GFX-RS projects, which exemplar WebGPu development.
ICU support
ICU support has been the second most requested feature in the Deno release library. We are pleased to announce that Deno V1.8 now provides full ICU support.
All ICU dependent JavaScript apis now correspond to browser apis.
Try this in a REPL:
$ denoDeno 1.8.0 exit using CTRL +d or close()> const d = new Date(Date.UTC(2020, 5, 26, 7, 0, 0));
undefined
> d.toLocaleString("de-DE", {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
});
"Freitag, 26. Juni 2020"
Copy the code
Improved coverage toolsdeno coverage
The release of the new Deno version expands our code coverage infrastructure with some powerful new features. The major change in this release is that the handling of code coverage is now divided into coverage collections and coverage reports.
Previously, code coverage was collected and reported in a single subcommand by specifying the –coverage flag when starting deno Test. Now, deno Test’s — Coverage flag brings in an argument to store the path of the directory where the collected configuration files are stored, the collection of code coverage. In step 2, we will now call Deno Coverage, whose path points to the directory where the code coverage configuration file is stored. This subcommand can either return a report directly from the console as a beautiful text output, or output an LCOV file (– lCOV flag) for tools like genhtml, coveralls. IO, or codecov.io.
In recent days, we have been testing this functionality on deno_std. For each commit, we upload coverage reports to Codecov.io, which we can then view in codecov.io. Adding this code is also simple, with only 10 lines of change in our GitHub Actions workflow configuration:
- name: Run tests
- run: deno test --unstable --allow-all
+ run: deno test --coverage=./cov --unstable --allow-all
+
+ - name: Generate lcov
+ run: deno coverage --unstable --lcov ./cov > cov.lcov
+
+ - name: Upload coverage
+ uses: codecov/codecov-action@v1
+ with:
+ name: The ${{ matrix.os ${{}} - matrix.deno }}
+ files: cov.lcov
Copy the code
To see an example of using coveralls. IO, just look at this repository: github.com/lucacasonat… .
The import mapping function is now stable
The import mapping feature was stable in Chrome version 89, and since then, we have updated the feature implementation to conform to the latest version of the specification and is now considered stable as well. This means that we no longer need to provide the — Unstable flag when using –import-map.
$ deno run --import-map=./import_map.json ./mod.ts
Copy the code
Also, the –import-map tag now supports not only local paths but also other hyperlinks, allowing us to import mappings from remote servers.
$ deno run --import-map=https://example.com/import_map.json ./mod.ts
Copy the code
The import mapping feature allows developers to use so-called “bare” specifiers instead of relative or absolute file paths or HTTP URL paths.
// Deno does not support such specifiers by default,
// But by providing a mapping, we can remap
// These empty specifiers go to other urls
import * as http from "std/http";
Copy the code
{
"imports": {
"std/http": "https://deno.land/[email protected]/http/mod.ts"}}Copy the code
Developers should note that import mappings cannot be combined: this means you can only provide one import mapping to deno Run or Deno Test. Because of this, authors of dependent libraries should still use regular, non-bare specifiers (relative or absolute file paths or HTTP URL paths), otherwise consumers of dependent libraries will need to manually add dependent libraries (and their dependencies) bare specifiers to their import maps.
A more useful feature of importing maps is the ability to remap regular specifiers to completely different specifiers. For example, if we have some fragmented dependencies nested in our module diagram, we can replace them with fixed versions before pinning them upstream. Or if we use a build process that adds a hash to a module file name, we can reference the file directly in the source code instead of the hash value, and only need to remap the specifier at run time using an imported map.
Refer to the specification for more examples and detailed instructions.
The Auth Token can be used to obtain modules
Not all code is publicly available on the public Internet. Previously, Deno could not download code from servers that required authentication. In this release, we added the ability for the user to specify each domain authentication token used when extracting the module for the first time.
To do this, the Deno CLI looks for an environment variable named DENO_AUTH_TOKENS to determine which authentication tokens should be considered when requesting a remote module. Values of environment variables are semicolons (;). Format of n separated tokens, where each token is in the format {token}@{hostname[:port]}.
For example, a single token would look like this:
[email protected]
Copy the code
Multiple tokens look like this:
[email protected]; [email protected]: 8080Copy the code
When Deno extracts remote modules whose host names match those of remote modules, Deno sets the requested Authorization headers as Bearer {token} values. This allows the remote server to understand that the request is an authorized request associated with a specific authorized user to provide access to specific resources and modules on the server.
Refer to the manual entry for more detailed usage instructions and instructions on configuring our environment to retrieve data from the private GitHub repository.
Deno.test
The Exit cleanup program
The deno.test API already has two cleaners that help us ensure that our code does not reveal operational secrets or resources, for example, that all open files or network requests are closed before the test code ends and that no more system calls are made.
Deno 1.8 adds a new cleaner to ensure that the code under test does not call deno.exit (). Rogue exit statements can indicate false positive test results and are often abused or forgotten to delete.
This cleaner is enabled for all tests by default, but can be turned off by setting sanitizeExit Boolean to false in the test definition:
Deno.test({
name: "false success".fn() {
Deno.exit(0);
},
sanitizeExit: false});// This test will not be run:
Deno.test({
name: "failing test".fn() {
throw new Error("this test fails"); }});Copy the code
You can try to run this code: deno test at https://deno.land/posts/v1.8/exit_sanitizer.ts.
Deno.permissions
The API is now in a stable state
Deno’s security model is permission-based. Currently, these permissions can only be granted when the application is started. This works in most cases, but in some cases, requesting or revoking permissions at run time leads to a better user experience.
In Deno 1.8, we now have a stable API for Query, Request, and REVOKE permissions. These apis are included in the deno.Permissions object. Here’s an example:
function homedir() {
try {
console.log('Your catalogue is:${Deno.env.get("HOME")}`);
} catch (err) {
console.log('Cannot get directory:${err}`); }}// Try to get the home directory (this operation will fail because you do not have permission for env yet).
homedir();
const {granted} = await Deno.permissions.request({name: "env"});
if (granted) {
console.log('You have been granted the "env" permission);
} else {
console.log('You have not been granted' env 'permission);
}
// Try to get the home directory (successful if user authorized)
homedir();
await Deno.permissions.revoke({name: "env"});
// Try to get the home directory (this operation will fail because permissions have been revoked)
homedir();
Copy the code
You can try to run the script: deno run https://deno.land/posts/v1.8/permission_api.ts.
Deno.link
和 Deno.symlink
The API is now in a stable state
The release also provides stable versions of four apis for symbolic links:
Deno.link
Deno.linkSync
Deno.symlink
Deno.symlinkSync
Before these apis can be stabilized, they pass a security assessment, and we need specific permissions to use them.
Deno.link and denO. linkSync require read and write permissions on source files and destination paths.
Deno.symlink and denO. symlinkSync require write permission on the destination path.
More detailedDeno.metrics
As Deno becomes more stable, it becomes increasingly important for developers to have an easy way to detect their applications. This starts at the lowest level (at the runtime itself). In Deno, all privileged operations in JS (those that go to Rust) are done through a single central interface between JS and Rust. We call requests through this interface OPS. For example, calling deno.open invokes the op_open_async operation on the privileged side, returning the resource ID (or error) of the open file.
More than two years ago, on October 11, 2018, we provided a way to look at metrics for all actions between Rust and JS: deno.metrics. The API currently exposes the number of synchronous and asynchronous operations started and completed, as well as the amount of data sent through the operation interface. So far, this has been limited to the combined data of all the different operations. There is no way to find out how many times an operation is called — only data for all operations.
When you run this code with — Unstable, this version adds a new field named ops to deno.metrics. This field contains information about each operation, how often the API is called and how much data is transferred through the API. This allows for more fine-grained detection of the runtime.
Here’s an example:
$ deno --unstableDeno 1.8.0 exit using CTRL +d or close()> Deno.metrics().ops["op_open_async"]
undefined
> await Deno.open("./README.md")
File {}
> Deno.metrics().ops["op_open_async"]
{
opsDispatched: 1,
opsDispatchedSync: 0,
opsDispatchedAsync: 1,
opsDispatchedAsyncUnref: 0,
opsCompleted: 1,
opsCompletedSync: 0,
opsCompletedAsync: 1,
opsCompletedAsyncUnref: 0,
bytesSentControl: 54,
bytesSentData: 0,
bytesReceived: 22
}
Copy the code
In an upcoming release, the asynchronous operation cleanup tool in deno.test will use this new information to provide more actionable errors when asynchronous operations are not completed before tests are completed. We have seen this feature used to detect applications and pipe data into monitoring software:
deno fmt
Support for JSON
Deno FMT can now format.json and.jsonc files, just like JS or TS files. The formatting tool will format both json and jsonc code from Markdown files.
Deno.emit
Support for IIFE bundles
The built-in bundle can now issue bundles in the immediate Function Expression (IIFE) format.
By default, the output format is still ESM, but users can change it by setting the emitoptions. bundle option to iife:
const {files} = await Deno.emit("/a.ts", {
bundle: "iife".sources: {
"/a.ts": `import { b } from "./b.ts"; console.log(b); `."/b.ts": `export const b = "b"; `,}});console.log(files["deno:///bundle.js"]);
Copy the code
The result is:
(function () {
const b = "b";
console.log(b);
return{}; }) ();Copy the code
You can run this: deno run – unstable https://deno.land/posts/v1.8/emit_iife.ts.
This is especially useful for creating bundles for older browsers that do not support ESM.
deno lsp
Now it’s in a steady state
Over the past few months, we’ve been working hard to update the old VS Code editor integration (Deno extension). The old extensions only worked with VS Code, and the types resolved did not always match those in the Deno CLI.
In Deno 1.6, we released Deno LSP — Deno’s built-in language server — in the Canary version. LSP enables us to provide editor integration from a single code base to all lSP-enabled editors. The built-in language server is based on the same architecture as the rest of the Deno CLI, and therefore provides the same TypeScript diagnostics as the rest of the CLI.
Two weeks ago, in Deno 1.7.5, we stabilized Deno LSP and switched our VS Code extension to use it. We have received good feedback so far and will work to resolve all reported issues. If you encounter problems with the extension, please report the problem to our problem tracker, after all, we can’t solve problems we don’t know about.
In addition to the official VS Code integration, we have also created more community integrations based on deno LSP:
- Vim with CoC: github.com/fannheyward…
- Neovim:github.com/neovim/nvim…
- Emacs: Emacs – LSP. Making. IO/LSP mode/pa…
- Kakoune: deno. Land/manual/gett…
- Sublime does: deno. Land/manual/gett…
TypeScript 4.2
Deno 1.8 comes bundled with the latest stable version of TypeScript.
For more information about the new features in Typescript 4.2, see Typescript 4.2
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.