neon/
lib.rs

1//! The [Neon][neon] crate provides bindings for writing [Node.js addons][addons]
2//! (i.e., dynamically-loaded binary modules) with a safe and fast Rust API.
3//!
4//! ## Getting Started
5//!
6//! You can conveniently bootstrap a new Neon project with the Neon project
7//! generator. You don't need to install anything special on your machine as
8//! long as you have a [supported version of Node and Rust][supported] on
9//! your system.
10//!
11//! To start a new project, open a terminal in the directory where you would
12//! like to place the project, and run at the command prompt:
13//!
14//! ```text
15//! % npm init neon my-project
16//! ... answer the user prompts ...
17//! ✨ Created Neon project `my-project`. Happy 🦀 hacking! ✨
18//! ```
19//!
20//! where `my-project` can be any name you like for the project. This will
21//! run the Neon project generator, prompting you with a few questions and
22//! placing a simple but working Neon project in a subdirectory called
23//! `my-project` (or whatever name you chose).
24//!
25//! You can then install and build the project by changing into the project
26//! directory and running the standard Node installation command:
27//!
28//! ```text
29//! % cd my-project
30//! % npm install
31//! % node
32//! > require(".").hello()
33//! 'hello node'
34//! ```
35//!
36//! You can look in the project's generated `README.md` for more details on
37//! the project structure.
38//!
39//! ## Example
40//!
41//! The generated `src/lib.rs` contains a function annotated with the
42//! [`#[neon::main]`](main) attribute, marking it as the module's main entry
43//! point to be executed when the module is loaded. This function can have
44//! any name but is conventionally called `main`:
45//!
46//! ```no_run
47//! # mod example {
48//! # use neon::prelude::*;
49//! # fn hello(mut cx: FunctionContext) -> JsResult<JsString> {
50//! #    Ok(cx.string("hello node"))
51//! # }
52//! #[neon::main]
53//! fn main(mut cx: ModuleContext) -> NeonResult<()> {
54//!     cx.export_function("hello", hello)?;
55//!     Ok(())
56//! }
57//! # }
58//! ```
59//!
60//! The example code generated by `npm init neon` exports a single
61//! function via [`ModuleContext::export_function`](context::ModuleContext::export_function).
62//! The `hello` function is defined just above `main` in `src/lib.rs`:
63//!
64//! ```
65//! # use neon::prelude::*;
66//! #
67//! fn hello(mut cx: FunctionContext) -> JsResult<JsString> {
68//!     Ok(cx.string("hello node"))
69//! }
70//! ```
71//!
72//! The `hello` function takes a [`FunctionContext`](context::FunctionContext) and
73//! returns a JavaScript string. Because all Neon functions can potentially throw a
74//! JavaScript exception, the return type is wrapped in a [`JsResult`](result::JsResult).
75//!
76//! [neon]: https://www.neon-bindings.com/
77//! [addons]: https://nodejs.org/api/addons.html
78//! [supported]: https://github.com/neon-bindings/neon#platform-support
79#![cfg_attr(docsrs, feature(doc_cfg))]
80
81pub mod context;
82pub mod event;
83pub mod handle;
84pub mod meta;
85pub mod object;
86pub mod prelude;
87pub mod reflect;
88pub mod result;
89#[cfg(not(feature = "sys"))]
90mod sys;
91#[cfg(feature = "napi-6")]
92pub mod thread;
93// To use the #[aquamarine] attribute on the top-level neon::types module docs, we have to
94// use this hack so we can keep the module docs in a separate file.
95// See: https://github.com/mersinvald/aquamarine/issues/5#issuecomment-1168816499
96mod types_docs;
97mod types_impl;
98
99#[cfg(feature = "sys")]
100#[cfg_attr(docsrs, doc(cfg(feature = "sys")))]
101pub mod sys;
102
103pub use types_docs::exports as types;
104
105#[doc(hidden)]
106pub mod macro_internal;
107
108pub use neon_macros::*;
109
110#[cfg(feature = "napi-6")]
111mod lifecycle;
112
113#[cfg(feature = "napi-8")]
114static MODULE_TAG: once_cell::sync::Lazy<crate::sys::TypeTag> = once_cell::sync::Lazy::new(|| {
115    let mut lower = [0; std::mem::size_of::<u64>()];
116
117    // Generating a random module tag at runtime allows Neon builds to be reproducible. A few
118    //  alternativeswere considered:
119    // * Generating a random value at build time; this reduces runtime dependencies but, breaks
120    //   reproducible builds
121    // * A static random value; this solves the previous issues, but does not protect against ABI
122    //   differences across Neon and Rust versions
123    // * Calculating a variable from the environment (e.g. Rust version); this theoretically works
124    //   but, is complicated and error prone. This could be a future optimization.
125    getrandom::getrandom(&mut lower).expect("Failed to generate a Neon module type tag");
126
127    // We only use 64-bits of the available 128-bits. The rest is reserved for future versioning and
128    // expansion of implementation.
129    let lower = u64::from_ne_bytes(lower);
130
131    // Note: `upper` must be non-zero or `napi_check_object_type_tag` will always return false
132    // https://github.com/nodejs/node/blob/5fad0b93667ffc6e4def52996b9529ac99b26319/src/js_native_api_v8.cc#L2455
133    crate::sys::TypeTag { lower, upper: 1 }
134});
135
136#[test]
137#[ignore]
138fn feature_matrix() {
139    use std::{env, process::Command};
140
141    const EXTERNAL_BUFFERS: &str = "external-buffers";
142    const FUTURES: &str = "futures";
143    const NODE_API_VERSIONS: &[&str] = &[
144        "napi-1", "napi-2", "napi-3", "napi-4", "napi-5", "napi-6", "napi-7", "napi-8",
145    ];
146
147    // If the number of features in Neon grows, we can use `itertools` to generate permutations.
148    // https://docs.rs/itertools/latest/itertools/trait.Itertools.html#method.permutations
149    const FEATURES: &[&[&str]] = &[
150        &[],
151        &[EXTERNAL_BUFFERS],
152        &[FUTURES],
153        &[EXTERNAL_BUFFERS, FUTURES],
154    ];
155
156    let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
157
158    for features in FEATURES {
159        for version in NODE_API_VERSIONS.iter().map(|f| f.to_string()) {
160            let features = features.iter().fold(version, |f, s| f + "," + s);
161            let status = Command::new(&cargo)
162                .args(["check", "-p", "neon", "--features"])
163                .arg(features)
164                .spawn()
165                .unwrap()
166                .wait()
167                .unwrap();
168
169            assert!(status.success());
170        }
171    }
172}