pub(crate) mod api;
pub(crate) mod emit;
pub(crate) mod exec;
pub(crate) mod napi;
pub(crate) mod object;
pub(crate) mod value;
use napi::*;
use std::ffi::c_char;
use value::{Result, Thrown};
pub struct Instance {
bluetooth: std::sync::OnceLock<webbluetooth::Bluetooth>,
pub runtime: emit::Runtime,
}
impl Instance {
fn new() -> Self {
Self {
bluetooth: std::sync::OnceLock::new(),
runtime: emit::Runtime::new(),
}
}
pub fn bluetooth(&self) -> &webbluetooth::Bluetooth {
self.bluetooth.get_or_init(webbluetooth::Bluetooth::new)
}
}
unsafe fn args(env: napi_env, info: napi_callback_info, count: usize) -> Result<Vec<napi_value>> {
let mut argc = count;
let mut argv = vec![std::ptr::null_mut(); count];
value::ok(
unsafe {
napi_get_cb_info(
env,
info,
&mut argc,
argv.as_mut_ptr(),
std::ptr::null_mut(),
std::ptr::null_mut(),
)
},
"napi_get_cb_info",
)?;
Ok(argv)
}
unsafe extern "C" fn get_availability(env: napi_env, info: napi_callback_info) -> napi_value {
let instance = match unsafe { instance_from(env, info) } {
Ok(i) => i,
Err(e) => return value::throw(env, &e.0),
};
let bluetooth = instance.bluetooth().clone();
match instance
.runtime
.promise(env, async move { Ok(bluetooth.get_availability().await) })
{
Ok(promise) => promise,
Err(e) => value::throw(env, &e.0),
}
}
fn required(argv: &[napi_value], at: usize, what: &str) -> Result<napi_value> {
argv.get(at)
.copied()
.filter(|v| !v.is_null())
.ok_or_else(|| Thrown(format!("argument {} ({what}) is required", at + 1)))
}
unsafe fn request_options(
env: napi_env,
value: napi_value,
) -> Result<webbluetooth::RequestDeviceOptions> {
use webbluetooth::{DeviceFilter, RequestDeviceOptions};
let bad = |e: webbluetooth::Error| Thrown(e.to_string());
let mut options = RequestDeviceOptions::new();
let uuids = |env, list: napi_value| -> Result<Vec<String>> {
let mut len = 0;
value::ok(
unsafe { napi_get_array_length(env, list, &mut len) },
"array length",
)?;
let mut out = Vec::new();
for i in 0..len {
let mut item = std::ptr::null_mut();
value::ok(
unsafe { napi_get_element(env, list, i, &mut item) },
"array element",
)?;
out.push(value::as_string(env, item)?);
}
Ok(out)
};
if let Some(filters) = value::get(env, value, "filters")? {
let mut count = 0;
value::ok(
unsafe { napi_get_array_length(env, filters, &mut count) },
"filters length",
)?;
for i in 0..count {
let mut entry = std::ptr::null_mut();
value::ok(
unsafe { napi_get_element(env, filters, i, &mut entry) },
"filter",
)?;
let mut filter = DeviceFilter::new();
if let Some(services) = value::get(env, entry, "services")? {
filter = filter.services(uuids(env, services)?).map_err(bad)?;
}
if let Some(name) = value::get(env, entry, "name")? {
filter = filter.name(value::as_string(env, name)?);
}
if let Some(prefix) = value::get(env, entry, "namePrefix")? {
filter = filter.name_prefix(value::as_string(env, prefix)?);
}
options = options.filter(filter);
}
}
if let Some(optional) = value::get(env, value, "optionalServices")? {
options = options
.optional_services(uuids(env, optional)?)
.map_err(bad)?;
}
if let Some(all) = value::get(env, value, "acceptAllDevices")? {
if value::as_bool(env, all)? {
options = options.accept_all_devices();
}
}
Ok(options)
}
unsafe extern "C" fn request_device(env: napi_env, info: napi_callback_info) -> napi_value {
let result = (|| -> Result<napi_value> {
let instance = unsafe { instance_from(env, info) }?;
let argv = unsafe { args(env, info, 1) }?;
let options = unsafe { request_options(env, required(&argv, 0, "options")?) }?;
let bluetooth = instance.bluetooth().clone();
instance.runtime.promise_with(
env,
async move { bluetooth.request_device(options).await },
move |env, device| api::device_object(env, instance, device),
)
})();
match result {
Ok(promise) => promise,
Err(e) => value::throw(env, &e.0),
}
}
unsafe fn instance_from(env: napi_env, info: napi_callback_info) -> Result<&'static Instance> {
let mut argc = 0usize;
let mut data: *mut std::ffi::c_void = std::ptr::null_mut();
value::ok(
unsafe {
napi_get_cb_info(
env,
info,
&mut argc,
std::ptr::null_mut(),
std::ptr::null_mut(),
&mut data,
)
},
"napi_get_cb_info",
)?;
if data.is_null() {
return Err(Thrown("the module state is missing".into()));
}
Ok(unsafe { &*(data as *const Instance) })
}
fn method(
name: &'static std::ffi::CStr,
callback: napi_callback,
data: *mut std::ffi::c_void,
) -> napi_property_descriptor {
napi_property_descriptor {
utf8name: name.as_ptr() as *const c_char,
name: std::ptr::null_mut(),
method: Some(callback),
getter: None,
setter: None,
value: std::ptr::null_mut(),
attributes: 1 | 2 | 4,
data,
}
}
#[no_mangle]
pub unsafe extern "C" fn napi_register_module_v1(env: napi_env, exports: napi_value) -> napi_value {
let instance: &'static Instance = Box::leak(Box::new(Instance::new()));
let data = instance as *const Instance as *mut std::ffi::c_void;
let methods = [
method(c"getAvailability", get_availability, data),
method(c"requestDevice", request_device, data),
];
if value::ok(
unsafe { napi_define_properties(env, exports, methods.len(), methods.as_ptr()) },
"napi_define_properties",
)
.is_err()
{
return value::throw(env, "could not install the module's exports");
}
exports
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_registration_symbol_is_the_one_node_looks_up() {
let _entry: unsafe extern "C" fn(napi_env, napi_value) -> napi_value =
napi_register_module_v1;
}
#[test]
fn an_export_is_an_ordinary_enumerable_property() {
let d = method(c"getAvailability", get_availability, std::ptr::null_mut());
const ENUMERABLE: i32 = 2;
assert_eq!(
d.attributes & ENUMERABLE,
ENUMERABLE,
"exports must show up in Object.keys()"
);
}
#[test]
fn a_method_descriptor_names_its_callback() {
let d = method(c"getAvailability", get_availability, std::ptr::null_mut());
assert!(d.method.is_some());
assert!(d.getter.is_none() && d.setter.is_none());
assert!(!d.utf8name.is_null());
}
}