Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(example): remove JsFunction from example #2123

Merged
merged 9 commits into from
May 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions examples/napi-compat-mode/src/env.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use napi::{
CallContext, ContextlessResult, Env, JsBoolean, JsFunction, JsObject, JsString, JsUndefined,
JsUnknown, Result,
bindgen_prelude::Function, CallContext, ContextlessResult, Env, JsBoolean, JsObject, JsString,
JsUndefined, JsUnknown, Result,
};

#[js_function(2)]
Expand Down Expand Up @@ -48,8 +48,8 @@ pub fn throw_syntax_error(ctx: CallContext) -> Result<JsUndefined> {
let syntax_error = ctx
.env
.get_global()?
.get_named_property::<JsFunction>("SyntaxError")?;
ctx.env.throw(syntax_error.new_instance(&[message])?)?;
.get_named_property::<Function<JsString>>("SyntaxError")?;
ctx.env.throw(syntax_error.new_instance(message)?)?;
ctx.env.get_undefined()
}

Expand Down
22 changes: 11 additions & 11 deletions examples/napi-compat-mode/src/function.rs
Original file line number Diff line number Diff line change
@@ -1,47 +1,47 @@
use napi::{
bindgen_prelude::Function, CallContext, JsError, JsFunction, JsNull, JsObject, JsUnknown, Result,
bindgen_prelude::Function, CallContext, JsError, JsNull, JsObject, JsString, JsUnknown, Result,
};

#[js_function(1)]
pub fn call_function(ctx: CallContext) -> Result<JsNull> {
let js_func = ctx.get::<JsFunction>(0)?;
let js_func = ctx.get::<Function<(JsUnknown, JsUnknown)>>(0)?;
let js_string_hello = ctx.env.create_string("hello".as_ref())?.into_unknown();
let js_string_world = ctx.env.create_string("world".as_ref())?.into_unknown();

js_func.call(None, &[js_string_hello, js_string_world])?;
js_func.call((js_string_hello, js_string_world))?;

ctx.env.get_null()
}

#[js_function(1)]
pub fn call_function_with_ref_arguments(ctx: CallContext) -> Result<JsNull> {
let js_func = ctx.get::<JsFunction>(0)?;
let js_func = ctx.get::<Function<(JsString, JsString)>>(0)?;
let js_string_hello = ctx.env.create_string("hello".as_ref())?;
let js_string_world = ctx.env.create_string("world".as_ref())?;

js_func.call(None, &[&js_string_hello, &js_string_world])?;
js_func.call((js_string_hello, js_string_world))?;

ctx.env.get_null()
}

#[js_function(1)]
pub fn call_function_with_this(ctx: CallContext) -> Result<JsNull> {
let js_this: JsObject = ctx.this_unchecked();
let js_func = ctx.get::<JsFunction>(0)?;
let js_func = ctx.get::<Function<()>>(0)?;

js_func.call_without_args(Some(&js_this))?;
js_func.apply(&js_this, ())?;

ctx.env.get_null()
}

#[js_function(2)]
pub fn call_function_error(ctx: CallContext) -> Result<JsUnknown> {
let js_func = ctx.get::<JsFunction>(0)?;
let error_func = ctx.get::<JsFunction>(1)?;
let js_func = ctx.get::<Function<()>>(0)?;
let error_func = ctx.get::<Function>(1)?;

match js_func.call_without_args(None) {
match js_func.call(()) {
Ok(v) => Ok(v),
Err(e) => error_func.call(None, &[JsError::from(e).into_unknown(*ctx.env)]),
Err(e) => error_func.call(JsError::from(e).into_unknown(*ctx.env)),
}
}

Expand Down
113 changes: 41 additions & 72 deletions examples/napi-compat-mode/src/napi4/tsfn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,18 @@ use std::path::Path;
use std::thread;

use napi::{
threadsafe_function::{ThreadSafeCallContext, ThreadsafeFunctionCallMode},
CallContext, Error, JsBoolean, JsFunction, JsNumber, JsObject, JsString, JsUndefined, Ref,
Result, Status,
bindgen_prelude::Function, threadsafe_function::ThreadsafeFunctionCallMode, CallContext, Error,
JsBoolean, JsNumber, JsObject, JsString, JsUndefined, Ref, Result, Status,
};

#[js_function(1)]
pub fn test_threadsafe_function(ctx: CallContext) -> Result<JsUndefined> {
let func = ctx.get::<JsFunction>(0)?;

let tsfn =
ctx
.env
.create_threadsafe_function(&func, 0, |ctx: ThreadSafeCallContext<Vec<u32>>| {
ctx
.value
.iter()
.map(|v| ctx.env.create_uint32(*v))
.collect::<Result<Vec<JsNumber>>>()
})?;
let func = ctx.get::<Function<Vec<u32>>>(0)?;

let tsfn = func
.build_threadsafe_function()
.callee_handled::<true>()
.build()?;

let tsfn_cloned = tsfn.clone();

Expand All @@ -41,18 +34,9 @@ pub fn test_threadsafe_function(ctx: CallContext) -> Result<JsUndefined> {

#[js_function(1)]
pub fn test_abort_threadsafe_function(ctx: CallContext) -> Result<JsBoolean> {
let func = ctx.get::<JsFunction>(0)?;

let tsfn =
ctx
.env
.create_threadsafe_function(&func, 0, |ctx: ThreadSafeCallContext<Vec<u32>>| {
ctx
.value
.iter()
.map(|v| ctx.env.create_uint32(*v))
.collect::<Result<Vec<JsNumber>>>()
})?;
let func = ctx.get::<Function<Vec<JsNumber>>>(0)?;

let tsfn = func.build_threadsafe_function().build()?;

let tsfn_cloned = tsfn.clone();

Expand All @@ -62,51 +46,37 @@ pub fn test_abort_threadsafe_function(ctx: CallContext) -> Result<JsBoolean> {

#[js_function(1)]
pub fn test_abort_independent_threadsafe_function(ctx: CallContext) -> Result<JsBoolean> {
let func = ctx.get::<JsFunction>(0)?;
let func = ctx.get::<Function>(0)?;

let tsfn = ctx
.env
.create_threadsafe_function(&func, 0, |ctx: ThreadSafeCallContext<u32>| {
ctx.env.create_uint32(ctx.value).map(|v| vec![v])
})?;
let tsfn = func.build_threadsafe_function().build()?;

let tsfn_other =
ctx
.env
.create_threadsafe_function(&func, 0, |ctx: ThreadSafeCallContext<u32>| {
ctx.env.create_uint32(ctx.value).map(|v| vec![v])
})?;
let tsfn_other = func.build_threadsafe_function().build()?;

tsfn_other.abort()?;
ctx.env.get_boolean(tsfn.aborted())
}

#[js_function(1)]
pub fn test_call_aborted_threadsafe_function(ctx: CallContext) -> Result<JsUndefined> {
let func = ctx.get::<JsFunction>(0)?;
let func = ctx.get::<Function<u32>>(0)?;

let tsfn = ctx
.env
.create_threadsafe_function(&func, 0, |ctx: ThreadSafeCallContext<u32>| {
ctx.env.create_uint32(ctx.value).map(|v| vec![v])
})?;
let tsfn = func.build_threadsafe_function().build()?;

let tsfn_clone = tsfn.clone();
tsfn_clone.abort()?;

let call_status = tsfn.call(Ok(1), ThreadsafeFunctionCallMode::NonBlocking);
let call_status = tsfn.call(1, ThreadsafeFunctionCallMode::NonBlocking);
assert!(call_status != Status::Ok);
ctx.env.get_undefined()
}

#[js_function(1)]
pub fn test_tsfn_error(ctx: CallContext) -> Result<JsUndefined> {
let func = ctx.get::<JsFunction>(0)?;
let tsfn = ctx
.env
.create_threadsafe_function(&func, 0, |ctx: ThreadSafeCallContext<()>| {
ctx.env.get_undefined().map(|v| vec![v])
})?;
let func = ctx.get::<Function<Option<Error>>>(0)?;
let tsfn = func
.build_threadsafe_function()
.callee_handled::<true>()
.build()?;
thread::spawn(move || {
tsfn.call(
Err(Error::new(Status::GenericFailure, "invalid".to_owned())),
Expand All @@ -126,18 +96,18 @@ async fn read_file_content(filepath: &Path) -> Result<Vec<u8>> {
#[js_function(2)]
pub fn test_tokio_readfile(ctx: CallContext) -> Result<JsUndefined> {
let js_filepath = ctx.get::<JsString>(0)?;
let js_func = ctx.get::<JsFunction>(1)?;
let js_func = ctx.get::<Function<Vec<u8>>>(1)?;
let path_str = js_filepath.into_utf8()?.into_owned()?;

let tsfn =
ctx
.env
.create_threadsafe_function(&js_func, 0, |ctx: ThreadSafeCallContext<Vec<u8>>| {
ctx
.env
.create_buffer_with_data(ctx.value)
.map(|v| v.into_raw())
})?;
let tsfn = js_func
.build_threadsafe_function()
.callee_handled::<true>()
.build_callback(move |ctx| {
ctx
.env
.create_buffer_with_data(ctx.value)
.map(|v| v.into_raw())
})?;
let rt = tokio::runtime::Runtime::new()
.map_err(|e| Error::from_reason(format!("Create tokio runtime failed {}", e)))?;

Expand All @@ -149,24 +119,23 @@ pub fn test_tokio_readfile(ctx: CallContext) -> Result<JsUndefined> {
ctx.env.get_undefined()
}

#[js_function(2)]
#[js_function(3)]
pub fn test_tsfn_with_ref(ctx: CallContext) -> Result<JsUndefined> {
let callback = ctx.get::<JsFunction>(0)?;
let callback: Function<Ref<()>, napi::JsUnknown> = ctx.get::<Function<Ref<()>>>(0)?;
let options = ctx.get::<JsObject>(1)?;
let options_ref = ctx.env.create_reference(options)?;
let tsfn = ctx.env.create_threadsafe_function(
&callback,
0,
|mut ctx: ThreadSafeCallContext<Ref<()>>| {
let option_ref = ctx.env.create_reference(options);
let tsfn = callback
.build_threadsafe_function()
.callee_handled::<true>()
.build_callback(move |mut ctx| {
ctx
.env
.get_reference_value_unchecked::<JsObject>(&ctx.value)
.and_then(|obj| ctx.value.unref(ctx.env).map(|_| obj))
},
)?;
})?;

thread::spawn(move || {
tsfn.call(Ok(options_ref), ThreadsafeFunctionCallMode::Blocking);
tsfn.call(option_ref, ThreadsafeFunctionCallMode::Blocking);
});

ctx.env.get_undefined()
Expand Down
18 changes: 7 additions & 11 deletions examples/napi-compat-mode/src/napi4/tsfn_dua_instance.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
use napi::{
threadsafe_function::{ThreadSafeCallContext, ThreadsafeFunction},
CallContext, JsFunction, JsObject, JsUndefined,
bindgen_prelude::Function, threadsafe_function::ThreadsafeFunction, CallContext, JsObject,
JsUndefined,
};
use napi_derive::js_function;

#[derive(Clone)]
pub struct A {
pub cb: ThreadsafeFunction<String>,
pub cb: ThreadsafeFunction<String, napi::JsUnknown, String, false>,
}

#[js_function(1)]
pub fn constructor(ctx: CallContext) -> napi::Result<JsUndefined> {
let callback = ctx.get::<JsFunction>(0)?;
let callback = ctx.get::<Function<String>>(0)?;

let cb =
ctx
.env
.create_threadsafe_function(&callback, 0, |ctx: ThreadSafeCallContext<String>| {
Ok(ctx.value)
})?;
let cb: ThreadsafeFunction<String, napi::JsUnknown, String, false> =
callback.build_threadsafe_function().build()?;

let mut this: JsObject = ctx.this_unchecked();
let obj = A { cb };
Expand All @@ -32,7 +28,7 @@ pub fn call(ctx: CallContext) -> napi::Result<JsUndefined> {
let this = ctx.this_unchecked();
let obj = ctx.env.unwrap::<A>(&this)?;
obj.cb.call(
Ok("ThreadsafeFunction NonBlocking Call".to_owned()),
"ThreadsafeFunction NonBlocking Call".to_owned(),
napi::threadsafe_function::ThreadsafeFunctionCallMode::NonBlocking,
);
ctx.env.get_undefined()
Expand Down
12 changes: 6 additions & 6 deletions examples/napi/__tests__/__snapshots__/typegen.spec.ts.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,9 @@ Generated by [AVA](https://avajs.dev).
export declare function appendBuffer(buf: Buffer): Buffer␊
export declare function apply0(ctx: Animal, callback: (...args: any[]) => any): void␊
export declare function apply0(ctx: Animal, callback: () => void): void␊
export declare function apply1(ctx: Animal, callback: (...args: any[]) => any, name: string): void␊
export declare function apply1(ctx: Animal, callback: (arg: string) => void, name: string): void␊
export declare function arrayBufferPassThrough(buf: Uint8Array): Promise<Uint8Array>␊
Expand Down Expand Up @@ -323,11 +323,11 @@ Generated by [AVA](https://avajs.dev).
baz: number␊
}␊
export declare function call0(callback: (...args: any[]) => any): number␊
export declare function call0(callback: () => number): number␊
export declare function call1(callback: (...args: any[]) => any, arg: number): number␊
export declare function call1(callback: (arg: number) => number, arg: number): number␊
export declare function call2(callback: (...args: any[]) => any, arg1: number, arg2: number): number␊
export declare function call2(callback: (arg0: number, arg1: number) => number, arg1: number, arg2: number): number␊
export declare function callbackReturnPromise<T>(functionInput: () => T | Promise<T>, callback: (err: Error | null, result: T) => void): T | Promise<T>␊
Expand Down Expand Up @@ -444,7 +444,7 @@ Generated by [AVA](https://avajs.dev).
export declare function either4(input: string | number | boolean | Obj): number␊
export declare function eitherBoolOrFunction(input: boolean | ((...args: any[]) => any)): void␊
export declare function eitherBoolOrFunction(input: boolean | (any)): void␊
export declare function eitherBoolOrTuple(input: boolean | [boolean, string]): void␊
Expand Down
Binary file modified examples/napi/__tests__/__snapshots__/typegen.spec.ts.snap
Binary file not shown.
12 changes: 6 additions & 6 deletions examples/napi/index.d.cts
Original file line number Diff line number Diff line change
Expand Up @@ -271,9 +271,9 @@ export interface AllOptionalObject {

export declare function appendBuffer(buf: Buffer): Buffer

export declare function apply0(ctx: Animal, callback: (...args: any[]) => any): void
export declare function apply0(ctx: Animal, callback: () => void): void

export declare function apply1(ctx: Animal, callback: (...args: any[]) => any, name: string): void
export declare function apply1(ctx: Animal, callback: (arg: string) => void, name: string): void

export declare function arrayBufferPassThrough(buf: Uint8Array): Promise<Uint8Array>

Expand Down Expand Up @@ -313,11 +313,11 @@ export interface C {
baz: number
}

export declare function call0(callback: (...args: any[]) => any): number
export declare function call0(callback: () => number): number

export declare function call1(callback: (...args: any[]) => any, arg: number): number
export declare function call1(callback: (arg: number) => number, arg: number): number

export declare function call2(callback: (...args: any[]) => any, arg1: number, arg2: number): number
export declare function call2(callback: (arg0: number, arg1: number) => number, arg1: number, arg2: number): number

export declare function callbackReturnPromise<T>(functionInput: () => T | Promise<T>, callback: (err: Error | null, result: T) => void): T | Promise<T>

Expand Down Expand Up @@ -434,7 +434,7 @@ export declare function either3(input: string | number | boolean): number

export declare function either4(input: string | number | boolean | Obj): number

export declare function eitherBoolOrFunction(input: boolean | ((...args: any[]) => any)): void
export declare function eitherBoolOrFunction(input: boolean | (any)): void

export declare function eitherBoolOrTuple(input: boolean | [boolean, string]): void

Expand Down
Loading
Loading