diff --git a/core/examples/disable_ops.rs b/core/examples/disable_ops.rs new file mode 100644 index 0000000000..2d28908bf5 --- /dev/null +++ b/core/examples/disable_ops.rs @@ -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("", r#"Deno.core.print("I'm broken")"#) + .unwrap(); +} diff --git a/core/lib.rs b/core/lib.rs index a9f6d5d8bd..b190298846 100644 --- a/core/lib.rs +++ b/core/lib.rs @@ -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_unref; 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::ResourceId; pub use crate::resources::ResourceTable; diff --git a/core/ops_json.rs b/core/ops_json.rs index 25752322a1..22a84154da 100644 --- a/core/ops_json.rs +++ b/core/ops_json.rs @@ -11,6 +11,33 @@ use std::cell::RefCell; use std::future::Future; 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 { + // 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 { + // 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. /// /// The provided function `op_fn` has the following parameters: