1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
use deno_core::{serde_json, v8::GetPropertyNamesArgs};
use crate::{js_value::Function, Error, Module, ModuleHandle, Runtime, RuntimeOptions};
/// A wrapper type representing a runtime instance loaded with a single module
///
/// Exactly equivalent to [`Runtime::new`] followed by [`Runtime::load_module`]
///
/// Can also be created using the [`crate::import`] function
pub struct ModuleWrapper {
module_context: ModuleHandle,
runtime: Runtime,
}
impl ModuleWrapper {
/// Creates a new `ModuleWrapper` from a given module and runtime options.
///
/// # Arguments
/// * `module` - A reference to the module to load.
/// * `options` - The runtime options for the module.
///
/// # Returns
/// A `Result` containing `Self` on success or an `Error` on failure.
///
/// # Errors
/// Will return an error if module execution fails
pub fn new_from_module(module: &Module, options: RuntimeOptions) -> Result<Self, Error> {
let mut runtime = Runtime::new(options)?;
let module_context = runtime.load_module(module)?;
Ok(Self {
module_context,
runtime,
})
}
/// Creates a new `ModuleWrapper` from a file path and runtime options.
///
/// # Arguments
/// * `path` - The path to the module file.
/// * `options` - The runtime options for the module.
///
/// # Returns
/// A `Result` containing `Self` on success or an `Error` on failure.
///
/// # Errors
/// Will return an error if the file cannot be loaded, or if module execution fails
pub fn new_from_file(path: &str, options: RuntimeOptions) -> Result<Self, Error> {
let module = Module::load(path)?;
Self::new_from_module(&module, options)
}
/// Returns a reference to the module context.
#[must_use]
pub fn get_module_context(&self) -> &ModuleHandle {
&self.module_context
}
/// Returns a mutable reference to the underlying runtime.
pub fn get_runtime(&mut self) -> &mut Runtime {
&mut self.runtime
}
/// Retrieves a value from the module by name and deserializes it.
///
/// See [`Runtime::get_value`]
///
/// # Arguments
/// * `name` - The name of the value to retrieve.
///
/// # Returns
/// A `Result` containing the deserialized value of type `T` on success or an `Error` on failure.
///
/// # Errors
/// Will return an error if the value cannot be found, or deserialized into the given type
pub fn get<T>(&mut self, name: &str) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
self.runtime.get_value(Some(&self.module_context), name)
}
/// Retrieves a future resolving to a value from the module by name and deserializes it.
///
/// See [`Runtime::get_value_async`]
///
/// # Arguments
/// * `name` - The name of the value to retrieve.
///
/// # Returns
/// A `Result` containing the deserialized value of type `T` on success or an `Error` on failure.
///
/// # Errors
/// Will return an error if the value cannot be found, or deserialized into the given type
pub async fn get_async<T>(&mut self, name: &str) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
self.runtime
.get_value_async(Some(&self.module_context), name)
.await
}
/// Retrieves a value from the module by name and deserializes it.
///
/// Does not await promises or the event loop.
///
/// See [`Runtime::get_value_immediate`]
///
/// # Arguments
/// * `name` - The name of the value to retrieve.
///
/// # Returns
/// A `Result` containing the deserialized value of type `T` on success or an `Error` on failure.
///
/// # Errors
/// Will return an error if the value cannot be found, or deserialized into the given type
pub fn get_immediate<T>(&mut self, name: &str) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
self.runtime
.get_value_immediate(Some(&self.module_context), name)
}
/// Checks if a value in the module with the given name is callable as a JavaScript function.
///
/// # Arguments
/// * `name` - The name of the value to check for callability.
///
/// # Returns
/// `true` if the value is callable as a JavaScript function, `false` otherwise.
pub fn is_callable(&mut self, name: &str) -> bool {
let test = self.get::<Function>(name);
test.is_ok()
}
/// Calls a function in the module with the given name and arguments and deserializes the result.
///
/// See [`Runtime::call_function`]
///
/// # Arguments
/// * `name` - The name of the function to call.
/// * `args` - The arguments to pass to the function.
///
/// # Returns
/// A `Result` containing the deserialized result of type `T` on success or an `Error` on failure.
///
/// # Errors
/// Will return an error if the function cannot be called, if the function returns an error,
/// or if the function returns a value that cannot be deserialized into the given type
pub fn call<T>(&mut self, name: &str, args: &impl serde::ser::Serialize) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
self.runtime
.call_function(Some(&self.module_context), name, args)
}
/// Calls a function in the module with the given name and arguments and deserializes the result.
///
/// See [`Runtime::call_function_async`]
///
/// # Arguments
/// * `name` - The name of the function to call.
/// * `args` - The arguments to pass to the function.
///
/// # Returns
/// A `Result` containing the deserialized result of type `T` on success or an `Error` on failure.
///
/// # Errors
/// Will return an error if the function cannot be called, if the function returns an error,
/// or if the function returns a value that cannot be deserialized into the given type
pub async fn call_async(
&mut self,
name: &str,
args: &impl serde::ser::Serialize,
) -> Result<serde_json::Value, Error> {
self.runtime
.call_function_async(Some(&self.module_context), name, args)
.await
}
/// Calls a function in the module with the given name and arguments and deserializes the result.
/// Does not await promises or the event loop.
///
/// See [`Runtime::call_function_immediate`]
///
/// # Arguments
/// * `name` - The name of the function to call.
/// * `args` - The arguments to pass to the function.
///
/// # Returns
/// A `Result` containing the deserialized result of type `T` on success or an `Error` on failure.
///
/// # Errors
/// Will return an error if the function cannot be called, if the function returns an error,
/// or if the function returns a value that cannot be deserialized into the given type
pub fn call_immediate(
&mut self,
name: &str,
args: &impl serde::ser::Serialize,
) -> Result<serde_json::Value, Error> {
self.runtime
.call_function_immediate(Some(&self.module_context), name, args)
}
/// Calls a function using the module's runtime that was previously stored as a Function object
///
/// See [`Runtime::call_stored_function`]
///
/// # Arguments
/// * `function` - The Function to call.
/// * `args` - The arguments to pass to the function.
///
/// # Returns
/// A `Result` containing the deserialized result of type `T` on success or an `Error` on failure.
///
/// # Errors
/// Will return an error if the function cannot be called, if the function returns an error,
/// or if the function returns a value that cannot be deserialized into the given type
pub fn call_stored<T>(
&mut self,
function: &Function,
args: &impl serde::ser::Serialize,
) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
self.runtime
.call_stored_function(Some(&self.module_context), function, args)
}
/// Calls a function using the module's runtime that was previously stored as a Function object
///
/// See [`Runtime::call_stored_function_async`]
///
/// # Arguments
/// * `function` - The Function to call.
/// * `args` - The arguments to pass to the function.
///
/// # Returns
/// A `Result` containing the deserialized result of type `T` on success or an `Error` on failure.
///
/// # Errors
/// Will return an error if the function cannot be called, if the function returns an error,
/// or if the function returns a value that cannot be deserialized into the given type
pub async fn call_stored_async(
&mut self,
function: &Function,
args: &impl serde::ser::Serialize,
) -> Result<serde_json::Value, Error> {
self.runtime
.call_stored_function_async(Some(&self.module_context), function, args)
.await
}
/// Calls a function using the module's runtime that was previously stored as a Function object
///
/// Does not await promises or the event loop.
///
/// See [`Runtime::call_stored_function_immediate`]
///
/// # Arguments
/// * `function` - The Function to call.
/// * `args` - The arguments to pass to the function.
///
/// # Returns
/// A `Result` containing the deserialized result of type `T` on success or an `Error` on failure.
///
/// # Errors
/// Will return an error if the function cannot be called, if the function returns an error,
/// or if the function returns a value that cannot be deserialized into the given type
pub fn call_stored_immediate(
&mut self,
function: &Function,
args: &impl serde::ser::Serialize,
) -> Result<serde_json::Value, Error> {
self.runtime
.call_stored_function_immediate(Some(&self.module_context), function, args)
}
/// Retrieves the names of the module's exports.
/// (Keys that are not valid UTF-8, may not work as intended due to encoding issues)
///
/// # Returns
/// A `Vec` of `String` containing the names of the keys.
pub fn keys(&mut self) -> Vec<String> {
let mut keys: Vec<String> = Vec::new();
if let Ok(namespace) = self
.runtime
.deno_runtime()
.get_module_namespace(self.module_context.id())
{
let mut scope = self.runtime.deno_runtime().handle_scope();
let global = namespace.open(&mut scope);
if let Some(keys_obj) =
global.get_property_names(&mut scope, GetPropertyNamesArgs::default())
{
for i in 0..keys_obj.length() {
if let Ok(key_index) = deno_core::serde_v8::to_v8(&mut scope, i) {
if let Some(key_name_v8) = keys_obj.get(&mut scope, key_index) {
let name = key_name_v8.to_rust_string_lossy(&mut scope);
keys.push(name);
}
}
}
}
}
keys
}
}
#[cfg(test)]
mod test_runtime {
use super::*;
use crate::json_args;
#[test]
fn test_call() {
let module = Module::new(
"test.js",
"
console.log('test');
export const value = 3;
export function func() { return 4; }
",
);
let mut module = ModuleWrapper::new_from_module(&module, RuntimeOptions::default())
.expect("Could not create wrapper");
let value: usize = module
.call("func", json_args!())
.expect("Could not call function");
assert_eq!(4, value);
}
#[test]
fn test_get() {
let module = Module::new(
"test.js",
"
export const value = 3;
export function func() { return 4; }
",
);
let mut module = ModuleWrapper::new_from_module(&module, RuntimeOptions::default())
.expect("Could not create wrapper");
let value: usize = module.get("value").expect("Could not get value");
assert_eq!(3, value);
}
#[test]
fn test_callable() {
let module = Module::new(
"test.js",
"
export const value = 3;
export function func() { return 4; }
",
);
let mut module = ModuleWrapper::new_from_module(&module, RuntimeOptions::default())
.expect("Could not create wrapper");
assert!(module.is_callable("func"));
assert!(!module.is_callable("value"));
}
#[test]
fn test_keys() {
let module = Module::new(
"test.js",
"
export const value = 3;
export function func() { return 4; }
",
);
let mut module = ModuleWrapper::new_from_module(&module, RuntimeOptions::default())
.expect("Could not create wrapper");
let mut keys = module.keys();
assert_eq!(2, keys.len());
assert_eq!("value", keys.pop().unwrap());
assert_eq!("func", keys.pop().unwrap());
}
}