This repository was archived by the owner on Apr 2, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
Docs & Example for "Roll Your Own JS Runtime" blog posts #824
Merged
Merged
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
6704512
Add docs for create_snapshot() and its options.
NfNitLoop 57b6971
Add an example for "Roll Your Own JS Runtime"
NfNitLoop b19e5ce
Add copyright headers.
NfNitLoop 52d61e4
Don't link to outdated blog post in rust docs.
NfNitLoop 41a2877
Check the output of the snapshot example from CI.
NfNitLoop 19e672c
Update core/examples/snapshot/README.md
devsnek 95f1036
Merge branch 'main' into ryo-js-snapshot
devsnek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| # Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. | ||
| # Note: Since Cargo "example" targets don't discover/use `build.rs` files, this | ||
| # example is a member of the root `deno_core` workspace. That means it will | ||
| # compile with `cargo build` in the root, so that this example/documentation | ||
| # stays in-sync with development. | ||
|
|
||
| [package] | ||
| name = "build-your-own-js-snapshot" | ||
| version = "0.1.0" | ||
| edition = "2021" | ||
| build = "build.rs" | ||
|
|
||
|
|
||
| [dependencies] | ||
| deno_core.workspace = true | ||
| tokio.workspace = true | ||
|
|
||
| [build-dependencies] | ||
| deno_core.workspace = true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| # Snapshot Example | ||
|
|
||
| This example roughly follows the blog post | ||
| [Roll Your Own JavaScript Runtime: Part 3][blog] to create a `JsRuntime` with an | ||
| embedded startup snapshot. | ||
|
|
||
| That blog post and the two that preceded it were no longer accurate. By | ||
| including this example in the repository, it will continually be built, so it | ||
| will hopefully stay up-to-date. | ||
|
|
||
|
devsnek marked this conversation as resolved.
|
||
| ## Differences | ||
|
|
||
| Differences from those blog posts: | ||
|
|
||
| - The `create_snapshot()` API has changed in various ways. | ||
| - New API features for extensions: | ||
| - `#[op2]` ([read more][op2]) | ||
| - `extension!(...)` macro replaces `Extension::builder()` | ||
| - ESM-based extensions. | ||
|
|
||
| Missing features vs. those blog posts: | ||
|
|
||
| - Does not implement [TsModuleLoader], to keep this example more concise. | ||
|
|
||
| [blog]: https://deno.com/blog/roll-your-own-javascript-runtime-pt3#creating-a-snapshot-in-buildrs | ||
| [op2]: https://github.com/denoland/deno_core/tree/main/ops/op2#readme | ||
| [TsModuleLoader]: https://deno.com/blog/roll-your-own-javascript-runtime-pt2#supporting-typescript | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. | ||
| use deno_core::{ | ||
| extension, | ||
| snapshot::{create_snapshot, CreateSnapshotOptions}, | ||
| }; | ||
| use std::path::PathBuf; | ||
| use std::{env, fs}; | ||
|
|
||
| fn main() { | ||
| extension!( | ||
| runjs_extension, | ||
| // Must specify an entrypoint so that our module gets loaded while snapshotting: | ||
| esm_entry_point = "my:runtime", | ||
| esm = [ | ||
| dir "src", | ||
| "my:runtime" = "runtime.js", | ||
| ], | ||
| ); | ||
|
|
||
| let options = CreateSnapshotOptions { | ||
| cargo_manifest_dir: env!("CARGO_MANIFEST_DIR"), | ||
| startup_snapshot: None, | ||
| extensions: vec![runjs_extension::init_ops_and_esm()], | ||
| with_runtime_cb: None, | ||
| skip_op_registration: false, | ||
| extension_transpiler: None, | ||
| }; | ||
| let warmup_script = None; | ||
|
|
||
| let snapshot = | ||
| create_snapshot(options, warmup_script).expect("Error creating snapshot"); | ||
|
|
||
| // Save the snapshot for use by our source code: | ||
| let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); | ||
| let file_path = out_dir.join("RUNJS_SNAPSHOT.bin"); | ||
| fs::write(file_path, snapshot.output).expect("Failed to write snapshot"); | ||
|
|
||
| // Let cargo know that builds depend on these files: | ||
| for path in snapshot.files_loaded_during_snapshot { | ||
| println!("cargo:rerun-if-changed={}", path.display()); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. | ||
| // Run this script with `cargo run`. | ||
|
|
||
| import { callRust } from "my:runtime"; | ||
|
|
||
| callRust("Hello from example.js"); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. | ||
| use std::{env::current_dir, rc::Rc}; | ||
|
|
||
| use deno_core::{ | ||
| error::AnyError, extension, op2, FsModuleLoader, JsRuntime, | ||
| PollEventLoopOptions, RuntimeOptions, | ||
| }; | ||
|
|
||
| fn main() { | ||
| let runtime = tokio::runtime::Builder::new_current_thread() | ||
| .enable_all() | ||
| .build() | ||
| .unwrap(); | ||
| if let Err(error) = runtime.block_on(run_js("./example.js")) { | ||
| eprintln!("error: {}", error); | ||
| } | ||
| } | ||
|
|
||
| #[op2(fast)] | ||
| fn op_call_rust(#[string] value: String) { | ||
| println!("Received this value from JS: {value}"); | ||
| } | ||
|
|
||
| extension!(runjs_extension, ops = [op_call_rust,],); | ||
|
|
||
| async fn run_js(file_path: &str) -> Result<(), AnyError> { | ||
| let cwd = current_dir()?; | ||
| let main_module = deno_core::resolve_path(file_path, &cwd)?; | ||
|
|
||
| let mut js_runtime = JsRuntime::new(RuntimeOptions { | ||
| module_loader: Some(Rc::new(FsModuleLoader)), | ||
| startup_snapshot: Some(RUNTIME_SNAPSHOT), | ||
| extensions: vec![runjs_extension::init_ops()], | ||
| ..Default::default() | ||
| }); | ||
|
|
||
| let mod_id = js_runtime.load_main_es_module(&main_module).await?; | ||
| let result = js_runtime.mod_evaluate(mod_id); | ||
| js_runtime | ||
| .run_event_loop(PollEventLoopOptions::default()) | ||
| .await?; | ||
| result.await | ||
| } | ||
|
|
||
| // Load the snapshot generated by build.rs: | ||
| static RUNTIME_SNAPSHOT: &[u8] = | ||
| include_bytes!(concat!(env!("OUT_DIR"), "/RUNJS_SNAPSHOT.bin")); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. | ||
| /** | ||
| * This module provides the JavaScript interface atop calls to the Rust ops. | ||
| */ | ||
|
|
||
| // Minimal example, just passes arguments through to Rust: | ||
| export function callRust(stringValue) { | ||
| const { op_call_rust } = Deno.core.ops; | ||
| op_call_rust(stringValue); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This was the only way I found to get this example crate to run
build.rs, which is required for generating the V8 Snapshot. But I'd be happy to learn that there's a better way.