napi/
lib.rs

1#![deny(clippy::all)]
2#![allow(non_upper_case_globals)]
3
4//! High level Node.js [N-API](https://nodejs.org/api/n-api.html) binding
5//!
6//! **napi-rs** provides minimal overhead to write N-API modules in `Rust`.
7//!
8//! ## Feature flags
9//!
10//! ### napi1 ~ napi10
11//!
12//! Because `Node.js` N-API has versions. So there are feature flags to choose what version of `N-API` you want to build for.
13//! For example, if you want build a library which can be used by `node@10.17.0`, you should choose the `napi5` or lower.
14//!
15//! The details of N-API versions and support matrix: [Node-API version matrix](https://nodejs.org/api/n-api.html#node-api-version-matrix)
16//!
17//! ### tokio_rt
18//! With `tokio_rt` feature, `napi-rs` provides a ***tokio runtime*** in an additional thread.
19//! And you can easily run tokio `future` in it and return `promise`.
20//!
21//! ```
22//! use futures::prelude::*;
23//! use napi::bindgen_prelude::*;
24//! use tokio;
25//!
26//! #[napi]
27//! pub fn tokio_readfile(js_filepath: String) -> Result<Buffer> {
28//!     ctx.env.spawn_future_with_callback(
29//!         tokio::fs::read(js_filepath)
30//!           .map(|v| v.map_err(|e| Error::new(Status::Unknown, format!("failed to read file, {}", e)))),
31//!         |_, data| data.into(),
32//!     )
33//! }
34//! ```
35//!
36//! ### latin1
37//!
38//! Decode latin1 string from JavaScript using [encoding_rs](https://docs.rs/encoding_rs).
39//!
40//! With this feature, you can use `JsString.as_latin1_string` function
41//!
42//! ### serde-json
43//!
44//! Enable Serialize/Deserialize data cross `JavaScript Object` and `Rust struct`.
45//!
46//! ```
47//! #[derive(Serialize, Debug, Deserialize)]
48//! struct AnObject {
49//!     a: u32,
50//!     b: Vec<f64>,
51//!     c: String,
52//! }
53//!
54//! #[napi]
55//! fn deserialize_from_js(arg0: JsUnknown) -> Result<JsUndefined> {
56//!     let de_serialized: AnObject = ctx.env.from_js_value(arg0)?;
57//!     ...
58//! }
59//!
60//! #[napi]
61//! fn serialize(env: Env) -> Result<JsUnknown> {
62//!     let value = AnyObject { a: 1, b: vec![0.1, 2.22], c: "hello" };
63//!     env.to_js_value(&value)
64//! }
65//! ```
66//!
67
68#[cfg(all(target_family = "wasm", not(feature = "noop"), feature = "napi3"))]
69#[link(wasm_import_module = "napi")]
70extern "C" {
71  fn napi_add_env_cleanup_hook(
72    env: sys::napi_env,
73    fun: Option<unsafe extern "C" fn(arg: *mut core::ffi::c_void)>,
74    arg: *mut core::ffi::c_void,
75  ) -> sys::napi_status;
76}
77
78#[cfg(feature = "napi8")]
79mod async_cleanup_hook;
80#[cfg(feature = "napi8")]
81pub use async_cleanup_hook::AsyncCleanupHook;
82mod async_work;
83mod bindgen_runtime;
84#[cfg(feature = "compat-mode")]
85mod call_context;
86#[cfg(feature = "napi3")]
87mod cleanup_env;
88mod env;
89mod error;
90mod js_values;
91mod status;
92mod task;
93#[cfg(all(feature = "tokio_rt", feature = "napi4"))]
94mod tokio_runtime;
95mod value_type;
96#[cfg(feature = "napi3")]
97pub use cleanup_env::CleanupEnvHook;
98#[cfg(feature = "napi4")]
99pub mod threadsafe_function;
100
101mod version;
102
103pub use napi_sys as sys;
104
105pub use async_work::AsyncWorkPromise;
106#[cfg(feature = "compat-mode")]
107pub use call_context::CallContext;
108
109pub use bindgen_runtime::iterator;
110pub use env::*;
111pub use error::*;
112pub use js_values::*;
113pub use status::Status;
114pub use task::{ScopedTask, Task};
115pub use value_type::*;
116pub use version::NodeVersion;
117#[cfg(feature = "serde-json")]
118#[macro_use]
119extern crate serde;
120
121pub type ContextlessResult<T> = Result<Option<T>>;
122
123#[doc(hidden)]
124#[macro_export(local_inner_macros)]
125macro_rules! type_of {
126  ($env:expr, $value:expr) => {{
127    let mut value_type = 0;
128    #[allow(unused_unsafe)]
129    check_status!(unsafe { $crate::sys::napi_typeof($env, $value, &mut value_type) })
130      .and_then(|_| Ok($crate::ValueType::from(value_type)))
131  }};
132}
133
134#[doc(hidden)]
135#[macro_export]
136macro_rules! assert_type_of {
137  ($env: expr, $value:expr, $value_ty: expr) => {
138    $crate::type_of!($env, $value).and_then(|received_type| {
139      if received_type == $value_ty {
140        Ok(())
141      } else {
142        Err($crate::Error::new(
143          $crate::Status::InvalidArg,
144          format!(
145            "Expect value to be {}, but received {}",
146            $value_ty, received_type
147          ),
148        ))
149      }
150    })
151  };
152}
153
154pub mod bindgen_prelude {
155  #[cfg(all(feature = "compat-mode", not(feature = "noop")))]
156  pub use crate::bindgen_runtime::register_module_exports;
157  #[cfg(feature = "tokio_rt")]
158  pub use crate::tokio_runtime::*;
159  pub use crate::{
160    assert_type_of, bindgen_runtime::*, check_pending_exception, check_status,
161    check_status_or_throw, error, error::*, sys, type_of, JsError, JsValue, Property,
162    PropertyAttributes, Result, Status, Task, ValueType,
163  };
164
165  // This function's signature must be kept in sync with the one in tokio_runtime.rs, otherwise napi
166  // will fail to compile without the `tokio_rt` feature.
167
168  /// If the feature `tokio_rt` has been enabled this will enter the runtime context and
169  /// then call the provided closure. Otherwise it will just call the provided closure.
170  #[cfg(not(all(feature = "tokio_rt", feature = "napi4")))]
171  pub fn within_runtime_if_available<F: FnOnce() -> T, T>(f: F) -> T {
172    f()
173  }
174}
175
176#[doc(hidden)]
177pub mod __private {
178  pub use crate::bindgen_runtime::{
179    get_class_constructor, iterator::create_iterator, register_class, ___CALL_FROM_FACTORY,
180  };
181
182  use crate::sys;
183
184  pub unsafe fn log_js_value<V: AsRef<[sys::napi_value]>>(
185    // `info`, `log`, `warning` or `error`
186    method: &str,
187    env: sys::napi_env,
188    values: V,
189  ) {
190    use std::ffi::CString;
191    use std::ptr;
192
193    let mut g = ptr::null_mut();
194    unsafe { sys::napi_get_global(env, &mut g) };
195    let mut console = ptr::null_mut();
196    let console_c_string = CString::new("console").unwrap();
197    let method_c_string = CString::new(method).unwrap();
198    unsafe { sys::napi_get_named_property(env, g, console_c_string.as_ptr(), &mut console) };
199    let mut method_js_fn = ptr::null_mut();
200    unsafe {
201      sys::napi_get_named_property(env, console, method_c_string.as_ptr(), &mut method_js_fn)
202    };
203    unsafe {
204      sys::napi_call_function(
205        env,
206        console,
207        method_js_fn,
208        values.as_ref().len(),
209        values.as_ref().as_ptr(),
210        ptr::null_mut(),
211      )
212    };
213  }
214}
215
216pub extern crate ctor;
217
218#[cfg(feature = "tokio_rt")]
219pub extern crate tokio;
220
221#[cfg(feature = "error_anyhow")]
222pub extern crate anyhow;
223
224#[cfg(feature = "web_stream")]
225pub extern crate futures_core;
226#[cfg(feature = "web_stream")]
227pub extern crate tokio_stream;