From 7dbc94b49bdad6ffe72ded19005e5f572cfa0a3d Mon Sep 17 00:00:00 2001 From: Gabriel Schulhof Date: Sat, 23 Jan 2021 21:07:26 -0800 Subject: [PATCH 1/8] n-api: rename to node-api --- src/js_native_api.h | 9 +- src/js_native_api_types.h | 103 ++++++++++-- src/node_api.h | 325 ++++++++++++++++++++++---------------- src/node_api_types.h | 34 +++- 4 files changed, 315 insertions(+), 156 deletions(-) diff --git a/src/js_native_api.h b/src/js_native_api.h index 5daa20f9040096..2993b2b5f6c49f 100644 --- a/src/js_native_api.h +++ b/src/js_native_api.h @@ -7,9 +7,11 @@ // Use INT_MAX, this should only be consumed by the pre-processor anyway. #define NAPI_VERSION_EXPERIMENTAL 2147483647 -#ifndef NAPI_VERSION -#ifdef NAPI_EXPERIMENTAL +#define NODE_API_VERSION_EXPERIMENTAL NAPI_VERSION_EXPERIMENTAL +#if !(defined(NAPI_VERSION) || defined(NODE_API_VERSION)) +#if defined(NAPI_EXPERIMENTAL) || defined(NODE_API_EXPERIMENTAL) #define NAPI_VERSION NAPI_VERSION_EXPERIMENTAL +#define NODE_API_VERSION NODE_API_VERSION_EXPERIMENTAL #else // The baseline version for N-API. // The NAPI_VERSION controls which version will be used by default when @@ -18,6 +20,7 @@ // LTS versions, they can set NAPI_VERSION knowing that they have specifically // depended on that version. #define NAPI_VERSION 7 +#define NODE_API_VERSION NAPI_VERSION #endif #endif @@ -48,7 +51,7 @@ EXTERN_C_START -NAPI_EXTERN napi_status +NODE_API_EXTERN node_api_status napi_get_last_error_info(napi_env env, const napi_extended_error_info** result); diff --git a/src/js_native_api_types.h b/src/js_native_api_types.h index 7011c80e671a15..455ee5efdb5456 100644 --- a/src/js_native_api_types.h +++ b/src/js_native_api_types.h @@ -20,6 +20,13 @@ typedef struct napi_handle_scope__* napi_handle_scope; typedef struct napi_escapable_handle_scope__* napi_escapable_handle_scope; typedef struct napi_callback_info__* napi_callback_info; typedef struct napi_deferred__* napi_deferred; +#define node_api_env napi_env +#define node_api_value napi_value +#define node_api_ref napi_ref +#define node_api_handle_scope napi_handle_scope +#define node_api_escapable_handle_scope napi_escapable_handle_scope +#define node_api_callback_info napi_callback_info +#define node_api_deferred napi_deferred typedef enum { napi_default = 0, @@ -41,6 +48,16 @@ typedef enum { napi_configurable, #endif // NAPI_EXPERIMENTAL } napi_property_attributes; +#define node_api_default napi_default +#define node_api_writable napi_writable +#define node_api_enumerable napi_enumerable +#define node_api_configurable napi_configurable +#define node_api_static napi_static +#ifdef NAPI_EXPERIMENTAL +#define node_api_default_method napi_default_method +#define node_api_default_jsproperty napi_default_jsproperty +#endif // NAPI_EXPERIMENTAL +#define node_api_property_attributes napi_property_attributes typedef enum { // ES6 types (corresponds to typeof) @@ -55,6 +72,17 @@ typedef enum { napi_external, napi_bigint, } napi_valuetype; +#define node_api_undefined napi_undefined +#define node_api_null napi_null +#define node_api_boolean napi_boolean +#define node_api_number napi_number +#define node_api_string napi_string +#define node_api_symbol napi_symbol +#define node_api_object napi_object +#define node_api_function napi_function +#define napi_external, +#define napi_bigint, +#define napi_valuetype; typedef enum { napi_int8_array, @@ -69,6 +97,18 @@ typedef enum { napi_bigint64_array, napi_biguint64_array, } napi_typedarray_type; +#define node_api_int8_array napi_int8_array +#define node_api_uint8_array napi_uint8_array +#define node_api_uint8_clamped_array napi_uint8_clamped_array +#define node_api_int16_array napi_int16_array +#define node_api_uint16_array napi_uint16_array +#define node_api_int32_array napi_int32_array +#define node_api_uint32_array napi_uint32_array +#define node_api_float32_array napi_float32_array +#define node_api_float64_array napi_float64_array +#define node_api_bigint64_array napi_bigint64_array +#define node_api_biguint64_array napi_biguint64_array +#define node_api_typedarray_type napi_typedarray_type typedef enum { napi_ok, @@ -102,38 +142,70 @@ typedef enum { // * the definition of `napi_status` in doc/api/n-api.md to reflect the newly // added value(s). -typedef napi_value (*napi_callback)(napi_env env, - napi_callback_info info); -typedef void (*napi_finalize)(napi_env env, +#define node_api_ok napi_ok +#define node_api_invalid_arg napi_invalid_arg +#define node_api_object_expected napi_object_expected +#define node_api_string_expected napi_string_expected +#define node_api_name_expected napi_name_expected +#define node_api_function_expected napi_function_expected +#define node_api_number_expected napi_number_expected +#define node_api_boolean_expected napi_boolean_expected +#define node_api_array_expected napi_array_expected +#define node_api_generic_failure napi_generic_failure +#define node_api_pending_exception napi_pending_exception +#define node_api_cancelled napi_cancelled +#define node_api_escape_called_twice napi_escape_called_twice +#define node_api_handle_scope_mismatch napi_handle_scope_mismatch +#define node_api_callback_scope_mismatch napi_callback_scope_mismatch +#define node_api_queue_full napi_queue_full +#define node_api_closing napi_closing +#define node_api_bigint_expected napi_bigint_expected +#define node_api_date_expected napi_date_expected +#define node_api_arraybuffer_expected napi_arraybuffer_expected +#define node_api_detachable_arraybuffer_expected \ + napi_detachable_arraybuffer_expected +#define node_api_would_deadlock napi_would_deadlock +#define node_api_status napi_status + +typedef node_api_value (*napi_callback)(node_api_env env, + node_api_callback_info info); +#define node_api_callback napi_callback +typedef void (*napi_finalize)(node_api_env env, void* finalize_data, void* finalize_hint); +#define node_api_finalize napi_finalize typedef struct { // One of utf8name or name should be NULL. const char* utf8name; - napi_value name; + node_api_value name; - napi_callback method; - napi_callback getter; - napi_callback setter; - napi_value value; + node_api_callback method; + node_api_callback getter; + node_api_callback setter; + node_api_value value; - napi_property_attributes attributes; + node_api_property_attributes attributes; void* data; } napi_property_descriptor; +#define node_api_property_descriptor napi_property_descriptor typedef struct { const char* error_message; void* engine_reserved; uint32_t engine_error_code; - napi_status error_code; + node_api_status error_code; } napi_extended_error_info; +#define node_api_extended_error_info napi_extended_error_info #if NAPI_VERSION >= 6 typedef enum { napi_key_include_prototypes, napi_key_own_only } napi_key_collection_mode; +#define node_api_key_include_prototypes napi_key_include_prototypes +#define node_api_key_own_only napi_key_own_only +#define node_api_key_collection_mode napi_key_collection_mode typedef enum { napi_key_all_properties = 0, @@ -143,11 +215,21 @@ typedef enum { napi_key_skip_strings = 1 << 3, napi_key_skip_symbols = 1 << 4 } napi_key_filter; +#define node_api_key_all_properties napi_key_all_properties +#define node_api_key_writable napi_key_writable +#define node_api_key_enumerable napi_key_enumerable +#define node_api_key_configurable napi_key_configurable +#define node_api_key_skip_strings napi_key_skip_strings +#define node_api_key_skip_symbols napi_key_skip_symbols +#define node_api_key_filter napi_key_filter typedef enum { napi_key_keep_numbers, napi_key_numbers_to_strings } napi_key_conversion; +#define node_api_key_keep_numbers napi_key_keep_numbers +#define node_api_key_numbers_to_strings napi_key_numbers_to_strings +#define node_api_key_conversion napi_key_conversion #endif // NAPI_VERSION >= 6 #ifdef NAPI_EXPERIMENTAL @@ -155,6 +237,7 @@ typedef struct { uint64_t lower; uint64_t upper; } napi_type_tag; +#define node_api_type_tag napi_type_tag #endif // NAPI_EXPERIMENTAL #endif // SRC_JS_NATIVE_API_TYPES_H_ diff --git a/src/node_api.h b/src/node_api.h index 786988e296b8b2..52d1bbdafd40e5 100644 --- a/src/node_api.h +++ b/src/node_api.h @@ -9,6 +9,8 @@ #define NAPI_EXTERN __attribute__((__import_module__("napi"))) #endif #endif +#define NODE_API_EXTERN NAPI_EXTERN + #include "js_native_api.h" #include "node_api_types.h" @@ -19,6 +21,7 @@ struct uv_loop_s; // Forward declaration. #else # define NAPI_MODULE_EXPORT __attribute__((visibility("default"))) #endif +#define NODE_API_MODULE_EXPORT NAPI_MODULE_EXPORT #if defined(__GNUC__) # define NAPI_NO_RETURN __attribute__((noreturn)) @@ -27,21 +30,25 @@ struct uv_loop_s; // Forward declaration. #else # define NAPI_NO_RETURN #endif +#define NODE_API_NO_RETURN NAPI_NO_RETURN -typedef napi_value (*napi_addon_register_func)(napi_env env, - napi_value exports); +typedef node_api_value (*napi_addon_register_func)(node_api_env env, + node_api_value exports); +#define node_api_addon_register_func napi_addon_register_func typedef struct napi_module { int nm_version; unsigned int nm_flags; const char* nm_filename; - napi_addon_register_func nm_register_func; + node_api_addon_register_func nm_register_func; const char* nm_modname; void* nm_priv; void* reserved[4]; } napi_module; +#define node_api_module napi_module #define NAPI_MODULE_VERSION 1 +#define NODE_API_MODULE_VERSION NAPI_MODULE_VERSION #if defined(_MSC_VER) #pragma section(".CRT$XCU", read) @@ -55,10 +62,11 @@ typedef struct napi_module { static void fn(void) __attribute__((constructor)); \ static void fn(void) #endif +#define NODE_API_C_CTOR NAPI_C_CTOR #define NAPI_MODULE_X(modname, regfunc, priv, flags) \ EXTERN_C_START \ - static napi_module _module = \ + static node_api_module _module = \ { \ NAPI_MODULE_VERSION, \ flags, \ @@ -69,142 +77,176 @@ typedef struct napi_module { {0}, \ }; \ NAPI_C_CTOR(_register_ ## modname) { \ - napi_module_register(&_module); \ + node_api_module_register(&_module); \ } \ EXTERN_C_END +#define NODE_API_MODULE_X NAPI_MODULE_X #define NAPI_MODULE_INITIALIZER_X(base, version) \ NAPI_MODULE_INITIALIZER_X_HELPER(base, version) #define NAPI_MODULE_INITIALIZER_X_HELPER(base, version) base##version +#define NODE_API_MODULE_INITIALIZER_X NAPI_MODULE_INITIALIZER_X + #ifdef __wasm32__ #define NAPI_WASM_INITIALIZER \ - NAPI_MODULE_INITIALIZER_X(napi_register_wasm_v, NAPI_MODULE_VERSION) + NODE_API_MODULE_INITIALIZER_X(napi_register_wasm_v, NODE_API_MODULE_VERSION) +#define NODE_API_WASM_INITIALIZER NAPI_WASM_INITIALIZER #define NAPI_MODULE(modname, regfunc) \ EXTERN_C_START \ - NAPI_MODULE_EXPORT napi_value NAPI_WASM_INITIALIZER(napi_env env, \ - napi_value exports) { \ + NODE_API_MODULE_EXPORT node_api_value \ + NODE_API_WASM_INITIALIZER(node_api_env env, node_api_value exports) { \ return regfunc(env, exports); \ } \ EXTERN_C_END #else #define NAPI_MODULE(modname, regfunc) \ - NAPI_MODULE_X(modname, regfunc, NULL, 0) // NOLINT (readability/null_usage) + NODE_API_MODULE_X(modname, regfunc, NULL, 0) // NOLINT (readability/null_usage) #endif +#define NODE_API_MODULE NAPI_MODULE #define NAPI_MODULE_INITIALIZER_BASE napi_register_module_v +#define NODE_API_MODULE_INITIALIZER_BASE NAPI_MODULE_INITIALIZER_BASE #define NAPI_MODULE_INITIALIZER \ - NAPI_MODULE_INITIALIZER_X(NAPI_MODULE_INITIALIZER_BASE, \ - NAPI_MODULE_VERSION) - -#define NAPI_MODULE_INIT() \ - EXTERN_C_START \ - NAPI_MODULE_EXPORT napi_value \ - NAPI_MODULE_INITIALIZER(napi_env env, napi_value exports); \ - EXTERN_C_END \ - NAPI_MODULE(NODE_GYP_MODULE_NAME, NAPI_MODULE_INITIALIZER) \ - napi_value NAPI_MODULE_INITIALIZER(napi_env env, \ - napi_value exports) + NODE_API_MODULE_INITIALIZER_X(NODE_API_MODULE_INITIALIZER_BASE, \ + NODE_API_MODULE_VERSION) +#define NODE_API_MODULE_INITIALIZER NAPI_MODULE_INITIALIZER + +#define NAPI_MODULE_INIT() \ + EXTERN_C_START \ + NODE_API_MODULE_EXPORT node_api_value \ + NODE_API_MODULE_INITIALIZER(node_api_env env, node_api_value exports); \ + EXTERN_C_END \ + NODE_API_MODULE(NODE_GYP_MODULE_NAME, NODE_API_MODULE_INITIALIZER) \ + node_api_value NODE_API_MODULE_INITIALIZER(node_api_env env, \ + node_api_value exports) EXTERN_C_START -NAPI_EXTERN void napi_module_register(napi_module* mod); +NODE_API_EXTERN void napi_module_register(node_api_module* mod); +#define node_api_module_register napi_module_register -NAPI_EXTERN NAPI_NO_RETURN void napi_fatal_error(const char* location, - size_t location_len, - const char* message, - size_t message_len); +NODE_API_EXTERN NAPI_NO_RETURN void napi_fatal_error(const char* location, + size_t location_len, + const char* message, + size_t message_len); +#define node_api_fatal_error napi_fatal_error // Methods for custom handling of async operations -NAPI_EXTERN napi_status napi_async_init(napi_env env, - napi_value async_resource, - napi_value async_resource_name, - napi_async_context* result); - -NAPI_EXTERN napi_status napi_async_destroy(napi_env env, - napi_async_context async_context); - -NAPI_EXTERN napi_status napi_make_callback(napi_env env, - napi_async_context async_context, - napi_value recv, - napi_value func, - size_t argc, - const napi_value* argv, - napi_value* result); - -// Methods to provide node::Buffer functionality with napi types -NAPI_EXTERN napi_status napi_create_buffer(napi_env env, - size_t length, - void** data, - napi_value* result); -NAPI_EXTERN napi_status napi_create_external_buffer(napi_env env, - size_t length, - void* data, - napi_finalize finalize_cb, - void* finalize_hint, - napi_value* result); -NAPI_EXTERN napi_status napi_create_buffer_copy(napi_env env, - size_t length, - const void* data, - void** result_data, - napi_value* result); -NAPI_EXTERN napi_status napi_is_buffer(napi_env env, - napi_value value, - bool* result); -NAPI_EXTERN napi_status napi_get_buffer_info(napi_env env, - napi_value value, - void** data, - size_t* length); +NODE_API_EXTERN node_api_status napi_async_init(node_api_env env, + node_api_value async_resource, + node_api_value async_resource_name, + node_api_async_context* result); +#define node_api_async_init napi_async_init + +NAPI_EXTERN node_api_status +napi_async_destroy(node_api_env env, node_api_async_context async_context); +#define node_api_async_destroy napi_async_destroy + +NODE_API_EXTERN node_api_status +napi_make_callback(node_api_env env, + node_api_async_context async_context, + node_api_value recv, + node_api_value func, + size_t argc, + const node_api_value* argv, + node_api_value* result); +#define node_api_make_callback napi_make_callback + +// Methods to provide node::Buffer functionality with node_api types +NODE_API_EXTERN node_api_status napi_create_buffer(node_api_env env, + size_t length, + void** data, + node_api_value* result); +#define node_api_create_buffer napi_create_buffer +NODE_API_EXTERN node_api_status +napi_create_external_buffer(node_api_env env, + size_t length, + void* data, + node_api_finalize finalize_cb, + void* finalize_hint, + node_api_value* result); +#define node_api_create_external_buffer napi_create_external_buffer +NODE_API_EXTERN node_api_status +napi_create_buffer_copy(node_api_env env, + size_t length, + const void* data, + void** result_data, + node_api_value* result); +#define node_api_create_buffer napi_create_buffer +NODE_API_EXTERN node_api_status +napi_is_buffer(node_api_env env, + node_api_value value, + bool* result); +#define node_api_is_buffer napi_is_buffer +NODE_API_EXTERN node_api_status +napi_get_buffer_info(node_api_env env, + node_api_value value, + void** data, + size_t* length); +#define node_api_get_buffer_info napi_get_buffer_info // Methods to manage simple async operations -NAPI_EXTERN -napi_status napi_create_async_work(napi_env env, - napi_value async_resource, - napi_value async_resource_name, - napi_async_execute_callback execute, - napi_async_complete_callback complete, - void* data, - napi_async_work* result); -NAPI_EXTERN napi_status napi_delete_async_work(napi_env env, - napi_async_work work); -NAPI_EXTERN napi_status napi_queue_async_work(napi_env env, - napi_async_work work); -NAPI_EXTERN napi_status napi_cancel_async_work(napi_env env, - napi_async_work work); +NODE_API_EXTERN node_api_status +napi_create_async_work(node_api_env env, + node_api_value async_resource, + node_api_value async_resource_name, + node_api_async_execute_callback execute, + node_api_async_complete_callback complete, + void* data, + node_api_async_work* result); +#define node_api_create_async_work napi_create_async_work +NODE_API_EXTERN node_api_status +napi_delete_async_work(node_api_env env, node_api_async_work work); +#define node_api_delete_async_work napi_delete_async_work +NODE_API_EXTERN node_api_status +napi_queue_async_work(node_api_env env, node_api_async_work work); +#define node_api_queue_async_work napi_queue_async_work +NODE_API_EXTERN node_api_status +napi_cancel_async_work(node_api_env env, node_api_async_work work); +#define node_api_cancel_async_work napi_cancel_async_work // version management -NAPI_EXTERN -napi_status napi_get_node_version(napi_env env, - const napi_node_version** version); +NODE_API_EXTERN node_api_status +napi_get_node_version(node_api_env env, const node_api_node_version** version); +#define node_api_get_node_version napi_get_node_version #if NAPI_VERSION >= 2 // Return the current libuv event loop for a given environment -NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env, - struct uv_loop_s** loop); +NODE_API_EXTERN node_api_status +napi_get_uv_event_loop(node_api_env env, struct uv_loop_s** loop); +#define node_api_get_uv_event_loop napi_get_uv_event_loop #endif // NAPI_VERSION >= 2 #if NAPI_VERSION >= 3 -NAPI_EXTERN napi_status napi_fatal_exception(napi_env env, napi_value err); +NODE_API_EXTERN node_api_status +napi_fatal_exception(node_api_env env, node_api_value err); +#define node_api_fatal_exception napi_fatal_exception -NAPI_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env, - void (*fun)(void* arg), - void* arg); +NODE_API_EXTERN node_api_status +napi_add_env_cleanup_hook(node_api_env env, void (*fun)(void* arg), void* arg); +#define node_api_add_env_cleanup_hook napi_add_env_cleanup_hook -NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env, - void (*fun)(void* arg), - void* arg); +NODE_API_EXTERN node_api_status +napi_remove_env_cleanup_hook(node_api_env env, + void (*fun)(void* arg), + void* arg); +#define node_api_remove_env_cleanup_hook napi_remove_env_cleanup_hook -NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env, - napi_value resource_object, - napi_async_context context, - napi_callback_scope* result); +NODE_API_EXTERN node_api_status +napi_open_callback_scope(node_api_env env, + node_api_value resource_object, + node_api_async_context context, + node_api_callback_scope* result); +#define node_api_open_callback_scope napi_open_callback_scope -NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env, - napi_callback_scope scope); +NODE_API_EXTERN node_api_status +napi_close_callback_scope(node_api_env env, node_api_callback_scope scope); +#define node_api_close_callback_scope napi_close_callback_scope #endif // NAPI_VERSION >= 3 @@ -212,54 +254,67 @@ NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env, #ifndef __wasm32__ // Calling into JS from other threads -NAPI_EXTERN napi_status -napi_create_threadsafe_function(napi_env env, - napi_value func, - napi_value async_resource, - napi_value async_resource_name, - size_t max_queue_size, - size_t initial_thread_count, - void* thread_finalize_data, - napi_finalize thread_finalize_cb, - void* context, - napi_threadsafe_function_call_js call_js_cb, - napi_threadsafe_function* result); - -NAPI_EXTERN napi_status -napi_get_threadsafe_function_context(napi_threadsafe_function func, +NODE_API_EXTERN node_api_status +napi_create_threadsafe_function(node_api_env env, + node_api_value func, + node_api_value async_resource, + node_api_value async_resource_name, + size_t max_queue_size, + size_t initial_thread_count, + void* thread_finalize_data, + node_api_finalize thread_finalize_cb, + void* context, + node_api_threadsafe_function_call_js call_js_cb, + node_api_threadsafe_function* result); +#define node_api_create_threadsafe_function \ + napi_create_threadsafe_function + +NODE_API_EXTERN node_api_status +napi_get_threadsafe_function_context(node_api_threadsafe_function func, void** result); - -NAPI_EXTERN napi_status -napi_call_threadsafe_function(napi_threadsafe_function func, - void* data, - napi_threadsafe_function_call_mode is_blocking); - -NAPI_EXTERN napi_status -napi_acquire_threadsafe_function(napi_threadsafe_function func); - -NAPI_EXTERN napi_status -napi_release_threadsafe_function(napi_threadsafe_function func, - napi_threadsafe_function_release_mode mode); - -NAPI_EXTERN napi_status -napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func); - -NAPI_EXTERN napi_status -napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func); +#define node_api_get_threadsafe_function_context \ + napi_get_threadsafe_function_context + +NODE_API_EXTERN node_api_status +napi_call_threadsafe_function(node_api_threadsafe_function func, + void* data, + node_api_threadsafe_function_call_mode is_blocking); +#define node_api_call_threadsafe_function napi_call_threadsafe_function + +NODE_API_EXTERN node_api_status +napi_acquire_threadsafe_function(node_api_threadsafe_function func); +#define node_api_acquire_threadsafe_function napi_acquire_threadsafe_function + +NODE_API_EXTERN node_api_status +napi_release_threadsafe_function(node_api_threadsafe_function func, + node_api_threadsafe_function_release_mode mode); +#define node_api_release_threadsafe_function napi_release_threadsafe_function + +NODE_API_EXTERN node_api_status +napi_unref_threadsafe_function(node_api_env env, + node_api_threadsafe_function func); +#define node_api_unref_threadsafe_function napi_unref_threadsafe_function + +NODE_API_EXTERN node_api_status +napi_ref_threadsafe_function(node_api_env env, + node_api_threadsafe_function func); +#define node_api_ref_threadsafe_function napi_ref_threadsafe_function #endif // __wasm32__ #endif // NAPI_VERSION >= 4 #ifdef NAPI_EXPERIMENTAL -NAPI_EXTERN napi_status napi_add_async_cleanup_hook( - napi_env env, - napi_async_cleanup_hook hook, +NODE_API_EXTERN node_api_status napi_add_async_cleanup_hook( + node_api_env env, + node_api_async_cleanup_hook hook, void* arg, - napi_async_cleanup_hook_handle* remove_handle); + node_api_async_cleanup_hook_handle* remove_handle); +#define node_api_add_async_cleanup_hook napi_add_async_cleanup_hook -NAPI_EXTERN napi_status napi_remove_async_cleanup_hook( - napi_async_cleanup_hook_handle remove_handle); +NODE_API_EXTERN node_api_status napi_remove_async_cleanup_hook( + node_api_async_cleanup_hook_handle remove_handle); +#define node_api_remove_async_cleanup_hook napi_remove_async_cleanup_hook #endif // NAPI_EXPERIMENTAL diff --git a/src/node_api_types.h b/src/node_api_types.h index 0e400e9676df5b..10ccfb08e5af4d 100644 --- a/src/node_api_types.h +++ b/src/node_api_types.h @@ -6,8 +6,12 @@ typedef struct napi_callback_scope__* napi_callback_scope; typedef struct napi_async_context__* napi_async_context; typedef struct napi_async_work__* napi_async_work; +#define node_api_callback_scope napi_callback_scope +#define node_api_async_context napi_async_context +#define node_api_async_work napi_async_work #if NAPI_VERSION >= 4 typedef struct napi_threadsafe_function__* napi_threadsafe_function; +#define node_api_threadsafe_function napi_threadsafe_function #endif // NAPI_VERSION >= 4 #if NAPI_VERSION >= 4 @@ -15,23 +19,33 @@ typedef enum { napi_tsfn_release, napi_tsfn_abort } napi_threadsafe_function_release_mode; - +#define node_api_tsfn_release napi_tsfn_release +#define node_api_tsfn_abort napi_tsfn_abort +#define node_api_threadsafe_function_release_mode \ + napi_threadsafe_function_release_mode typedef enum { napi_tsfn_nonblocking, napi_tsfn_blocking } napi_threadsafe_function_call_mode; +#define node_api_tsfn_nonblocking napi_tsfn_nonblocking +#define node_api_tsfn_blocking napi_tsfn_blocking +#define node_api_threadsafe_function_call_mode \ + napi_threadsafe_function_call_mode #endif // NAPI_VERSION >= 4 -typedef void (*napi_async_execute_callback)(napi_env env, +typedef void (*napi_async_execute_callback)(node_api_env env, void* data); -typedef void (*napi_async_complete_callback)(napi_env env, - napi_status status, +#define node_api_async_execute_callback napi_async_execute_callback +typedef void (*napi_async_complete_callback)(node_api_env env, + node_api_status status, void* data); +#define node_api_async_complete_callback napi_async_complete_callback #if NAPI_VERSION >= 4 -typedef void (*napi_threadsafe_function_call_js)(napi_env env, - napi_value js_callback, +typedef void (*napi_threadsafe_function_call_js)(node_api_env env, + node_api_value js_callback, void* context, void* data); +#define node_api_threadsafe_function_call_js napi_threadsafe_function_call_js #endif // NAPI_VERSION >= 4 typedef struct { @@ -40,11 +54,15 @@ typedef struct { uint32_t patch; const char* release; } napi_node_version; +#define node_api_node_version napi_node_version #ifdef NAPI_EXPERIMENTAL typedef struct napi_async_cleanup_hook_handle__* napi_async_cleanup_hook_handle; -typedef void (*napi_async_cleanup_hook)(napi_async_cleanup_hook_handle handle, - void* data); +#define node_api_async_cleanup_hook_handle napi_async_cleanup_hook_handle +typedef void (*napi_async_cleanup_hook)( + node_api_async_cleanup_hook_handle handle, + void* data); +#define node_api_async_cleanup_hook napi_async_cleanup_hook #endif // NAPI_EXPERIMENTAL #endif // SRC_NODE_API_TYPES_H_ From 3f67fe2a8172cde27f0f3388b388af2923ded949 Mon Sep 17 00:00:00 2001 From: Gabriel Schulhof Date: Mon, 25 Jan 2021 17:21:41 -0800 Subject: [PATCH 2/8] update tests --- src/js_native_api.h | 1017 ++++++++++------- src/js_native_api_types.h | 12 +- src/node_api.h | 7 +- src/node_api_types.h | 6 +- .../2_function_arguments/binding.c | 33 +- test/js-native-api/3_callbacks/binding.c | 56 +- test/js-native-api/4_object_factory/binding.c | 23 +- .../5_function_factory/binding.c | 27 +- test/js-native-api/6_object_wrap/myobject.cc | 152 +-- test/js-native-api/6_object_wrap/myobject.h | 25 +- test/js-native-api/7_factory_wrap/binding.cc | 23 +- test/js-native-api/7_factory_wrap/myobject.cc | 101 +- test/js-native-api/7_factory_wrap/myobject.h | 24 +- .../8_passing_wrapped/binding.cc | 54 +- .../8_passing_wrapped/myobject.cc | 75 +- .../8_passing_wrapped/myobject.h | 19 +- test/js-native-api/common.c | 64 +- test/js-native-api/common.h | 60 +- test/js-native-api/entry_point.c | 4 +- test/js-native-api/test_array/test_array.c | 166 +-- test/js-native-api/test_bigint/test_bigint.c | 137 ++- test/js-native-api/test_constructor/test.js | 8 +- .../test_constructor/test_constructor.c | 204 ++-- test/js-native-api/test_conversions/test.js | 6 +- .../test_conversions/test_conversions.c | 142 +-- .../test_conversions/test_null.c | 90 +- .../test_conversions/test_null.h | 2 +- .../test_dataview/test_dataview.c | 107 +- test/js-native-api/test_date/test_date.c | 58 +- test/js-native-api/test_error/test_error.c | 217 ++-- .../test_exception/test_exception.c | 95 +- test/js-native-api/test_function/test.js | 2 +- .../test_function/test_function.c | 249 ++-- test/js-native-api/test_general/test.js | 6 +- .../test_general/testNapiStatus.js | 3 +- .../js-native-api/test_general/test_general.c | 329 +++--- .../test_handle_scope/test_handle_scope.c | 90 +- .../test_instance_data/test_instance_data.c | 83 +- test/js-native-api/test_new_target/binding.c | 82 +- test/js-native-api/test_number/test.js | 4 +- test/js-native-api/test_number/test_number.c | 97 +- test/js-native-api/test_object/test.js | 18 +- test/js-native-api/test_object/test_null.c | 357 +++--- test/js-native-api/test_object/test_null.h | 2 +- test/js-native-api/test_object/test_null.js | 4 +- test/js-native-api/test_object/test_object.c | 544 ++++----- .../js-native-api/test_promise/test_promise.c | 48 +- test/js-native-api/test_properties/test.js | 4 +- .../test_properties/test_properties.c | 110 +- test/js-native-api/test_reference/test.js | 10 +- .../test_reference/test_reference.c | 198 ++-- test/js-native-api/test_string/test_string.c | 274 +++-- test/js-native-api/test_symbol/test_symbol.c | 26 +- .../test_typedarray/test_typedarray.c | 198 ++-- test/node-api/1_hello_world/binding.c | 13 +- test/node-api/1_hello_world/test.js | 2 +- test/node-api/test_async/test_async.c | 228 ++-- .../test_async_cleanup_hook/binding.c | 32 +- test/node-api/test_async_context/binding.c | 132 ++- .../test-gcable-callback.js | 10 +- .../test_async_context/test-gcable.js | 5 +- test/node-api/test_buffer/test_buffer.c | 169 +-- test/node-api/test_callback_scope/binding.c | 129 ++- test/node-api/test_cleanup_hook/binding.c | 10 +- test/node-api/test_exception/test_exception.c | 23 +- test/node-api/test_fatal/test_fatal.c | 24 +- .../test_fatal_exception.c | 18 +- test/node-api/test_general/test_general.c | 43 +- test/node-api/test_instance_data/addon.c | 18 +- .../test_instance_data/test_instance_data.c | 268 ++--- .../test_instance_data/test_ref_then_set.c | 7 +- .../test_instance_data/test_set_then_ref.c | 7 +- test/node-api/test_make_callback/binding.c | 55 +- test/node-api/test_make_callback/test.js | 2 +- .../test_make_callback_recurse/binding.c | 41 +- test/node-api/test_null_init/test_null_init.c | 2 +- test/node-api/test_policy/binding.c | 13 +- .../test_threadsafe_function/binding.c | 272 +++-- .../node-api/test_threadsafe_function/test.js | 5 +- test/node-api/test_uv_loop/test_uv_loop.cc | 63 +- .../test_worker_buffer_callback.c | 24 +- test/node-api/test_worker_terminate/test.js | 2 +- .../test_worker_terminate.c | 40 +- .../test_worker_terminate_finalization.c | 42 +- 84 files changed, 4010 insertions(+), 3441 deletions(-) diff --git a/src/js_native_api.h b/src/js_native_api.h index 2993b2b5f6c49f..0c97f12524d63c 100644 --- a/src/js_native_api.h +++ b/src/js_native_api.h @@ -38,8 +38,10 @@ #define NAPI_EXTERN __attribute__((visibility("default"))) #endif #endif +#define NODE_API_EXTERN NAPI_EXTERN #define NAPI_AUTO_LENGTH SIZE_MAX +#define NODE_API_AUTO_LENGTH NAPI_AUTO_LENGTH #ifdef __cplusplus #define EXTERN_C_START extern "C" { @@ -52,511 +54,714 @@ EXTERN_C_START NODE_API_EXTERN node_api_status -napi_get_last_error_info(napi_env env, - const napi_extended_error_info** result); +napi_get_last_error_info(node_api_env env, + const node_api_extended_error_info** result); +#define node_api_get_last_error_info napi_get_last_error_info // Getters for defined singletons -NAPI_EXTERN napi_status napi_get_undefined(napi_env env, napi_value* result); -NAPI_EXTERN napi_status napi_get_null(napi_env env, napi_value* result); -NAPI_EXTERN napi_status napi_get_global(napi_env env, napi_value* result); -NAPI_EXTERN napi_status napi_get_boolean(napi_env env, - bool value, - napi_value* result); +NODE_API_EXTERN node_api_status +napi_get_undefined(node_api_env env, node_api_value* result); +#define node_api_get_undefined napi_get_undefined +NODE_API_EXTERN node_api_status +napi_get_null(node_api_env env, node_api_value* result); +#define node_api_get_null napi_get_null +NODE_API_EXTERN node_api_status +napi_get_global(node_api_env env, node_api_value* result); +#define node_api_get_global napi_get_global +NODE_API_EXTERN node_api_status +napi_get_boolean(node_api_env env, bool value, node_api_value* result); +#define node_api_get_boolean napi_get_boolean // Methods to create Primitive types/Objects -NAPI_EXTERN napi_status napi_create_object(napi_env env, napi_value* result); -NAPI_EXTERN napi_status napi_create_array(napi_env env, napi_value* result); -NAPI_EXTERN napi_status napi_create_array_with_length(napi_env env, - size_t length, - napi_value* result); -NAPI_EXTERN napi_status napi_create_double(napi_env env, - double value, - napi_value* result); -NAPI_EXTERN napi_status napi_create_int32(napi_env env, - int32_t value, - napi_value* result); -NAPI_EXTERN napi_status napi_create_uint32(napi_env env, - uint32_t value, - napi_value* result); -NAPI_EXTERN napi_status napi_create_int64(napi_env env, - int64_t value, - napi_value* result); -NAPI_EXTERN napi_status napi_create_string_latin1(napi_env env, - const char* str, - size_t length, - napi_value* result); -NAPI_EXTERN napi_status napi_create_string_utf8(napi_env env, - const char* str, - size_t length, - napi_value* result); -NAPI_EXTERN napi_status napi_create_string_utf16(napi_env env, - const char16_t* str, - size_t length, - napi_value* result); -NAPI_EXTERN napi_status napi_create_symbol(napi_env env, - napi_value description, - napi_value* result); -NAPI_EXTERN napi_status napi_create_function(napi_env env, - const char* utf8name, - size_t length, - napi_callback cb, - void* data, - napi_value* result); -NAPI_EXTERN napi_status napi_create_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result); -NAPI_EXTERN napi_status napi_create_type_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result); -NAPI_EXTERN napi_status napi_create_range_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result); - -// Methods to get the native napi_value from Primitive type -NAPI_EXTERN napi_status napi_typeof(napi_env env, - napi_value value, - napi_valuetype* result); -NAPI_EXTERN napi_status napi_get_value_double(napi_env env, - napi_value value, - double* result); -NAPI_EXTERN napi_status napi_get_value_int32(napi_env env, - napi_value value, - int32_t* result); -NAPI_EXTERN napi_status napi_get_value_uint32(napi_env env, - napi_value value, - uint32_t* result); -NAPI_EXTERN napi_status napi_get_value_int64(napi_env env, - napi_value value, - int64_t* result); -NAPI_EXTERN napi_status napi_get_value_bool(napi_env env, - napi_value value, - bool* result); +NODE_API_EXTERN node_api_status +napi_create_object(node_api_env env, node_api_value* result); +#define node_api_create_object napi_create_object +NODE_API_EXTERN node_api_status +napi_create_array(node_api_env env, node_api_value* result); +#define node_api_create_array napi_create_array +NODE_API_EXTERN node_api_status +napi_create_array_with_length(node_api_env env, + size_t length, + node_api_value* result); +#define node_api_create_array_with_length \ + napi_create_array_with_length +NODE_API_EXTERN node_api_status +napi_create_double(node_api_env env, + double value, + node_api_value* result); +#define node_api_create_double napi_create_double +NODE_API_EXTERN node_api_status +napi_create_int32(node_api_env env, + int32_t value, + node_api_value* result); +#define node_api_create_int32 napi_create_int32 +NODE_API_EXTERN node_api_status +napi_create_uint32(node_api_env env, + uint32_t value, + node_api_value* result); +#define node_api_create_uint32 napi_create_uint32 +NODE_API_EXTERN node_api_status +napi_create_int64(node_api_env env, + int64_t value, + node_api_value* result); +#define node_api_create_int64 napi_create_int64 +NODE_API_EXTERN node_api_status +napi_create_string_latin1(node_api_env env, + const char* str, + size_t length, + node_api_value* result); +#define node_api_create_string_latin1 napi_create_string_latin1 +NODE_API_EXTERN node_api_status +napi_create_string_utf8(node_api_env env, + const char* str, + size_t length, + node_api_value* result); +#define node_api_create_string_utf8 napi_create_string_utf8 +NODE_API_EXTERN node_api_status +napi_create_string_utf16(node_api_env env, + const char16_t* str, + size_t length, + node_api_value* result); +#define node_api_create_string_utf16 napi_create_string_utf16 +NODE_API_EXTERN node_api_status +napi_create_symbol(node_api_env env, + node_api_value description, + node_api_value* result); +#define node_api_create_symbol napi_create_symbol +NODE_API_EXTERN node_api_status +napi_create_function(node_api_env env, + const char* utf8name, + size_t length, + node_api_callback cb, + void* data, + node_api_value* result); +#define node_api_create_function napi_create_function +NODE_API_EXTERN node_api_status +napi_create_error(node_api_env env, + node_api_value code, + node_api_value msg, + node_api_value* result); +#define node_api_create_error napi_create_error +NODE_API_EXTERN node_api_status +napi_create_type_error(node_api_env env, + node_api_value code, + node_api_value msg, + node_api_value* result); +#define node_api_create_type_error napi_create_type_error +NODE_API_EXTERN node_api_status +napi_create_range_error(node_api_env env, + node_api_value code, + node_api_value msg, + node_api_value* result); +#define node_api_create_range_error napi_create_range_error + +// Methods to get the native node_api_value from Primitive type +NODE_API_EXTERN node_api_status +napi_typeof(node_api_env env, + node_api_value value, + node_api_valuetype* result); +#define node_api_typeof napi_typeof +NODE_API_EXTERN node_api_status +napi_get_value_double(node_api_env env, + node_api_value value, + double* result); +#define node_api_get_value_double napi_get_value_double +NODE_API_EXTERN node_api_status +napi_get_value_int32(node_api_env env, + node_api_value value, + int32_t* result); +#define node_api_get_value_int32 napi_get_value_int32 +NODE_API_EXTERN node_api_status +napi_get_value_uint32(node_api_env env, + node_api_value value, + uint32_t* result); +#define node_api_get_value_uint32 napi_get_value_uint32 +NODE_API_EXTERN node_api_status +napi_get_value_int64(node_api_env env, node_api_value value, int64_t* result); +#define node_api_get_value_int64 napi_get_value_int64 +NODE_API_EXTERN node_api_status +napi_get_value_bool(node_api_env env, node_api_value value, bool* result); +#define node_api_get_value_bool napi_get_value_bool // Copies LATIN-1 encoded bytes from a string into a buffer. -NAPI_EXTERN napi_status napi_get_value_string_latin1(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result); +NODE_API_EXTERN node_api_status +napi_get_value_string_latin1(node_api_env env, + node_api_value value, + char* buf, + size_t bufsize, + size_t* result); +#define node_api_get_value_string_latin1 napi_get_value_string_latin1 // Copies UTF-8 encoded bytes from a string into a buffer. -NAPI_EXTERN napi_status napi_get_value_string_utf8(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result); +NODE_API_EXTERN node_api_status +napi_get_value_string_utf8(node_api_env env, + node_api_value value, + char* buf, + size_t bufsize, + size_t* result); +#define node_api_get_value_string_utf8 napi_get_value_string_utf8 // Copies UTF-16 encoded bytes from a string into a buffer. -NAPI_EXTERN napi_status napi_get_value_string_utf16(napi_env env, - napi_value value, - char16_t* buf, - size_t bufsize, - size_t* result); +NODE_API_EXTERN node_api_status +napi_get_value_string_utf16(node_api_env env, + node_api_value value, + char16_t* buf, + size_t bufsize, + size_t* result); +#define node_api_get_value_string_utf16 napi_get_value_string_utf16 // Methods to coerce values // These APIs may execute user scripts -NAPI_EXTERN napi_status napi_coerce_to_bool(napi_env env, - napi_value value, - napi_value* result); -NAPI_EXTERN napi_status napi_coerce_to_number(napi_env env, - napi_value value, - napi_value* result); -NAPI_EXTERN napi_status napi_coerce_to_object(napi_env env, - napi_value value, - napi_value* result); -NAPI_EXTERN napi_status napi_coerce_to_string(napi_env env, - napi_value value, - napi_value* result); +NODE_API_EXTERN node_api_status +napi_coerce_to_bool(node_api_env env, + node_api_value value, + node_api_value* result); +#define node_api_coerce_to_bool napi_coerce_to_bool +NODE_API_EXTERN node_api_status +napi_coerce_to_number(node_api_env env, + node_api_value value, + node_api_value* result); +#define node_api_coerce_to_number napi_coerce_to_number +NODE_API_EXTERN +node_api_status napi_coerce_to_object(node_api_env env, + node_api_value value, + node_api_value* result); +#define node_api_coerce_to_object napi_coerce_to_object +NODE_API_EXTERN node_api_status +napi_coerce_to_string(node_api_env env, + node_api_value value, + node_api_value* result); +#define node_api_coerce_to_string napi_coerce_to_string // Methods to work with Objects -NAPI_EXTERN napi_status napi_get_prototype(napi_env env, - napi_value object, - napi_value* result); -NAPI_EXTERN napi_status napi_get_property_names(napi_env env, - napi_value object, - napi_value* result); -NAPI_EXTERN napi_status napi_set_property(napi_env env, - napi_value object, - napi_value key, - napi_value value); -NAPI_EXTERN napi_status napi_has_property(napi_env env, - napi_value object, - napi_value key, - bool* result); -NAPI_EXTERN napi_status napi_get_property(napi_env env, - napi_value object, - napi_value key, - napi_value* result); -NAPI_EXTERN napi_status napi_delete_property(napi_env env, - napi_value object, - napi_value key, - bool* result); -NAPI_EXTERN napi_status napi_has_own_property(napi_env env, - napi_value object, - napi_value key, - bool* result); -NAPI_EXTERN napi_status napi_set_named_property(napi_env env, - napi_value object, - const char* utf8name, - napi_value value); -NAPI_EXTERN napi_status napi_has_named_property(napi_env env, - napi_value object, - const char* utf8name, - bool* result); -NAPI_EXTERN napi_status napi_get_named_property(napi_env env, - napi_value object, - const char* utf8name, - napi_value* result); -NAPI_EXTERN napi_status napi_set_element(napi_env env, - napi_value object, - uint32_t index, - napi_value value); -NAPI_EXTERN napi_status napi_has_element(napi_env env, - napi_value object, - uint32_t index, - bool* result); -NAPI_EXTERN napi_status napi_get_element(napi_env env, - napi_value object, - uint32_t index, - napi_value* result); -NAPI_EXTERN napi_status napi_delete_element(napi_env env, - napi_value object, - uint32_t index, - bool* result); -NAPI_EXTERN napi_status -napi_define_properties(napi_env env, - napi_value object, +NODE_API_EXTERN node_api_status +napi_get_prototype(node_api_env env, + node_api_value object, + node_api_value* result); +#define node_api_get_prototype napi_get_prototype +NODE_API_EXTERN node_api_status +napi_get_property_names(node_api_env env, + node_api_value object, + node_api_value* result); +#define node_api_get_property_names napi_get_property_names +NODE_API_EXTERN node_api_status +napi_set_property(node_api_env env, + node_api_value object, + node_api_value key, + node_api_value value); +#define node_api_set_property napi_set_property +NODE_API_EXTERN node_api_status +napi_has_property(node_api_env env, + node_api_value object, + node_api_value key, + bool* result); +#define node_api_has_property napi_has_property +NODE_API_EXTERN node_api_status +napi_get_property(node_api_env env, + node_api_value object, + node_api_value key, + node_api_value* result); +#define node_api_get_property napi_get_property +NODE_API_EXTERN node_api_status +napi_delete_property(node_api_env env, + node_api_value object, + node_api_value key, + bool* result); +#define node_api_delete_property napi_delete_property +NODE_API_EXTERN node_api_status +napi_has_own_property(node_api_env env, + node_api_value object, + node_api_value key, + bool* result); +#define node_api_has_own_property napi_has_own_property +NODE_API_EXTERN node_api_status +napi_set_named_property(node_api_env env, + node_api_value object, + const char* utf8name, + node_api_value value); +#define node_api_set_named_property napi_set_named_property +NODE_API_EXTERN node_api_status +napi_has_named_property(node_api_env env, + node_api_value object, + const char* utf8name, + bool* result); +#define node_api_has_named_property napi_has_named_property +NODE_API_EXTERN node_api_status +napi_get_named_property(node_api_env env, + node_api_value object, + const char* utf8name, + node_api_value* result); +#define node_api_get_named_property napi_get_named_property +NODE_API_EXTERN node_api_status +napi_set_element(node_api_env env, + node_api_value object, + uint32_t index, + node_api_value value); +#define node_api_set_element napi_set_element +NODE_API_EXTERN node_api_status +napi_has_element(node_api_env env, + node_api_value object, + uint32_t index, + bool* result); +#define node_api_has_element napi_has_element +NODE_API_EXTERN node_api_status +napi_get_element(node_api_env env, + node_api_value object, + uint32_t index, + node_api_value* result); +#define node_api_get_element napi_get_element +NODE_API_EXTERN node_api_status +napi_delete_element(node_api_env env, + node_api_value object, + uint32_t index, + bool* result); +#define node_api_delete_element napi_delete_element +NODE_API_EXTERN node_api_status +napi_define_properties(node_api_env env, + node_api_value object, size_t property_count, - const napi_property_descriptor* properties); + const node_api_property_descriptor* properties); +#define node_api_define_properties napi_define_properties // Methods to work with Arrays -NAPI_EXTERN napi_status napi_is_array(napi_env env, - napi_value value, - bool* result); -NAPI_EXTERN napi_status napi_get_array_length(napi_env env, - napi_value value, - uint32_t* result); +NODE_API_EXTERN node_api_status +napi_is_array(node_api_env env, + node_api_value value, + bool* result); +#define node_api_is_array napi_is_array +NODE_API_EXTERN node_api_status +napi_get_array_length(node_api_env env, + node_api_value value, + uint32_t* result); +#define node_api_get_array_length napi_get_array_length // Methods to compare values -NAPI_EXTERN napi_status napi_strict_equals(napi_env env, - napi_value lhs, - napi_value rhs, - bool* result); +NODE_API_EXTERN node_api_status +napi_strict_equals(node_api_env env, + node_api_value lhs, + node_api_value rhs, + bool* result); +#define node_api_strict_equals napi_strict_equals // Methods to work with Functions -NAPI_EXTERN napi_status napi_call_function(napi_env env, - napi_value recv, - napi_value func, - size_t argc, - const napi_value* argv, - napi_value* result); -NAPI_EXTERN napi_status napi_new_instance(napi_env env, - napi_value constructor, - size_t argc, - const napi_value* argv, - napi_value* result); -NAPI_EXTERN napi_status napi_instanceof(napi_env env, - napi_value object, - napi_value constructor, - bool* result); - -// Methods to work with napi_callbacks +NODE_API_EXTERN node_api_status +napi_call_function(node_api_env env, + node_api_value recv, + node_api_value func, + size_t argc, + const node_api_value* argv, + node_api_value* result); +#define node_api_call_function napi_call_function +NODE_API_EXTERN node_api_status +napi_new_instance(node_api_env env, + node_api_value constructor, + size_t argc, + const node_api_value* argv, + node_api_value* result); +#define node_api_new_instance napi_new_instance +NODE_API_EXTERN node_api_status +napi_instanceof(node_api_env env, + node_api_value object, + node_api_value constructor, + bool* result); +#define node_api_instanceof napi_instanceof + +// Methods to work with node_api_callbacks // Gets all callback info in a single call. (Ugly, but faster.) -NAPI_EXTERN napi_status napi_get_cb_info( - napi_env env, // [in] NAPI environment handle - napi_callback_info cbinfo, // [in] Opaque callback-info handle - size_t* argc, // [in-out] Specifies the size of the provided argv array - // and receives the actual count of args. - napi_value* argv, // [out] Array of values - napi_value* this_arg, // [out] Receives the JS 'this' arg for the call +NODE_API_EXTERN node_api_status napi_get_cb_info( + node_api_env env, // [in] NAPI environment handle + node_api_callback_info cbinfo, // [in] Opaque callback-info handle + size_t* argc, // [in-out] Specifies the size of the provided argv array + // and receives the actual count of args. + node_api_value* argv, // [out] Array of values + node_api_value* this_arg, // [out] Receives the JS 'this' arg for the call void** data); // [out] Receives the data pointer for the callback. +#define node_api_get_cb_info napi_get_cb_info -NAPI_EXTERN napi_status napi_get_new_target(napi_env env, - napi_callback_info cbinfo, - napi_value* result); -NAPI_EXTERN napi_status -napi_define_class(napi_env env, +NODE_API_EXTERN node_api_status +napi_get_new_target(node_api_env env, + node_api_callback_info cbinfo, + node_api_value* result); +#define node_api_get_new_target napi_get_new_target +NODE_API_EXTERN node_api_status +napi_define_class(node_api_env env, const char* utf8name, size_t length, - napi_callback constructor, + node_api_callback constructor, void* data, size_t property_count, - const napi_property_descriptor* properties, - napi_value* result); + const node_api_property_descriptor* properties, + node_api_value* result); +#define node_api_define_class napi_define_class // Methods to work with external data objects -NAPI_EXTERN napi_status napi_wrap(napi_env env, - napi_value js_object, - void* native_object, - napi_finalize finalize_cb, - void* finalize_hint, - napi_ref* result); -NAPI_EXTERN napi_status napi_unwrap(napi_env env, - napi_value js_object, - void** result); -NAPI_EXTERN napi_status napi_remove_wrap(napi_env env, - napi_value js_object, - void** result); -NAPI_EXTERN napi_status napi_create_external(napi_env env, - void* data, - napi_finalize finalize_cb, - void* finalize_hint, - napi_value* result); -NAPI_EXTERN napi_status napi_get_value_external(napi_env env, - napi_value value, - void** result); +NODE_API_EXTERN node_api_status +napi_wrap(node_api_env env, + node_api_value js_object, + void* native_object, + node_api_finalize finalize_cb, + void* finalize_hint, + node_api_ref* result); +#define node_api_wrap napi_wrap +NODE_API_EXTERN node_api_status +napi_unwrap(node_api_env env, node_api_value js_object, void** result); +#define node_api_unwrap napi_unwrap +NODE_API_EXTERN node_api_status +napi_remove_wrap(node_api_env env, + node_api_value js_object, + void** result); +#define node_api_remove_wrap napi_remove_wrap +NODE_API_EXTERN node_api_status +napi_create_external(node_api_env env, + void* data, + node_api_finalize finalize_cb, + void* finalize_hint, + node_api_value* result); +#define node_api_create_external napi_create_external +NODE_API_EXTERN node_api_status +napi_get_value_external(node_api_env env, + node_api_value value, + void** result); +#define node_api_get_value_external napi_get_value_external // Methods to control object lifespan // Set initial_refcount to 0 for a weak reference, >0 for a strong reference. -NAPI_EXTERN napi_status napi_create_reference(napi_env env, - napi_value value, - uint32_t initial_refcount, - napi_ref* result); +NODE_API_EXTERN node_api_status +napi_create_reference(node_api_env env, + node_api_value value, + uint32_t initial_refcount, + node_api_ref* result); +#define node_api_create_reference napi_create_reference // Deletes a reference. The referenced value is released, and may // be GC'd unless there are other references to it. -NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref); +NODE_API_EXTERN node_api_status +napi_delete_reference(node_api_env env, node_api_ref ref); +#define node_api_delete_reference napi_delete_reference // Increments the reference count, optionally returning the resulting count. // After this call the reference will be a strong reference because its // refcount is >0, and the referenced object is effectively "pinned". // Calling this when the refcount is 0 and the object is unavailable // results in an error. -NAPI_EXTERN napi_status napi_reference_ref(napi_env env, - napi_ref ref, - uint32_t* result); +NODE_API_EXTERN node_api_status +napi_reference_ref(node_api_env env, + node_api_ref ref, + uint32_t* result); +#define node_api_reference_ref napi_reference_ref // Decrements the reference count, optionally returning the resulting count. // If the result is 0 the reference is now weak and the object may be GC'd // at any time if there are no other references. Calling this when the // refcount is already 0 results in an error. -NAPI_EXTERN napi_status napi_reference_unref(napi_env env, - napi_ref ref, - uint32_t* result); +NODE_API_EXTERN node_api_status +napi_reference_unref(node_api_env env, + node_api_ref ref, + uint32_t* result); +#define node_api_reference_unref napi_reference_unref // Attempts to get a referenced value. If the reference is weak, // the value might no longer be available, in that case the call // is still successful but the result is NULL. -NAPI_EXTERN napi_status napi_get_reference_value(napi_env env, - napi_ref ref, - napi_value* result); - -NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env, - napi_handle_scope* result); -NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env, - napi_handle_scope scope); -NAPI_EXTERN napi_status -napi_open_escapable_handle_scope(napi_env env, - napi_escapable_handle_scope* result); -NAPI_EXTERN napi_status -napi_close_escapable_handle_scope(napi_env env, - napi_escapable_handle_scope scope); - -NAPI_EXTERN napi_status napi_escape_handle(napi_env env, - napi_escapable_handle_scope scope, - napi_value escapee, - napi_value* result); +NODE_API_EXTERN node_api_status +napi_get_reference_value(node_api_env env, + node_api_ref ref, + node_api_value* result); +#define node_api_get_reference_value napi_get_reference_value + +NODE_API_EXTERN node_api_status +napi_open_handle_scope(node_api_env env, + node_api_handle_scope* result); +#define node_api_open_handle_scope napi_open_handle_scope +NODE_API_EXTERN node_api_status +napi_close_handle_scope(node_api_env env, + node_api_handle_scope scope); +#define node_api_close_handle_scope napi_close_handle_scope + +NODE_API_EXTERN node_api_status +napi_open_escapable_handle_scope(node_api_env env, + node_api_escapable_handle_scope* result); +#define node_api_open_escapable_handle_scope napi_open_escapable_handle_scope +NODE_API_EXTERN node_api_status +napi_close_escapable_handle_scope(node_api_env env, + node_api_escapable_handle_scope scope); +#define node_api_close_escapable_handle_scope napi_close_escapable_handle_scope + +NODE_API_EXTERN node_api_status +napi_escape_handle(node_api_env env, + node_api_escapable_handle_scope scope, + node_api_value escapee, + node_api_value* result); +#define node_api_escape_handle napi_escape_handle // Methods to support error handling -NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error); -NAPI_EXTERN napi_status napi_throw_error(napi_env env, - const char* code, - const char* msg); -NAPI_EXTERN napi_status napi_throw_type_error(napi_env env, - const char* code, - const char* msg); -NAPI_EXTERN napi_status napi_throw_range_error(napi_env env, - const char* code, - const char* msg); -NAPI_EXTERN napi_status napi_is_error(napi_env env, - napi_value value, - bool* result); +NODE_API_EXTERN node_api_status +napi_throw(node_api_env env, node_api_value error); +#define node_api_throw napi_throw +NODE_API_EXTERN node_api_status +napi_throw_error(node_api_env env, + const char* code, + const char* msg); +#define node_api_throw_error napi_throw_error +NODE_API_EXTERN node_api_status +napi_throw_type_error(node_api_env env, + const char* code, + const char* msg); +#define node_api_throw_type_error napi_throw_type_error +NODE_API_EXTERN node_api_status +napi_throw_range_error(node_api_env env, + const char* code, + const char* msg); +#define node_api_throw_range_error napi_throw_range_error +NODE_API_EXTERN node_api_status napi_is_error(node_api_env env, + node_api_value value, + bool* result); +#define node_api_is_error napi_is_error // Methods to support catching exceptions -NAPI_EXTERN napi_status napi_is_exception_pending(napi_env env, bool* result); -NAPI_EXTERN napi_status napi_get_and_clear_last_exception(napi_env env, - napi_value* result); +NODE_API_EXTERN node_api_status +napi_is_exception_pending(node_api_env env, bool* result); +#define node_api_is_exception_pending napi_is_exception_pending +NODE_API_EXTERN node_api_status +napi_get_and_clear_last_exception(node_api_env env, + node_api_value* result); +#define node_api_get_and_clear_last_exception napi_get_and_clear_last_exception // Methods to work with array buffers and typed arrays -NAPI_EXTERN napi_status napi_is_arraybuffer(napi_env env, - napi_value value, - bool* result); -NAPI_EXTERN napi_status napi_create_arraybuffer(napi_env env, - size_t byte_length, - void** data, - napi_value* result); -NAPI_EXTERN napi_status -napi_create_external_arraybuffer(napi_env env, +NODE_API_EXTERN node_api_status +napi_is_arraybuffer(node_api_env env, + node_api_value value, + bool* result); +#define node_api_is_arraybuffer napi_is_arraybuffer +NODE_API_EXTERN node_api_status +napi_create_arraybuffer(node_api_env env, + size_t byte_length, + void** data, + node_api_value* result); +#define node_api_create_arraybuffer napi_create_arraybuffer +NODE_API_EXTERN node_api_status +napi_create_external_arraybuffer(node_api_env env, void* external_data, size_t byte_length, - napi_finalize finalize_cb, + node_api_finalize finalize_cb, void* finalize_hint, - napi_value* result); -NAPI_EXTERN napi_status napi_get_arraybuffer_info(napi_env env, - napi_value arraybuffer, - void** data, - size_t* byte_length); -NAPI_EXTERN napi_status napi_is_typedarray(napi_env env, - napi_value value, - bool* result); -NAPI_EXTERN napi_status napi_create_typedarray(napi_env env, - napi_typedarray_type type, - size_t length, - napi_value arraybuffer, - size_t byte_offset, - napi_value* result); -NAPI_EXTERN napi_status napi_get_typedarray_info(napi_env env, - napi_value typedarray, - napi_typedarray_type* type, - size_t* length, - void** data, - napi_value* arraybuffer, - size_t* byte_offset); - -NAPI_EXTERN napi_status napi_create_dataview(napi_env env, - size_t length, - napi_value arraybuffer, - size_t byte_offset, - napi_value* result); -NAPI_EXTERN napi_status napi_is_dataview(napi_env env, - napi_value value, - bool* result); -NAPI_EXTERN napi_status napi_get_dataview_info(napi_env env, - napi_value dataview, - size_t* bytelength, - void** data, - napi_value* arraybuffer, - size_t* byte_offset); + node_api_value* result); +#define node_api_create_external_arraybuffer napi_create_external_arraybuffer + +NODE_API_EXTERN node_api_status +napi_get_arraybuffer_info(node_api_env env, + node_api_value arraybuffer, + void** data, + size_t* byte_length); +#define node_api_get_arraybuffer_info napi_get_arraybuffer_info +NODE_API_EXTERN node_api_status +napi_is_typedarray(node_api_env env, node_api_value value, bool* result); +#define node_api_is_typedarray napi_is_typedarray +NODE_API_EXTERN node_api_status +napi_create_typedarray(node_api_env env, + node_api_typedarray_type type, + size_t length, + node_api_value arraybuffer, + size_t byte_offset, + node_api_value* result); +#define node_api_create_typedarray napi_create_typedarray +NODE_API_EXTERN node_api_status +napi_get_typedarray_info(node_api_env env, + node_api_value typedarray, + napi_typedarray_type* type, + size_t* length, + void** data, + node_api_value* arraybuffer, + size_t* byte_offset); +#define node_api_get_typedarray_info napi_get_typedarray_info + +NODE_API_EXTERN node_api_status +napi_create_dataview(node_api_env env, + size_t length, + node_api_value arraybuffer, + size_t byte_offset, + node_api_value* result); +#define node_api_create_dataview napi_create_dataview +NODE_API_EXTERN node_api_status +napi_is_dataview(node_api_env env, + node_api_value value, + bool* result); +#define node_api_is_dataview napi_is_dataview +NODE_API_EXTERN node_api_status +napi_get_dataview_info(node_api_env env, + node_api_value dataview, + size_t* bytelength, + void** data, + node_api_value* arraybuffer, + size_t* byte_offset); +#define node_api_get_dataview_info napi_get_dataview_info // version management -NAPI_EXTERN napi_status napi_get_version(napi_env env, uint32_t* result); +NODE_API_EXTERN node_api_status +napi_get_version(node_api_env env, uint32_t* result); +#define node_api_get_version napi_get_version // Promises -NAPI_EXTERN napi_status napi_create_promise(napi_env env, - napi_deferred* deferred, - napi_value* promise); -NAPI_EXTERN napi_status napi_resolve_deferred(napi_env env, - napi_deferred deferred, - napi_value resolution); -NAPI_EXTERN napi_status napi_reject_deferred(napi_env env, - napi_deferred deferred, - napi_value rejection); -NAPI_EXTERN napi_status napi_is_promise(napi_env env, - napi_value value, - bool* is_promise); +NODE_API_EXTERN node_api_status +napi_create_promise(node_api_env env, + node_api_deferred* deferred, + node_api_value* promise); +#define node_api_create_promise napi_create_promise +NODE_API_EXTERN node_api_status +napi_resolve_deferred(node_api_env env, + node_api_deferred deferred, + node_api_value resolution); +#define node_api_resolve_deferred napi_resolve_deferred +NODE_API_EXTERN node_api_status +napi_reject_deferred(node_api_env env, + node_api_deferred deferred, + node_api_value rejection); +#define node_api_reject_deferred napi_reject_deferred +NODE_API_EXTERN node_api_status +napi_is_promise(node_api_env env, + node_api_value value, + bool* is_promise); +#define node_api_is_promise napi_is_promise // Running a script -NAPI_EXTERN napi_status napi_run_script(napi_env env, - napi_value script, - napi_value* result); +NODE_API_EXTERN node_api_status +napi_run_script(node_api_env env, + node_api_value script, + node_api_value* result); +#define node_api_run_script napi_run_script // Memory management -NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env, - int64_t change_in_bytes, - int64_t* adjusted_value); +NODE_API_EXTERN node_api_status +napi_adjust_external_memory(node_api_env env, + int64_t change_in_bytes, + int64_t* adjusted_value); +#define node_api_adjust_external_memory napi_adjust_external_memory #if NAPI_VERSION >= 5 // Dates -NAPI_EXTERN napi_status napi_create_date(napi_env env, - double time, - napi_value* result); +NODE_API_EXTERN node_api_status +napi_create_date(node_api_env env, double time, node_api_value* result); +#define node_api_create_date napi_create_date -NAPI_EXTERN napi_status napi_is_date(napi_env env, - napi_value value, - bool* is_date); +NODE_API_EXTERN node_api_status +napi_is_date(node_api_env env, node_api_value value, bool* is_date); +#define node_api_is_date napi_is_date -NAPI_EXTERN napi_status napi_get_date_value(napi_env env, - napi_value value, - double* result); +NODE_API_EXTERN node_api_status +napi_get_date_value(node_api_env env, node_api_value value, double* result); +#define node_api_get_date_value napi_get_date_value // Add finalizer for pointer -NAPI_EXTERN napi_status napi_add_finalizer(napi_env env, - napi_value js_object, - void* native_object, - napi_finalize finalize_cb, - void* finalize_hint, - napi_ref* result); +NODE_API_EXTERN node_api_status +napi_add_finalizer(node_api_env env, + node_api_value js_object, + void* native_object, + napi_finalize finalize_cb, + void* finalize_hint, + napi_ref* result); +#define node_api_add_finalizer napi_add_finalizer #endif // NAPI_VERSION >= 5 #if NAPI_VERSION >= 6 // BigInt -NAPI_EXTERN napi_status napi_create_bigint_int64(napi_env env, - int64_t value, - napi_value* result); -NAPI_EXTERN napi_status napi_create_bigint_uint64(napi_env env, - uint64_t value, - napi_value* result); -NAPI_EXTERN napi_status napi_create_bigint_words(napi_env env, - int sign_bit, - size_t word_count, - const uint64_t* words, - napi_value* result); -NAPI_EXTERN napi_status napi_get_value_bigint_int64(napi_env env, - napi_value value, - int64_t* result, - bool* lossless); -NAPI_EXTERN napi_status napi_get_value_bigint_uint64(napi_env env, - napi_value value, - uint64_t* result, - bool* lossless); -NAPI_EXTERN napi_status napi_get_value_bigint_words(napi_env env, - napi_value value, - int* sign_bit, - size_t* word_count, - uint64_t* words); +NODE_API_EXTERN node_api_status +napi_create_bigint_int64(node_api_env env, + int64_t value, + node_api_value* result); +#define node_api_create_bigint_int64 napi_create_bigint_int64 +NODE_API_EXTERN node_api_status +napi_create_bigint_uint64(node_api_env env, + uint64_t value, + node_api_value* result); +#define node_api_create_bigint_uint64 napi_create_bigint_uint64 +NODE_API_EXTERN node_api_status +napi_create_bigint_words(node_api_env env, + int sign_bit, + size_t word_count, + const uint64_t* words, + node_api_value* result); +#define node_api_create_bigint_words napi_create_bigint_words +NODE_API_EXTERN node_api_status +napi_get_value_bigint_int64(node_api_env env, + node_api_value value, + int64_t* result, + bool* lossless); +#define node_api_get_value_bigint_int64 napi_get_value_bigint_int64 +NODE_API_EXTERN node_api_status +napi_get_value_bigint_uint64(node_api_env env, + node_api_value value, + uint64_t* result, + bool* lossless); +#define node_api_get_value_bigint_uint64 napi_get_value_bigint_uint64 +NODE_API_EXTERN node_api_status +napi_get_value_bigint_words(node_api_env env, + node_api_value value, + int* sign_bit, + size_t* word_count, + uint64_t* words); +#define node_api_get_value_bigint_words napi_get_value_bigint_words // Object -NAPI_EXTERN napi_status -napi_get_all_property_names(napi_env env, - napi_value object, - napi_key_collection_mode key_mode, - napi_key_filter key_filter, - napi_key_conversion key_conversion, - napi_value* result); +NODE_API_EXTERN node_api_status +napi_get_all_property_names(node_api_env env, + node_api_value object, + node_api_key_collection_mode key_mode, + node_api_key_filter key_filter, + node_api_key_conversion key_conversion, + node_api_value* result); +#define node_api_get_all_property_names napi_get_all_property_names // Instance data -NAPI_EXTERN napi_status napi_set_instance_data(napi_env env, - void* data, - napi_finalize finalize_cb, - void* finalize_hint); +NODE_API_EXTERN node_api_status +napi_set_instance_data(node_api_env env, + void* data, + node_api_finalize finalize_cb, + void* finalize_hint); +#define node_api_set_instance_data napi_set_instance_data -NAPI_EXTERN napi_status napi_get_instance_data(napi_env env, - void** data); +NODE_API_EXTERN node_api_status +napi_get_instance_data(node_api_env env, void** data); +#define node_api_get_instance_data napi_get_instance_data #endif // NAPI_VERSION >= 6 #if NAPI_VERSION >= 7 // ArrayBuffer detaching -NAPI_EXTERN napi_status napi_detach_arraybuffer(napi_env env, - napi_value arraybuffer); +NODE_API_EXTERN node_api_status +napi_detach_arraybuffer(node_api_env env, node_api_value arraybuffer); +#define node_api_detach_arraybuffer napi_detach_arraybuffer -NAPI_EXTERN napi_status napi_is_detached_arraybuffer(napi_env env, - napi_value value, - bool* result); +NODE_API_EXTERN node_api_status +napi_is_detached_arraybuffer(node_api_env env, + node_api_value value, + bool* result); +#define node_api_is_detached_arraybuffer napi_is_detached_arraybuffer #endif // NAPI_VERSION >= 7 -#ifdef NAPI_EXPERIMENTAL +#if defined(NAPI_EXPERIMENTAL) || defined(NODE_API_EXPERIMENTAL) // Type tagging -NAPI_EXTERN napi_status napi_type_tag_object(napi_env env, - napi_value value, - const napi_type_tag* type_tag); - -NAPI_EXTERN napi_status -napi_check_object_type_tag(napi_env env, - napi_value value, - const napi_type_tag* type_tag, +NODE_API_EXTERN node_api_status +napi_type_tag_object(node_api_env env, + node_api_value value, + const node_api_type_tag* type_tag); +#define node_api_type_tag_object napi_type_tag_object + +NODE_API_EXTERN node_api_status +napi_check_object_type_tag(node_api_env env, + node_api_value value, + const node_api_type_tag* type_tag, bool* result); -NAPI_EXTERN napi_status napi_object_freeze(napi_env env, - napi_value object); -NAPI_EXTERN napi_status napi_object_seal(napi_env env, - napi_value object); +#define node_api_check_object_type_tag napi_check_object_type_tag +NODE_API_EXTERN node_api_status +napi_object_freeze(node_api_env env, node_api_value object); +#define node_api_object_freeze napi_object_freeze +NODE_API_EXTERN node_api_status +napi_object_seal(node_api_env env, node_api_value object); +#define node_api_object_seal napi_object_seal #endif // NAPI_EXPERIMENTAL EXTERN_C_END diff --git a/src/js_native_api_types.h b/src/js_native_api_types.h index 455ee5efdb5456..188020031e9d35 100644 --- a/src/js_native_api_types.h +++ b/src/js_native_api_types.h @@ -20,7 +20,7 @@ typedef struct napi_handle_scope__* napi_handle_scope; typedef struct napi_escapable_handle_scope__* napi_escapable_handle_scope; typedef struct napi_callback_info__* napi_callback_info; typedef struct napi_deferred__* napi_deferred; -#define node_api_env napi_env +#define node_api_env napi_env #define node_api_value napi_value #define node_api_ref napi_ref #define node_api_handle_scope napi_handle_scope @@ -80,9 +80,9 @@ typedef enum { #define node_api_symbol napi_symbol #define node_api_object napi_object #define node_api_function napi_function -#define napi_external, -#define napi_bigint, -#define napi_valuetype; +#define node_api_external napi_external +#define node_api_bigint napi_bigint +#define node_api_valuetype napi_valuetype typedef enum { napi_int8_array, @@ -232,12 +232,12 @@ typedef enum { #define node_api_key_conversion napi_key_conversion #endif // NAPI_VERSION >= 6 -#ifdef NAPI_EXPERIMENTAL +#if defined(NAPI_EXPERIMENTAL) || defined(NODE_API_EXPERIMENTAL) typedef struct { uint64_t lower; uint64_t upper; } napi_type_tag; #define node_api_type_tag napi_type_tag -#endif // NAPI_EXPERIMENTAL +#endif // NAPI_EXPERIMENTAL || NODE_API_EXPERIMENTAL #endif // SRC_JS_NATIVE_API_TYPES_H_ diff --git a/src/node_api.h b/src/node_api.h index 52d1bbdafd40e5..6a5386c54f9a49 100644 --- a/src/node_api.h +++ b/src/node_api.h @@ -121,6 +121,7 @@ typedef struct napi_module { NODE_API_MODULE(NODE_GYP_MODULE_NAME, NODE_API_MODULE_INITIALIZER) \ node_api_value NODE_API_MODULE_INITIALIZER(node_api_env env, \ node_api_value exports) +#define NODE_API_MODULE_INIT NAPI_MODULE_INIT EXTERN_C_START @@ -174,7 +175,7 @@ napi_create_buffer_copy(node_api_env env, const void* data, void** result_data, node_api_value* result); -#define node_api_create_buffer napi_create_buffer +#define node_api_create_buffer_copy napi_create_buffer_copy NODE_API_EXTERN node_api_status napi_is_buffer(node_api_env env, node_api_value value, @@ -303,7 +304,7 @@ napi_ref_threadsafe_function(node_api_env env, #endif // NAPI_VERSION >= 4 -#ifdef NAPI_EXPERIMENTAL +#if defined(NAPI_EXPERIMENTAL) || defined(NODE_API_EXPERIMENTAL) NODE_API_EXTERN node_api_status napi_add_async_cleanup_hook( node_api_env env, @@ -316,7 +317,7 @@ NODE_API_EXTERN node_api_status napi_remove_async_cleanup_hook( node_api_async_cleanup_hook_handle remove_handle); #define node_api_remove_async_cleanup_hook napi_remove_async_cleanup_hook -#endif // NAPI_EXPERIMENTAL +#endif // NAPI_EXPERIMENTAL || NODE_API_EXPERIMENTAL EXTERN_C_END diff --git a/src/node_api_types.h b/src/node_api_types.h index 10ccfb08e5af4d..d7a23c3abc15f1 100644 --- a/src/node_api_types.h +++ b/src/node_api_types.h @@ -22,7 +22,7 @@ typedef enum { #define node_api_tsfn_release napi_tsfn_release #define node_api_tsfn_abort napi_tsfn_abort #define node_api_threadsafe_function_release_mode \ - napi_threadsafe_function_release_mode + napi_threadsafe_function_release_mode typedef enum { napi_tsfn_nonblocking, napi_tsfn_blocking @@ -56,13 +56,13 @@ typedef struct { } napi_node_version; #define node_api_node_version napi_node_version -#ifdef NAPI_EXPERIMENTAL +#if defined(NAPI_EXPERIMENTAL) || defined(NODE_API_EXPERIMENTAL) typedef struct napi_async_cleanup_hook_handle__* napi_async_cleanup_hook_handle; #define node_api_async_cleanup_hook_handle napi_async_cleanup_hook_handle typedef void (*napi_async_cleanup_hook)( node_api_async_cleanup_hook_handle handle, void* data); #define node_api_async_cleanup_hook napi_async_cleanup_hook -#endif // NAPI_EXPERIMENTAL +#endif // NAPI_EXPERIMENTAL || NODE_API_EXPERIMENTAL #endif // SRC_NODE_API_TYPES_H_ diff --git a/test/js-native-api/2_function_arguments/binding.c b/test/js-native-api/2_function_arguments/binding.c index c9f2d03c7d2117..f799b01a15e20c 100644 --- a/test/js-native-api/2_function_arguments/binding.c +++ b/test/js-native-api/2_function_arguments/binding.c @@ -1,38 +1,39 @@ #include #include "../common.h" -static napi_value Add(napi_env env, napi_callback_info info) { +static node_api_value Add(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 2, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 2, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + node_api_valuetype valuetype1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); - NAPI_ASSERT(env, valuetype0 == napi_number && valuetype1 == napi_number, + NODE_API_ASSERT(env, + valuetype0 == node_api_number && valuetype1 == node_api_number, "Wrong argument type. Numbers expected."); double value0; - NAPI_CALL(env, napi_get_value_double(env, args[0], &value0)); + NODE_API_CALL(env, node_api_get_value_double(env, args[0], &value0)); double value1; - NAPI_CALL(env, napi_get_value_double(env, args[1], &value1)); + NODE_API_CALL(env, node_api_get_value_double(env, args[1], &value1)); - napi_value sum; - NAPI_CALL(env, napi_create_double(env, value0 + value1, &sum)); + node_api_value sum; + NODE_API_CALL(env, node_api_create_double(env, value0 + value1, &sum)); return sum; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor desc = DECLARE_NAPI_PROPERTY("add", Add); - NAPI_CALL(env, napi_define_properties(env, exports, 1, &desc)); +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor desc = DECLARE_NODE_API_PROPERTY("add", Add); + NODE_API_CALL(env, node_api_define_properties(env, exports, 1, &desc)); return exports; } EXTERN_C_END diff --git a/test/js-native-api/3_callbacks/binding.c b/test/js-native-api/3_callbacks/binding.c index 5384fb1fc569b0..2e7628def6aa3c 100644 --- a/test/js-native-api/3_callbacks/binding.c +++ b/test/js-native-api/3_callbacks/binding.c @@ -2,56 +2,58 @@ #include "../common.h" #include -static napi_value RunCallback(napi_env env, napi_callback_info info) { +static node_api_value +RunCallback(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments. Expects a single argument."); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_function, + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); + NODE_API_ASSERT(env, valuetype0 == node_api_function, "Wrong type of arguments. Expects a function as first argument."); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); - NAPI_ASSERT(env, valuetype1 == napi_undefined, + node_api_valuetype valuetype1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); + NODE_API_ASSERT(env, valuetype1 == node_api_undefined, "Additional arguments should be undefined."); - napi_value argv[1]; + node_api_value argv[1]; const char* str = "hello world"; size_t str_len = strlen(str); - NAPI_CALL(env, napi_create_string_utf8(env, str, str_len, argv)); + NODE_API_CALL(env, node_api_create_string_utf8(env, str, str_len, argv)); - napi_value global; - NAPI_CALL(env, napi_get_global(env, &global)); + node_api_value global; + NODE_API_CALL(env, node_api_get_global(env, &global)); - napi_value cb = args[0]; - NAPI_CALL(env, napi_call_function(env, global, cb, 1, argv, NULL)); + node_api_value cb = args[0]; + NODE_API_CALL(env, node_api_call_function(env, global, cb, 1, argv, NULL)); return NULL; } -static napi_value RunCallbackWithRecv(napi_env env, napi_callback_info info) { +static node_api_value +RunCallbackWithRecv(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value cb = args[0]; - napi_value recv = args[1]; - NAPI_CALL(env, napi_call_function(env, recv, cb, 0, NULL, NULL)); + node_api_value cb = args[0]; + node_api_value recv = args[1]; + NODE_API_CALL(env, node_api_call_function(env, recv, cb, 0, NULL, NULL)); return NULL; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor desc[2] = { - DECLARE_NAPI_PROPERTY("RunCallback", RunCallback), - DECLARE_NAPI_PROPERTY("RunCallbackWithRecv", RunCallbackWithRecv), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor desc[2] = { + DECLARE_NODE_API_PROPERTY("RunCallback", RunCallback), + DECLARE_NODE_API_PROPERTY("RunCallbackWithRecv", RunCallbackWithRecv), }; - NAPI_CALL(env, napi_define_properties(env, exports, 2, desc)); + NODE_API_CALL(env, node_api_define_properties(env, exports, 2, desc)); return exports; } EXTERN_C_END diff --git a/test/js-native-api/4_object_factory/binding.c b/test/js-native-api/4_object_factory/binding.c index 5e1403a892143a..39e67370527bdd 100644 --- a/test/js-native-api/4_object_factory/binding.c +++ b/test/js-native-api/4_object_factory/binding.c @@ -1,23 +1,28 @@ #include #include "../common.h" -static napi_value CreateObject(napi_env env, napi_callback_info info) { +static node_api_value +CreateObject(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value obj; - NAPI_CALL(env, napi_create_object(env, &obj)); + node_api_value obj; + NODE_API_CALL(env, node_api_create_object(env, &obj)); - NAPI_CALL(env, napi_set_named_property(env, obj, "msg", args[0])); + NODE_API_CALL(env, node_api_set_named_property(env, obj, "msg", args[0])); return obj; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - NAPI_CALL(env, - napi_create_function(env, "exports", -1, CreateObject, NULL, &exports)); +node_api_value Init(node_api_env env, node_api_value exports) { + NODE_API_CALL(env, node_api_create_function(env, + "exports", + NODE_API_AUTO_LENGTH, + CreateObject, + NULL, + &exports)); return exports; } EXTERN_C_END diff --git a/test/js-native-api/5_function_factory/binding.c b/test/js-native-api/5_function_factory/binding.c index 73c6890253d580..7d5ed057f102ee 100644 --- a/test/js-native-api/5_function_factory/binding.c +++ b/test/js-native-api/5_function_factory/binding.c @@ -1,23 +1,30 @@ #include #include "../common.h" -static napi_value MyFunction(napi_env env, napi_callback_info info) { - napi_value str; - NAPI_CALL(env, napi_create_string_utf8(env, "hello world", -1, &str)); +static node_api_value +MyFunction(node_api_env env, node_api_callback_info info) { + node_api_value str; + NODE_API_CALL(env, + node_api_create_string_utf8(env, "hello world", -1, &str)); return str; } -static napi_value CreateFunction(napi_env env, napi_callback_info info) { - napi_value fn; - NAPI_CALL(env, - napi_create_function(env, "theFunction", -1, MyFunction, NULL, &fn)); +static node_api_value +CreateFunction(node_api_env env, node_api_callback_info info) { + node_api_value fn; + NODE_API_CALL(env, + node_api_create_function(env, "theFunction", -1, MyFunction, NULL, &fn)); return fn; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - NAPI_CALL(env, - napi_create_function(env, "exports", -1, CreateFunction, NULL, &exports)); +node_api_value Init(node_api_env env, node_api_value exports) { + NODE_API_CALL(env, node_api_create_function(env, + "exports", + NODE_API_AUTO_LENGTH, + CreateFunction, + NULL, + &exports)); return exports; } EXTERN_C_END diff --git a/test/js-native-api/6_object_wrap/myobject.cc b/test/js-native-api/6_object_wrap/myobject.cc index 30e6b66dcbe4b7..70978897f5b75f 100644 --- a/test/js-native-api/6_object_wrap/myobject.cc +++ b/test/js-native-api/6_object_wrap/myobject.cc @@ -1,160 +1,174 @@ #include "myobject.h" #include "../common.h" -napi_ref MyObject::constructor; +node_api_ref MyObject::constructor; MyObject::MyObject(double value) : value_(value), env_(nullptr), wrapper_(nullptr) {} -MyObject::~MyObject() { napi_delete_reference(env_, wrapper_); } +MyObject::~MyObject() { node_api_delete_reference(env_, wrapper_); } void MyObject::Destructor( - napi_env env, void* nativeObject, void* /*finalize_hint*/) { + node_api_env env, void* nativeObject, void* /*finalize_hint*/) { MyObject* obj = static_cast(nativeObject); delete obj; } -void MyObject::Init(napi_env env, napi_value exports) { - napi_property_descriptor properties[] = { - { "value", nullptr, nullptr, GetValue, SetValue, 0, napi_default, 0 }, - { "valueReadonly", nullptr, nullptr, GetValue, nullptr, 0, napi_default, +void MyObject::Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor properties[] = { + { "value", nullptr, nullptr, GetValue, SetValue, 0, node_api_default, 0 }, + { "valueReadonly", nullptr, nullptr, GetValue, nullptr, 0, node_api_default, 0 }, - DECLARE_NAPI_PROPERTY("plusOne", PlusOne), - DECLARE_NAPI_PROPERTY("multiply", Multiply), + DECLARE_NODE_API_PROPERTY("plusOne", PlusOne), + DECLARE_NODE_API_PROPERTY("multiply", Multiply), }; - napi_value cons; - NAPI_CALL_RETURN_VOID(env, napi_define_class( + node_api_value cons; + NODE_API_CALL_RETURN_VOID(env, node_api_define_class( env, "MyObject", -1, New, nullptr, - sizeof(properties) / sizeof(napi_property_descriptor), + sizeof(properties) / sizeof(node_api_property_descriptor), properties, &cons)); - NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, cons, 1, &constructor)); + NODE_API_CALL_RETURN_VOID(env, + node_api_create_reference(env, cons, 1, &constructor)); - NAPI_CALL_RETURN_VOID(env, - napi_set_named_property(env, exports, "MyObject", cons)); + NODE_API_CALL_RETURN_VOID(env, + node_api_set_named_property(env, exports, "MyObject", cons)); } -napi_value MyObject::New(napi_env env, napi_callback_info info) { - napi_value new_target; - NAPI_CALL(env, napi_get_new_target(env, info, &new_target)); +node_api_value MyObject::New(node_api_env env, node_api_callback_info info) { + node_api_value new_target; + NODE_API_CALL(env, node_api_get_new_target(env, info, &new_target)); bool is_constructor = (new_target != nullptr); size_t argc = 1; - napi_value args[1]; - napi_value _this; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &_this, nullptr)); + node_api_value args[1]; + node_api_value _this; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, args, &_this, nullptr)); if (is_constructor) { // Invoked as constructor: `new MyObject(...)` double value = 0; - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); - if (valuetype != napi_undefined) { - NAPI_CALL(env, napi_get_value_double(env, args[0], &value)); + if (valuetype != node_api_undefined) { + NODE_API_CALL(env, node_api_get_value_double(env, args[0], &value)); } MyObject* obj = new MyObject(value); obj->env_ = env; - NAPI_CALL(env, napi_wrap(env, - _this, - obj, - MyObject::Destructor, - nullptr, // finalize_hint - &obj->wrapper_)); + NODE_API_CALL(env, node_api_wrap(env, + _this, + obj, + MyObject::Destructor, + nullptr, // finalize_hint + &obj->wrapper_)); return _this; } // Invoked as plain function `MyObject(...)`, turn into construct call. argc = 1; - napi_value argv[1] = {args[0]}; + node_api_value argv[1] = {args[0]}; - napi_value cons; - NAPI_CALL(env, napi_get_reference_value(env, constructor, &cons)); + node_api_value cons; + NODE_API_CALL(env, node_api_get_reference_value(env, constructor, &cons)); - napi_value instance; - NAPI_CALL(env, napi_new_instance(env, cons, argc, argv, &instance)); + node_api_value instance; + NODE_API_CALL(env, node_api_new_instance(env, cons, argc, argv, &instance)); return instance; } -napi_value MyObject::GetValue(napi_env env, napi_callback_info info) { - napi_value _this; - NAPI_CALL(env, - napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); +node_api_value +MyObject::GetValue(node_api_env env, node_api_callback_info info) { + node_api_value _this; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); MyObject* obj; - NAPI_CALL(env, napi_unwrap(env, _this, reinterpret_cast(&obj))); + NODE_API_CALL(env, + node_api_unwrap(env, _this, reinterpret_cast(&obj))); - napi_value num; - NAPI_CALL(env, napi_create_double(env, obj->value_, &num)); + node_api_value num; + NODE_API_CALL(env, node_api_create_double(env, obj->value_, &num)); return num; } -napi_value MyObject::SetValue(napi_env env, napi_callback_info info) { +node_api_value +MyObject::SetValue(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - napi_value _this; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &_this, nullptr)); + node_api_value args[1]; + node_api_value _this; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, args, &_this, nullptr)); MyObject* obj; - NAPI_CALL(env, napi_unwrap(env, _this, reinterpret_cast(&obj))); + NODE_API_CALL(env, + node_api_unwrap(env, _this, reinterpret_cast(&obj))); - NAPI_CALL(env, napi_get_value_double(env, args[0], &obj->value_)); + NODE_API_CALL(env, node_api_get_value_double(env, args[0], &obj->value_)); return nullptr; } -napi_value MyObject::PlusOne(napi_env env, napi_callback_info info) { - napi_value _this; - NAPI_CALL(env, - napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); +node_api_value +MyObject::PlusOne(node_api_env env, node_api_callback_info info) { + node_api_value _this; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); MyObject* obj; - NAPI_CALL(env, napi_unwrap(env, _this, reinterpret_cast(&obj))); + NODE_API_CALL(env, + node_api_unwrap(env, _this, reinterpret_cast(&obj))); obj->value_ += 1; - napi_value num; - NAPI_CALL(env, napi_create_double(env, obj->value_, &num)); + node_api_value num; + NODE_API_CALL(env, node_api_create_double(env, obj->value_, &num)); return num; } -napi_value MyObject::Multiply(napi_env env, napi_callback_info info) { +node_api_value +MyObject::Multiply(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - napi_value _this; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &_this, nullptr)); + node_api_value args[1]; + node_api_value _this; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, args, &_this, nullptr)); double multiple = 1; if (argc >= 1) { - NAPI_CALL(env, napi_get_value_double(env, args[0], &multiple)); + NODE_API_CALL(env, node_api_get_value_double(env, args[0], &multiple)); } MyObject* obj; - NAPI_CALL(env, napi_unwrap(env, _this, reinterpret_cast(&obj))); + NODE_API_CALL(env, + node_api_unwrap(env, _this, reinterpret_cast(&obj))); - napi_value cons; - NAPI_CALL(env, napi_get_reference_value(env, constructor, &cons)); + node_api_value cons; + NODE_API_CALL(env, node_api_get_reference_value(env, constructor, &cons)); const int kArgCount = 1; - napi_value argv[kArgCount]; - NAPI_CALL(env, napi_create_double(env, obj->value_ * multiple, argv)); + node_api_value argv[kArgCount]; + NODE_API_CALL(env, + node_api_create_double(env, obj->value_ * multiple, argv)); - napi_value instance; - NAPI_CALL(env, napi_new_instance(env, cons, kArgCount, argv, &instance)); + node_api_value instance; + NODE_API_CALL(env, + node_api_new_instance(env, cons, kArgCount, argv, &instance)); return instance; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { +node_api_value Init(node_api_env env, node_api_value exports) { MyObject::Init(env, exports); return exports; } diff --git a/test/js-native-api/6_object_wrap/myobject.h b/test/js-native-api/6_object_wrap/myobject.h index 337180598bc042..d01cb9131e4472 100644 --- a/test/js-native-api/6_object_wrap/myobject.h +++ b/test/js-native-api/6_object_wrap/myobject.h @@ -5,22 +5,25 @@ class MyObject { public: - static void Init(napi_env env, napi_value exports); - static void Destructor(napi_env env, void* nativeObject, void* finalize_hint); + static void Init(node_api_env env, node_api_value exports); + static void + Destructor(node_api_env env, void* nativeObject, void* finalize_hint); private: explicit MyObject(double value_ = 0); ~MyObject(); - static napi_value New(napi_env env, napi_callback_info info); - static napi_value GetValue(napi_env env, napi_callback_info info); - static napi_value SetValue(napi_env env, napi_callback_info info); - static napi_value PlusOne(napi_env env, napi_callback_info info); - static napi_value Multiply(napi_env env, napi_callback_info info); - static napi_ref constructor; + static node_api_value New(node_api_env env, node_api_callback_info info); + static node_api_value + GetValue(node_api_env env, node_api_callback_info info); + static node_api_value + SetValue(node_api_env env, node_api_callback_info info); + static node_api_value PlusOne(node_api_env env, node_api_callback_info info); + static node_api_value + Multiply(node_api_env env, node_api_callback_info info); + static node_api_ref constructor; double value_; - napi_env env_; - napi_ref wrapper_; + node_api_env env_; + node_api_ref wrapper_; }; - #endif // TEST_JS_NATIVE_API_6_OBJECT_WRAP_MYOBJECT_H_ diff --git a/test/js-native-api/7_factory_wrap/binding.cc b/test/js-native-api/7_factory_wrap/binding.cc index 4a75156bd5359b..cf5f5e9de8b0be 100644 --- a/test/js-native-api/7_factory_wrap/binding.cc +++ b/test/js-native-api/7_factory_wrap/binding.cc @@ -2,27 +2,28 @@ #include "myobject.h" #include "../common.h" -napi_value CreateObject(napi_env env, napi_callback_info info) { +node_api_value CreateObject(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + node_api_value args[1]; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, args, nullptr, nullptr)); - napi_value instance; - NAPI_CALL(env, MyObject::NewInstance(env, args[0], &instance)); + node_api_value instance; + NODE_API_CALL(env, MyObject::NewInstance(env, args[0], &instance)); return instance; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - NAPI_CALL(env, MyObject::Init(env)); +node_api_value Init(node_api_env env, node_api_value exports) { + NODE_API_CALL(env, MyObject::Init(env)); - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_GETTER("finalizeCount", MyObject::GetFinalizeCount), - DECLARE_NAPI_PROPERTY("createObject", CreateObject), + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_GETTER("finalizeCount", MyObject::GetFinalizeCount), + DECLARE_NODE_API_PROPERTY("createObject", CreateObject), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/js-native-api/7_factory_wrap/myobject.cc b/test/js-native-api/7_factory_wrap/myobject.cc index b7cc9c534f366a..0fd2ce0e85ded5 100644 --- a/test/js-native-api/7_factory_wrap/myobject.cc +++ b/test/js-native-api/7_factory_wrap/myobject.cc @@ -5,9 +5,9 @@ static int finalize_count = 0; MyObject::MyObject() : env_(nullptr), wrapper_(nullptr) {} -MyObject::~MyObject() { napi_delete_reference(env_, wrapper_); } +MyObject::~MyObject() { node_api_delete_reference(env_, wrapper_); } -void MyObject::Destructor(napi_env env, +void MyObject::Destructor(node_api_env env, void* nativeObject, void* /*finalize_hint*/) { ++finalize_count; @@ -15,89 +15,94 @@ void MyObject::Destructor(napi_env env, delete obj; } -napi_value MyObject::GetFinalizeCount(napi_env env, napi_callback_info info) { - napi_value result; - NAPI_CALL(env, napi_create_int32(env, finalize_count, &result)); +node_api_value +MyObject::GetFinalizeCount(node_api_env env, node_api_callback_info info) { + node_api_value result; + NODE_API_CALL(env, node_api_create_int32(env, finalize_count, &result)); return result; } -napi_ref MyObject::constructor; +node_api_ref MyObject::constructor; -napi_status MyObject::Init(napi_env env) { - napi_status status; - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("plusOne", PlusOne), +node_api_status MyObject::Init(node_api_env env) { + node_api_status status; + node_api_property_descriptor properties[] = { + DECLARE_NODE_API_PROPERTY("plusOne", PlusOne), }; - napi_value cons; - status = napi_define_class( + node_api_value cons; + status = node_api_define_class( env, "MyObject", -1, New, nullptr, 1, properties, &cons); - if (status != napi_ok) return status; + if (status != node_api_ok) return status; - status = napi_create_reference(env, cons, 1, &constructor); - if (status != napi_ok) return status; + status = node_api_create_reference(env, cons, 1, &constructor); + if (status != node_api_ok) return status; - return napi_ok; + return node_api_ok; } -napi_value MyObject::New(napi_env env, napi_callback_info info) { +node_api_value MyObject::New(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - napi_value _this; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &_this, nullptr)); + node_api_value args[1]; + node_api_value _this; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, args, &_this, nullptr)); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); MyObject* obj = new MyObject(); - if (valuetype == napi_undefined) { + if (valuetype == node_api_undefined) { obj->counter_ = 0; } else { - NAPI_CALL(env, napi_get_value_uint32(env, args[0], &obj->counter_)); + NODE_API_CALL(env, + node_api_get_value_uint32(env, args[0], &obj->counter_)); } obj->env_ = env; - NAPI_CALL(env, napi_wrap(env, - _this, - obj, - MyObject::Destructor, - nullptr, /* finalize_hint */ - &obj->wrapper_)); + NODE_API_CALL(env, node_api_wrap(env, + _this, + obj, + MyObject::Destructor, + nullptr, /* finalize_hint */ + &obj->wrapper_)); return _this; } -napi_status MyObject::NewInstance(napi_env env, - napi_value arg, - napi_value* instance) { - napi_status status; +node_api_status MyObject::NewInstance(node_api_env env, + node_api_value arg, + node_api_value* instance) { + node_api_status status; const int argc = 1; - napi_value argv[argc] = {arg}; + node_api_value argv[argc] = {arg}; - napi_value cons; - status = napi_get_reference_value(env, constructor, &cons); - if (status != napi_ok) return status; + node_api_value cons; + status = node_api_get_reference_value(env, constructor, &cons); + if (status != node_api_ok) return status; - status = napi_new_instance(env, cons, argc, argv, instance); - if (status != napi_ok) return status; + status = node_api_new_instance(env, cons, argc, argv, instance); + if (status != node_api_ok) return status; - return napi_ok; + return node_api_ok; } -napi_value MyObject::PlusOne(napi_env env, napi_callback_info info) { - napi_value _this; - NAPI_CALL(env, - napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); +node_api_value +MyObject::PlusOne(node_api_env env, node_api_callback_info info) { + node_api_value _this; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); MyObject* obj; - NAPI_CALL(env, napi_unwrap(env, _this, reinterpret_cast(&obj))); + NODE_API_CALL(env, + node_api_unwrap(env, _this, reinterpret_cast(&obj))); obj->counter_ += 1; - napi_value num; - NAPI_CALL(env, napi_create_uint32(env, obj->counter_, &num)); + node_api_value num; + NODE_API_CALL(env, node_api_create_uint32(env, obj->counter_, &num)); return num; } diff --git a/test/js-native-api/7_factory_wrap/myobject.h b/test/js-native-api/7_factory_wrap/myobject.h index 455ec1c52c5760..285d3a3b082d5d 100644 --- a/test/js-native-api/7_factory_wrap/myobject.h +++ b/test/js-native-api/7_factory_wrap/myobject.h @@ -5,23 +5,25 @@ class MyObject { public: - static napi_status Init(napi_env env); - static void Destructor(napi_env env, void* nativeObject, void* finalize_hint); - static napi_value GetFinalizeCount(napi_env env, napi_callback_info info); - static napi_status NewInstance(napi_env env, - napi_value arg, - napi_value* instance); + static node_api_status Init(node_api_env env); + static void + Destructor(node_api_env env, void* nativeObject, void* finalize_hint); + static node_api_value + GetFinalizeCount(node_api_env env, node_api_callback_info info); + static node_api_status NewInstance(node_api_env env, + node_api_value arg, + node_api_value* instance); private: MyObject(); ~MyObject(); - static napi_ref constructor; - static napi_value New(napi_env env, napi_callback_info info); - static napi_value PlusOne(napi_env env, napi_callback_info info); + static node_api_ref constructor; + static node_api_value New(node_api_env env, node_api_callback_info info); + static node_api_value PlusOne(node_api_env env, node_api_callback_info info); uint32_t counter_; - napi_env env_; - napi_ref wrapper_; + node_api_env env_; + node_api_ref wrapper_; }; #endif // TEST_JS_NATIVE_API_7_FACTORY_WRAP_MYOBJECT_H_ diff --git a/test/js-native-api/8_passing_wrapped/binding.cc b/test/js-native-api/8_passing_wrapped/binding.cc index 8670a86879eb1c..ca3e775a50d4f8 100644 --- a/test/js-native-api/8_passing_wrapped/binding.cc +++ b/test/js-native-api/8_passing_wrapped/binding.cc @@ -4,52 +4,62 @@ extern size_t finalize_count; -static napi_value CreateObject(napi_env env, napi_callback_info info) { +static node_api_value +CreateObject(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + node_api_value args[1]; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, args, nullptr, nullptr)); - napi_value instance; - NAPI_CALL(env, MyObject::NewInstance(env, args[0], &instance)); + node_api_value instance; + NODE_API_CALL(env, MyObject::NewInstance(env, args[0], &instance)); return instance; } -static napi_value Add(napi_env env, napi_callback_info info) { +static node_api_value Add(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + node_api_value args[2]; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, args, nullptr, nullptr)); MyObject* obj1; - NAPI_CALL(env, napi_unwrap(env, args[0], reinterpret_cast(&obj1))); + NODE_API_CALL(env, + node_api_unwrap(env, args[0], reinterpret_cast(&obj1))); MyObject* obj2; - NAPI_CALL(env, napi_unwrap(env, args[1], reinterpret_cast(&obj2))); + NODE_API_CALL(env, + node_api_unwrap(env, args[1], reinterpret_cast(&obj2))); - napi_value sum; - NAPI_CALL(env, napi_create_double(env, obj1->Val() + obj2->Val(), &sum)); + node_api_value sum; + NODE_API_CALL(env, + node_api_create_double(env, obj1->Val() + obj2->Val(), &sum)); return sum; } -static napi_value FinalizeCount(napi_env env, napi_callback_info info) { - napi_value return_value; - NAPI_CALL(env, napi_create_uint32(env, finalize_count, &return_value)); +static node_api_value +FinalizeCount(node_api_env env, node_api_callback_info info) { + node_api_value return_value; + NODE_API_CALL(env, + node_api_create_uint32(env, finalize_count, &return_value)); return return_value; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { +node_api_value Init(node_api_env env, node_api_value exports) { MyObject::Init(env); - napi_property_descriptor desc[] = { - DECLARE_NAPI_PROPERTY("createObject", CreateObject), - DECLARE_NAPI_PROPERTY("add", Add), - DECLARE_NAPI_PROPERTY("finalizeCount", FinalizeCount), + node_api_property_descriptor desc[] = { + DECLARE_NODE_API_PROPERTY("createObject", CreateObject), + DECLARE_NODE_API_PROPERTY("add", Add), + DECLARE_NODE_API_PROPERTY("finalizeCount", FinalizeCount), }; - NAPI_CALL(env, - napi_define_properties(env, exports, sizeof(desc) / sizeof(*desc), desc)); + NODE_API_CALL(env, node_api_define_properties(env, + exports, + sizeof(desc) / sizeof(*desc), + desc)); return exports; } diff --git a/test/js-native-api/8_passing_wrapped/myobject.cc b/test/js-native-api/8_passing_wrapped/myobject.cc index 28e207a4248d09..c19c9c1275f910 100644 --- a/test/js-native-api/8_passing_wrapped/myobject.cc +++ b/test/js-native-api/8_passing_wrapped/myobject.cc @@ -7,77 +7,78 @@ MyObject::MyObject() : env_(nullptr), wrapper_(nullptr) {} MyObject::~MyObject() { finalize_count++; - napi_delete_reference(env_, wrapper_); + node_api_delete_reference(env_, wrapper_); } void MyObject::Destructor( - napi_env env, void* nativeObject, void* /*finalize_hint*/) { + node_api_env env, void* nativeObject, void* /*finalize_hint*/) { MyObject* obj = static_cast(nativeObject); delete obj; } -napi_ref MyObject::constructor; +node_api_ref MyObject::constructor; -napi_status MyObject::Init(napi_env env) { - napi_status status; +node_api_status MyObject::Init(node_api_env env) { + node_api_status status; - napi_value cons; - status = napi_define_class( + node_api_value cons; + status = node_api_define_class( env, "MyObject", -1, New, nullptr, 0, nullptr, &cons); - if (status != napi_ok) return status; + if (status != node_api_ok) return status; - status = napi_create_reference(env, cons, 1, &constructor); - if (status != napi_ok) return status; + status = node_api_create_reference(env, cons, 1, &constructor); + if (status != node_api_ok) return status; - return napi_ok; + return node_api_ok; } -napi_value MyObject::New(napi_env env, napi_callback_info info) { +node_api_value MyObject::New(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - napi_value _this; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &_this, nullptr)); + node_api_value args[1]; + node_api_value _this; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, args, &_this, nullptr)); MyObject* obj = new MyObject(); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); - if (valuetype == napi_undefined) { + if (valuetype == node_api_undefined) { obj->val_ = 0; } else { - NAPI_CALL(env, napi_get_value_double(env, args[0], &obj->val_)); + NODE_API_CALL(env, node_api_get_value_double(env, args[0], &obj->val_)); } obj->env_ = env; - // The below call to napi_wrap() must request a reference to the wrapped + // The below call to node_api_wrap() must request a reference to the wrapped // object via the out-parameter, because this ensures that we test the code // path that deals with a reference that is destroyed from its own finalizer. - NAPI_CALL(env, napi_wrap(env, - _this, - obj, - MyObject::Destructor, - nullptr, // finalize_hint - &obj->wrapper_)); + NODE_API_CALL(env, node_api_wrap(env, + _this, + obj, + MyObject::Destructor, + nullptr, // finalize_hint + &obj->wrapper_)); return _this; } -napi_status MyObject::NewInstance(napi_env env, - napi_value arg, - napi_value* instance) { - napi_status status; +node_api_status MyObject::NewInstance(node_api_env env, + node_api_value arg, + node_api_value* instance) { + node_api_status status; const int argc = 1; - napi_value argv[argc] = {arg}; + node_api_value argv[argc] = {arg}; - napi_value cons; - status = napi_get_reference_value(env, constructor, &cons); - if (status != napi_ok) return status; + node_api_value cons; + status = node_api_get_reference_value(env, constructor, &cons); + if (status != node_api_ok) return status; - status = napi_new_instance(env, cons, argc, argv, instance); - if (status != napi_ok) return status; + status = node_api_new_instance(env, cons, argc, argv, instance); + if (status != node_api_ok) return status; - return napi_ok; + return node_api_ok; } diff --git a/test/js-native-api/8_passing_wrapped/myobject.h b/test/js-native-api/8_passing_wrapped/myobject.h index 445cf560aaffd8..35c6c92cb2aafb 100644 --- a/test/js-native-api/8_passing_wrapped/myobject.h +++ b/test/js-native-api/8_passing_wrapped/myobject.h @@ -5,22 +5,23 @@ class MyObject { public: - static napi_status Init(napi_env env); - static void Destructor(napi_env env, void* nativeObject, void* finalize_hint); - static napi_status NewInstance(napi_env env, - napi_value arg, - napi_value* instance); + static node_api_status Init(node_api_env env); + static void + Destructor(node_api_env env, void* nativeObject, void* finalize_hint); + static node_api_status NewInstance(node_api_env env, + node_api_value arg, + node_api_value* instance); double Val() const { return val_; } private: MyObject(); ~MyObject(); - static napi_ref constructor; - static napi_value New(napi_env env, napi_callback_info info); + static node_api_ref constructor; + static node_api_value New(node_api_env env, node_api_callback_info info); double val_; - napi_env env_; - napi_ref wrapper_; + node_api_env env_; + node_api_ref wrapper_; }; #endif // TEST_JS_NATIVE_API_8_PASSING_WRAPPED_MYOBJECT_H_ diff --git a/test/js-native-api/common.c b/test/js-native-api/common.c index a6de256147c22a..09bf1f64ce409e 100644 --- a/test/js-native-api/common.c +++ b/test/js-native-api/common.c @@ -3,49 +3,51 @@ #include -void add_returned_status(napi_env env, +void add_returned_status(node_api_env env, const char* key, - napi_value object, + node_api_value object, char* expected_message, - napi_status expected_status, - napi_status actual_status) { + node_api_status expected_status, + node_api_status actual_status) { - char napi_message_string[100] = ""; - napi_value prop_value; + char node_api_message_string[100] = ""; + node_api_value prop_value; if (actual_status != expected_status) { - snprintf(napi_message_string, sizeof(napi_message_string), "Invalid status [%d]", actual_status); + snprintf(node_api_message_string, + sizeof(node_api_message_string), + "Invalid status [%d]", actual_status); } - NAPI_CALL_RETURN_VOID(env, - napi_create_string_utf8( + NODE_API_CALL_RETURN_VOID(env, + node_api_create_string_utf8( env, (actual_status == expected_status ? expected_message : - napi_message_string), - NAPI_AUTO_LENGTH, + node_api_message_string), + NODE_API_AUTO_LENGTH, &prop_value)); - NAPI_CALL_RETURN_VOID(env, - napi_set_named_property(env, - object, - key, - prop_value)); + NODE_API_CALL_RETURN_VOID(env, + node_api_set_named_property(env, + object, + key, + prop_value)); } -void add_last_status(napi_env env, const char* key, napi_value return_value) { - napi_value prop_value; - const napi_extended_error_info* p_last_error; - NAPI_CALL_RETURN_VOID(env, napi_get_last_error_info(env, &p_last_error)); +void add_last_status(node_api_env env, const char* key, node_api_value return_value) { + node_api_value prop_value; + const node_api_extended_error_info* p_last_error; + NODE_API_CALL_RETURN_VOID(env, node_api_get_last_error_info(env, &p_last_error)); - NAPI_CALL_RETURN_VOID(env, - napi_create_string_utf8(env, - (p_last_error->error_message == NULL ? - "napi_ok" : - p_last_error->error_message), - NAPI_AUTO_LENGTH, - &prop_value)); - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, - return_value, - key, - prop_value)); + NODE_API_CALL_RETURN_VOID(env, + node_api_create_string_utf8(env, + (p_last_error->error_message == NULL ? + "node_api_ok" : + p_last_error->error_message), + NODE_API_AUTO_LENGTH, + &prop_value)); + NODE_API_CALL_RETURN_VOID(env, node_api_set_named_property(env, + return_value, + key, + prop_value)); } diff --git a/test/js-native-api/common.h b/test/js-native-api/common.h index a524e8c7a75182..40be8533b01eec 100644 --- a/test/js-native-api/common.h +++ b/test/js-native-api/common.h @@ -1,27 +1,27 @@ #include // Empty value so that macros here are able to return NULL or void -#define NAPI_RETVAL_NOTHING // Intentionally blank #define +#define NODE_API_RETVAL_NOTHING // Intentionally blank #define #define GET_AND_THROW_LAST_ERROR(env) \ do { \ - const napi_extended_error_info *error_info; \ - napi_get_last_error_info((env), &error_info); \ + const node_api_extended_error_info *error_info; \ + node_api_get_last_error_info((env), &error_info); \ bool is_pending; \ - napi_is_exception_pending((env), &is_pending); \ + node_api_is_exception_pending((env), &is_pending); \ /* If an exception is already pending, don't rethrow it */ \ if (!is_pending) { \ const char* error_message = error_info->error_message != NULL ? \ error_info->error_message : \ "empty error message"; \ - napi_throw_error((env), NULL, error_message); \ + node_api_throw_error((env), NULL, error_message); \ } \ } while (0) -#define NAPI_ASSERT_BASE(env, assertion, message, ret_val) \ +#define NODE_API_ASSERT_BASE(env, assertion, message, ret_val) \ do { \ if (!(assertion)) { \ - napi_throw_error( \ + node_api_throw_error( \ (env), \ NULL, \ "assertion (" #assertion ") failed: " message); \ @@ -30,42 +30,44 @@ } while (0) // Returns NULL on failed assertion. -// This is meant to be used inside napi_callback methods. -#define NAPI_ASSERT(env, assertion, message) \ - NAPI_ASSERT_BASE(env, assertion, message, NULL) +// This is meant to be used inside node_api_callback methods. +#define NODE_API_ASSERT(env, assertion, message) \ + NODE_API_ASSERT_BASE(env, assertion, message, NULL) // Returns empty on failed assertion. // This is meant to be used inside functions with void return type. -#define NAPI_ASSERT_RETURN_VOID(env, assertion, message) \ - NAPI_ASSERT_BASE(env, assertion, message, NAPI_RETVAL_NOTHING) +#define NODE_API_ASSERT_RETURN_VOID(env, assertion, message) \ + NODE_API_ASSERT_BASE(env, assertion, message, NODE_API_RETVAL_NOTHING) -#define NAPI_CALL_BASE(env, the_call, ret_val) \ +#define NODE_API_CALL_BASE(env, the_call, ret_val) \ do { \ - if ((the_call) != napi_ok) { \ + if ((the_call) != node_api_ok) { \ GET_AND_THROW_LAST_ERROR((env)); \ return ret_val; \ } \ } while (0) -// Returns NULL if the_call doesn't return napi_ok. -#define NAPI_CALL(env, the_call) \ - NAPI_CALL_BASE(env, the_call, NULL) +// Returns NULL if the_call doesn't return node_api_ok. +#define NODE_API_CALL(env, the_call) \ + NODE_API_CALL_BASE(env, the_call, NULL) -// Returns empty if the_call doesn't return napi_ok. -#define NAPI_CALL_RETURN_VOID(env, the_call) \ - NAPI_CALL_BASE(env, the_call, NAPI_RETVAL_NOTHING) +// Returns empty if the_call doesn't return node_api_ok. +#define NODE_API_CALL_RETURN_VOID(env, the_call) \ + NODE_API_CALL_BASE(env, the_call, NODE_API_RETVAL_NOTHING) -#define DECLARE_NAPI_PROPERTY(name, func) \ - { (name), NULL, (func), NULL, NULL, NULL, napi_default, NULL } +#define DECLARE_NODE_API_PROPERTY(name, func) \ + { (name), NULL, (func), NULL, NULL, NULL, node_api_default, NULL } -#define DECLARE_NAPI_GETTER(name, func) \ - { (name), NULL, NULL, (func), NULL, NULL, napi_default, NULL } +#define DECLARE_NODE_API_GETTER(name, func) \ + { (name), NULL, NULL, (func), NULL, NULL, node_api_default, NULL } -void add_returned_status(napi_env env, +void add_returned_status(node_api_env env, const char* key, - napi_value object, + node_api_value object, char* expected_message, - napi_status expected_status, - napi_status actual_status); + node_api_status expected_status, + node_api_status actual_status); -void add_last_status(napi_env env, const char* key, napi_value return_value); +void add_last_status(node_api_env env, + const char* key, + node_api_value return_value); diff --git a/test/js-native-api/entry_point.c b/test/js-native-api/entry_point.c index 6b7b50a38c9535..4d9c3fa5e15d50 100644 --- a/test/js-native-api/entry_point.c +++ b/test/js-native-api/entry_point.c @@ -1,7 +1,7 @@ #include EXTERN_C_START -napi_value Init(napi_env env, napi_value exports); +node_api_value Init(node_api_env env, node_api_value exports); EXTERN_C_END -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/js-native-api/test_array/test_array.c b/test/js-native-api/test_array/test_array.c index 044f8636f5b9ce..90530e0347b185 100644 --- a/test/js-native-api/test_array/test_array.c +++ b/test/js-native-api/test_array/test_array.c @@ -2,184 +2,188 @@ #include #include "../common.h" -static napi_value TestGetElement(napi_env env, napi_callback_info info) { +static node_api_value +TestGetElement(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 2, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 2, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects an array as first argument."); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + node_api_valuetype valuetype1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); - NAPI_ASSERT(env, valuetype1 == napi_number, + NODE_API_ASSERT(env, valuetype1 == node_api_number, "Wrong type of arguments. Expects an integer as second argument."); - napi_value array = args[0]; + node_api_value array = args[0]; int32_t index; - NAPI_CALL(env, napi_get_value_int32(env, args[1], &index)); + NODE_API_CALL(env, node_api_get_value_int32(env, args[1], &index)); - NAPI_ASSERT(env, index >= 0, "Invalid index. Expects a positive integer."); + NODE_API_ASSERT(env, index >= 0, "Invalid index. Expects a positive integer."); bool isarray; - NAPI_CALL(env, napi_is_array(env, array, &isarray)); + NODE_API_CALL(env, node_api_is_array(env, array, &isarray)); if (!isarray) { return NULL; } uint32_t length; - NAPI_CALL(env, napi_get_array_length(env, array, &length)); + NODE_API_CALL(env, node_api_get_array_length(env, array, &length)); - NAPI_ASSERT(env, ((uint32_t)index < length), "Index out of bounds!"); + NODE_API_ASSERT(env, ((uint32_t)index < length), "Index out of bounds!"); - napi_value ret; - NAPI_CALL(env, napi_get_element(env, array, index, &ret)); + node_api_value ret; + NODE_API_CALL(env, node_api_get_element(env, array, index, &ret)); return ret; } -static napi_value TestHasElement(napi_env env, napi_callback_info info) { +static node_api_value +TestHasElement(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 2, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 2, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects an array as first argument."); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + node_api_valuetype valuetype1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); - NAPI_ASSERT(env, valuetype1 == napi_number, + NODE_API_ASSERT(env, valuetype1 == node_api_number, "Wrong type of arguments. Expects an integer as second argument."); - napi_value array = args[0]; + node_api_value array = args[0]; int32_t index; - NAPI_CALL(env, napi_get_value_int32(env, args[1], &index)); + NODE_API_CALL(env, node_api_get_value_int32(env, args[1], &index)); bool isarray; - NAPI_CALL(env, napi_is_array(env, array, &isarray)); + NODE_API_CALL(env, node_api_is_array(env, array, &isarray)); if (!isarray) { return NULL; } bool has_element; - NAPI_CALL(env, napi_has_element(env, array, index, &has_element)); + NODE_API_CALL(env, node_api_has_element(env, array, index, &has_element)); - napi_value ret; - NAPI_CALL(env, napi_get_boolean(env, has_element, &ret)); + node_api_value ret; + NODE_API_CALL(env, node_api_get_boolean(env, has_element, &ret)); return ret; } -static napi_value TestDeleteElement(napi_env env, napi_callback_info info) { +static node_api_value +TestDeleteElement(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; + node_api_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_ASSERT(env, argc == 2, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects an array as first argument."); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); - NAPI_ASSERT(env, valuetype1 == napi_number, + node_api_valuetype valuetype1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); + NODE_API_ASSERT(env, valuetype1 == node_api_number, "Wrong type of arguments. Expects an integer as second argument."); - napi_value array = args[0]; + node_api_value array = args[0]; int32_t index; bool result; - napi_value ret; + node_api_value ret; - NAPI_CALL(env, napi_get_value_int32(env, args[1], &index)); - NAPI_CALL(env, napi_is_array(env, array, &result)); + NODE_API_CALL(env, node_api_get_value_int32(env, args[1], &index)); + NODE_API_CALL(env, node_api_is_array(env, array, &result)); if (!result) { return NULL; } - NAPI_CALL(env, napi_delete_element(env, array, index, &result)); - NAPI_CALL(env, napi_get_boolean(env, result, &ret)); + NODE_API_CALL(env, node_api_delete_element(env, array, index, &result)); + NODE_API_CALL(env, node_api_get_boolean(env, result, &ret)); return ret; } -static napi_value New(napi_env env, napi_callback_info info) { +static node_api_value New(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects an array as first argument."); - napi_value ret; - NAPI_CALL(env, napi_create_array(env, &ret)); + node_api_value ret; + NODE_API_CALL(env, node_api_create_array(env, &ret)); uint32_t i, length; - NAPI_CALL(env, napi_get_array_length(env, args[0], &length)); + NODE_API_CALL(env, node_api_get_array_length(env, args[0], &length)); for (i = 0; i < length; i++) { - napi_value e; - NAPI_CALL(env, napi_get_element(env, args[0], i, &e)); - NAPI_CALL(env, napi_set_element(env, ret, i, e)); + node_api_value e; + NODE_API_CALL(env, node_api_get_element(env, args[0], i, &e)); + NODE_API_CALL(env, node_api_set_element(env, ret, i, e)); } return ret; } -static napi_value NewWithLength(napi_env env, napi_callback_info info) { +static node_api_value +NewWithLength(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_number, + NODE_API_ASSERT(env, valuetype0 == node_api_number, "Wrong type of arguments. Expects an integer the first argument."); int32_t array_length; - NAPI_CALL(env, napi_get_value_int32(env, args[0], &array_length)); + NODE_API_CALL(env, node_api_get_value_int32(env, args[0], &array_length)); - napi_value ret; - NAPI_CALL(env, napi_create_array_with_length(env, array_length, &ret)); + node_api_value ret; + NODE_API_CALL(env, node_api_create_array_with_length(env, array_length, &ret)); return ret; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("TestGetElement", TestGetElement), - DECLARE_NAPI_PROPERTY("TestHasElement", TestHasElement), - DECLARE_NAPI_PROPERTY("TestDeleteElement", TestDeleteElement), - DECLARE_NAPI_PROPERTY("New", New), - DECLARE_NAPI_PROPERTY("NewWithLength", NewWithLength), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("TestGetElement", TestGetElement), + DECLARE_NODE_API_PROPERTY("TestHasElement", TestHasElement), + DECLARE_NODE_API_PROPERTY("TestDeleteElement", TestDeleteElement), + DECLARE_NODE_API_PROPERTY("New", New), + DECLARE_NODE_API_PROPERTY("NewWithLength", NewWithLength), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/js-native-api/test_bigint/test_bigint.c b/test/js-native-api/test_bigint/test_bigint.c index 181f9103fa3399..f5e7fa8620bbb2 100644 --- a/test/js-native-api/test_bigint/test_bigint.c +++ b/test/js-native-api/test_bigint/test_bigint.c @@ -4,153 +4,164 @@ #include #include "../common.h" -static napi_value IsLossless(napi_env env, napi_callback_info info) { +static node_api_value +IsLossless(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); bool is_signed; - NAPI_CALL(env, napi_get_value_bool(env, args[1], &is_signed)); + NODE_API_CALL(env, node_api_get_value_bool(env, args[1], &is_signed)); bool lossless; if (is_signed) { int64_t input; - NAPI_CALL(env, napi_get_value_bigint_int64(env, args[0], &input, &lossless)); + NODE_API_CALL(env, + node_api_get_value_bigint_int64(env, args[0], &input, &lossless)); } else { uint64_t input; - NAPI_CALL(env, napi_get_value_bigint_uint64(env, args[0], &input, &lossless)); + NODE_API_CALL(env, + node_api_get_value_bigint_uint64(env, args[0], &input, &lossless)); } - napi_value output; - NAPI_CALL(env, napi_get_boolean(env, lossless, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_get_boolean(env, lossless, &output)); return output; } -static napi_value TestInt64(napi_env env, napi_callback_info info) { +static node_api_value +TestInt64(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_bigint, + NODE_API_ASSERT(env, valuetype0 == node_api_bigint, "Wrong type of arguments. Expects a bigint as first argument."); int64_t input; bool lossless; - NAPI_CALL(env, napi_get_value_bigint_int64(env, args[0], &input, &lossless)); + NODE_API_CALL(env, + node_api_get_value_bigint_int64(env, args[0], &input, &lossless)); - napi_value output; - NAPI_CALL(env, napi_create_bigint_int64(env, input, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_bigint_int64(env, input, &output)); return output; } -static napi_value TestUint64(napi_env env, napi_callback_info info) { +static node_api_value +TestUint64(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_bigint, + NODE_API_ASSERT(env, valuetype0 == node_api_bigint, "Wrong type of arguments. Expects a bigint as first argument."); uint64_t input; bool lossless; - NAPI_CALL(env, napi_get_value_bigint_uint64( + NODE_API_CALL(env, node_api_get_value_bigint_uint64( env, args[0], &input, &lossless)); - napi_value output; - NAPI_CALL(env, napi_create_bigint_uint64(env, input, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_bigint_uint64(env, input, &output)); return output; } -static napi_value TestWords(napi_env env, napi_callback_info info) { +static node_api_value +TestWords(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_bigint, + NODE_API_ASSERT(env, valuetype0 == node_api_bigint, "Wrong type of arguments. Expects a bigint as first argument."); size_t expected_word_count; - NAPI_CALL(env, napi_get_value_bigint_words( + NODE_API_CALL(env, node_api_get_value_bigint_words( env, args[0], NULL, &expected_word_count, NULL)); int sign_bit; size_t word_count = 10; uint64_t words[10]; - NAPI_CALL(env, napi_get_value_bigint_words( + NODE_API_CALL(env, node_api_get_value_bigint_words( env, args[0], &sign_bit, &word_count, words)); - NAPI_ASSERT(env, word_count == expected_word_count, + NODE_API_ASSERT(env, word_count == expected_word_count, "word counts do not match"); - napi_value output; - NAPI_CALL(env, napi_create_bigint_words( - env, sign_bit, word_count, words, &output)); + node_api_value output; + NODE_API_CALL(env, + node_api_create_bigint_words(env, sign_bit, word_count, words, &output)); return output; } // throws RangeError -static napi_value CreateTooBigBigInt(napi_env env, napi_callback_info info) { +static node_api_value +CreateTooBigBigInt(node_api_env env, node_api_callback_info info) { int sign_bit = 0; size_t word_count = SIZE_MAX; uint64_t words[10]; - napi_value output; + node_api_value output; - NAPI_CALL(env, napi_create_bigint_words( + NODE_API_CALL(env, node_api_create_bigint_words( env, sign_bit, word_count, words, &output)); return output; } // Test that we correctly forward exceptions from the engine. -static napi_value MakeBigIntWordsThrow(napi_env env, napi_callback_info info) { +static node_api_value +MakeBigIntWordsThrow(node_api_env env, node_api_callback_info info) { uint64_t words[10]; - napi_value output; - - napi_status status = napi_create_bigint_words(env, - 0, - INT_MAX, - words, - &output); - if (status != napi_pending_exception) - napi_throw_error(env, NULL, "Expected status `napi_pending_exception`"); + node_api_value output; + + node_api_status status = node_api_create_bigint_words(env, + 0, + INT_MAX, + words, + &output); + if (status != node_api_pending_exception) + node_api_throw_error(env, + NULL, + "Expected status `node_api_pending_exception`"); return NULL; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("IsLossless", IsLossless), - DECLARE_NAPI_PROPERTY("TestInt64", TestInt64), - DECLARE_NAPI_PROPERTY("TestUint64", TestUint64), - DECLARE_NAPI_PROPERTY("TestWords", TestWords), - DECLARE_NAPI_PROPERTY("CreateTooBigBigInt", CreateTooBigBigInt), - DECLARE_NAPI_PROPERTY("MakeBigIntWordsThrow", MakeBigIntWordsThrow), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("IsLossless", IsLossless), + DECLARE_NODE_API_PROPERTY("TestInt64", TestInt64), + DECLARE_NODE_API_PROPERTY("TestUint64", TestUint64), + DECLARE_NODE_API_PROPERTY("TestWords", TestWords), + DECLARE_NODE_API_PROPERTY("CreateTooBigBigInt", CreateTooBigBigInt), + DECLARE_NODE_API_PROPERTY("MakeBigIntWordsThrow", MakeBigIntWordsThrow), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/js-native-api/test_constructor/test.js b/test/js-native-api/test_constructor/test.js index c5be4c93bf81e9..51ca004325105d 100644 --- a/test/js-native-api/test_constructor/test.js +++ b/test/js-native-api/test_constructor/test.js @@ -21,7 +21,7 @@ assert.throws(() => { test_object.readonlyValue = 3; }, assert.ok(test_object.hiddenValue); -// Properties with napi_enumerable attribute should be enumerable. +// Properties with node_api_enumerable attribute should be enumerable. const propertyNames = []; for (const name in test_object) { propertyNames.push(name); @@ -35,7 +35,7 @@ assert.ok(!propertyNames.includes('readwriteAccessor2')); assert.ok(!propertyNames.includes('readonlyAccessor1')); assert.ok(!propertyNames.includes('readonlyAccessor2')); -// The napi_writable attribute should be ignored for accessors. +// The node_api_writable attribute should be ignored for accessors. test_object.readwriteAccessor1 = 1; assert.strictEqual(test_object.readwriteAccessor1, 1); assert.strictEqual(test_object.readonlyAccessor1, 1); @@ -50,13 +50,13 @@ assert.throws(() => { test_object.readonlyAccessor2 = 3; }, getterOnlyErrorRE); assert.strictEqual(TestConstructor.staticReadonlyAccessor1, 10); assert.strictEqual(test_object.staticReadonlyAccessor1, undefined); -// Verify that passing NULL to napi_define_class() results in the correct +// Verify that passing NULL to node_api_define_class() results in the correct // error. assert.deepStrictEqual(TestConstructor.TestDefineClass(), { envIsNull: 'Invalid argument', nameIsNull: 'Invalid argument', cbIsNull: 'Invalid argument', - cbDataIsNull: 'napi_ok', + cbDataIsNull: 'node_api_ok', propertiesIsNull: 'Invalid argument', resultIsNull: 'Invalid argument' }); diff --git a/test/js-native-api/test_constructor/test_constructor.c b/test/js-native-api/test_constructor/test_constructor.c index 6c14e39fe2e624..8ff52741b38733 100644 --- a/test/js-native-api/test_constructor/test_constructor.c +++ b/test/js-native-api/test_constructor/test_constructor.c @@ -4,192 +4,196 @@ static double value_ = 1; static double static_value_ = 10; -static napi_value TestDefineClass(napi_env env, - napi_callback_info info) { - napi_status status; - napi_value result, return_value; +static node_api_value +TestDefineClass(node_api_env env, node_api_callback_info info) { + node_api_status status; + node_api_value result, return_value; - napi_property_descriptor property_descriptor = { + node_api_property_descriptor property_descriptor = { "TestDefineClass", NULL, TestDefineClass, NULL, NULL, NULL, - napi_enumerable | napi_static, + node_api_enumerable | node_api_static, NULL}; - NAPI_CALL(env, napi_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); - status = napi_define_class(NULL, - "TrackedFunction", - NAPI_AUTO_LENGTH, - TestDefineClass, - NULL, - 1, - &property_descriptor, - &result); + status = node_api_define_class(NULL, + "TrackedFunction", + NODE_API_AUTO_LENGTH, + TestDefineClass, + NULL, + 1, + &property_descriptor, + &result); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, + node_api_invalid_arg, status); - napi_define_class(env, - NULL, - NAPI_AUTO_LENGTH, - TestDefineClass, - NULL, - 1, - &property_descriptor, - &result); + node_api_define_class(env, + NULL, + NODE_API_AUTO_LENGTH, + TestDefineClass, + NULL, + 1, + &property_descriptor, + &result); add_last_status(env, "nameIsNull", return_value); - napi_define_class(env, - "TrackedFunction", - NAPI_AUTO_LENGTH, - NULL, - NULL, - 1, - &property_descriptor, - &result); + node_api_define_class(env, + "TrackedFunction", + NODE_API_AUTO_LENGTH, + NULL, + NULL, + 1, + &property_descriptor, + &result); add_last_status(env, "cbIsNull", return_value); - napi_define_class(env, - "TrackedFunction", - NAPI_AUTO_LENGTH, - TestDefineClass, - NULL, - 1, - &property_descriptor, - &result); + node_api_define_class(env, + "TrackedFunction", + NODE_API_AUTO_LENGTH, + TestDefineClass, + NULL, + 1, + &property_descriptor, + &result); add_last_status(env, "cbDataIsNull", return_value); - napi_define_class(env, - "TrackedFunction", - NAPI_AUTO_LENGTH, - TestDefineClass, - NULL, - 1, - NULL, - &result); + node_api_define_class(env, + "TrackedFunction", + NODE_API_AUTO_LENGTH, + TestDefineClass, + NULL, + 1, + NULL, + &result); add_last_status(env, "propertiesIsNull", return_value); - napi_define_class(env, - "TrackedFunction", - NAPI_AUTO_LENGTH, - TestDefineClass, - NULL, - 1, - &property_descriptor, - NULL); + node_api_define_class(env, + "TrackedFunction", + NODE_API_AUTO_LENGTH, + TestDefineClass, + NULL, + 1, + &property_descriptor, + NULL); add_last_status(env, "resultIsNull", return_value); return return_value; } -static napi_value GetValue(napi_env env, napi_callback_info info) { +static node_api_value GetValue(node_api_env env, node_api_callback_info info) { size_t argc = 0; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, NULL, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, NULL, NULL, NULL)); - NAPI_ASSERT(env, argc == 0, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 0, "Wrong number of arguments"); - napi_value number; - NAPI_CALL(env, napi_create_double(env, value_, &number)); + node_api_value number; + NODE_API_CALL(env, node_api_create_double(env, value_, &number)); return number; } -static napi_value SetValue(napi_env env, napi_callback_info info) { +static node_api_value SetValue(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments"); - NAPI_CALL(env, napi_get_value_double(env, args[0], &value_)); + NODE_API_CALL(env, node_api_get_value_double(env, args[0], &value_)); return NULL; } -static napi_value Echo(napi_env env, napi_callback_info info) { +static node_api_value Echo(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments"); return args[0]; } -static napi_value New(napi_env env, napi_callback_info info) { - napi_value _this; - NAPI_CALL(env, napi_get_cb_info(env, info, NULL, NULL, &_this, NULL)); +static node_api_value New(node_api_env env, node_api_callback_info info) { + node_api_value _this; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, NULL, NULL, &_this, NULL)); return _this; } -static napi_value GetStaticValue(napi_env env, napi_callback_info info) { +static node_api_value +GetStaticValue(node_api_env env, node_api_callback_info info) { size_t argc = 0; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, NULL, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, NULL, NULL, NULL)); - NAPI_ASSERT(env, argc == 0, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 0, "Wrong number of arguments"); - napi_value number; - NAPI_CALL(env, napi_create_double(env, static_value_, &number)); + node_api_value number; + NODE_API_CALL(env, node_api_create_double(env, static_value_, &number)); return number; } -static napi_value NewExtra(napi_env env, napi_callback_info info) { - napi_value _this; - NAPI_CALL(env, napi_get_cb_info(env, info, NULL, NULL, &_this, NULL)); +static node_api_value NewExtra(node_api_env env, node_api_callback_info info) { + node_api_value _this; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, NULL, NULL, &_this, NULL)); return _this; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_value number, cons; - NAPI_CALL(env, napi_create_double(env, value_, &number)); +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_value number, cons; + NODE_API_CALL(env, node_api_create_double(env, value_, &number)); - NAPI_CALL(env, napi_define_class( + NODE_API_CALL(env, node_api_define_class( env, "MyObject_Extra", 8, NewExtra, NULL, 0, NULL, &cons)); - napi_property_descriptor properties[] = { - { "echo", NULL, Echo, NULL, NULL, NULL, napi_enumerable, NULL }, + node_api_property_descriptor properties[] = { + { "echo", NULL, Echo, NULL, NULL, NULL, node_api_enumerable, NULL }, { "readwriteValue", NULL, NULL, NULL, NULL, number, - napi_enumerable | napi_writable, NULL }, - { "readonlyValue", NULL, NULL, NULL, NULL, number, napi_enumerable, - NULL }, - { "hiddenValue", NULL, NULL, NULL, NULL, number, napi_default, NULL }, - { "readwriteAccessor1", NULL, NULL, GetValue, SetValue, NULL, napi_default, + node_api_enumerable | node_api_writable, NULL }, + { "readonlyValue", NULL, NULL, NULL, NULL, number, node_api_enumerable, NULL }, + { "hiddenValue", NULL, NULL, NULL, NULL, number, node_api_default, NULL }, + { "readwriteAccessor1", NULL, NULL, GetValue, SetValue, NULL, + node_api_default, NULL }, { "readwriteAccessor2", NULL, NULL, GetValue, SetValue, NULL, - napi_writable, NULL }, - { "readonlyAccessor1", NULL, NULL, GetValue, NULL, NULL, napi_default, + node_api_writable, NULL }, + { "readonlyAccessor1", NULL, NULL, GetValue, NULL, NULL, node_api_default, NULL }, - { "readonlyAccessor2", NULL, NULL, GetValue, NULL, NULL, napi_writable, + { "readonlyAccessor2", NULL, NULL, GetValue, NULL, NULL, node_api_writable, NULL }, { "staticReadonlyAccessor1", NULL, NULL, GetStaticValue, NULL, NULL, - napi_default | napi_static, NULL}, + node_api_default | node_api_static, NULL}, { "constructorName", NULL, NULL, NULL, NULL, cons, - napi_enumerable | napi_static, NULL }, + node_api_enumerable | node_api_static, NULL }, { "TestDefineClass", NULL, TestDefineClass, NULL, NULL, NULL, - napi_enumerable | napi_static, NULL }, + node_api_enumerable | node_api_static, NULL }, }; - NAPI_CALL(env, napi_define_class(env, "MyObject", NAPI_AUTO_LENGTH, New, - NULL, sizeof(properties)/sizeof(*properties), properties, &cons)); + NODE_API_CALL(env, + node_api_define_class(env, "MyObject", NODE_API_AUTO_LENGTH, New, + NULL, sizeof(properties)/sizeof(*properties), properties, &cons)); return cons; } diff --git a/test/js-native-api/test_conversions/test.js b/test/js-native-api/test_conversions/test.js index 2fd6ace593840e..d8cf47fba2bbae 100644 --- a/test/js-native-api/test_conversions/test.js +++ b/test/js-native-api/test_conversions/test.js @@ -179,21 +179,21 @@ assert.deepStrictEqual(test.testNull.coerceToBool(), { envIsNull: 'Invalid argument', valueIsNull: 'Invalid argument', resultIsNull: 'Invalid argument', - inputTypeCheck: 'napi_ok' + inputTypeCheck: 'node_api_ok' }); assert.deepStrictEqual(test.testNull.coerceToObject(), { envIsNull: 'Invalid argument', valueIsNull: 'Invalid argument', resultIsNull: 'Invalid argument', - inputTypeCheck: 'napi_ok' + inputTypeCheck: 'node_api_ok' }); assert.deepStrictEqual(test.testNull.coerceToString(), { envIsNull: 'Invalid argument', valueIsNull: 'Invalid argument', resultIsNull: 'Invalid argument', - inputTypeCheck: 'napi_ok' + inputTypeCheck: 'node_api_ok' }); assert.deepStrictEqual(test.testNull.getValueStringUtf8(), { diff --git a/test/js-native-api/test_conversions/test_conversions.c b/test/js-native-api/test_conversions/test_conversions.c index 4f8561a9acf13a..0b9ce1b1d3c49a 100644 --- a/test/js-native-api/test_conversions/test_conversions.c +++ b/test/js-native-api/test_conversions/test_conversions.c @@ -2,152 +2,152 @@ #include "../common.h" #include "test_null.h" -static napi_value AsBool(napi_env env, napi_callback_info info) { +static node_api_value AsBool(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); bool value; - NAPI_CALL(env, napi_get_value_bool(env, args[0], &value)); + NODE_API_CALL(env, node_api_get_value_bool(env, args[0], &value)); - napi_value output; - NAPI_CALL(env, napi_get_boolean(env, value, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_get_boolean(env, value, &output)); return output; } -static napi_value AsInt32(napi_env env, napi_callback_info info) { +static node_api_value AsInt32(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); int32_t value; - NAPI_CALL(env, napi_get_value_int32(env, args[0], &value)); + NODE_API_CALL(env, node_api_get_value_int32(env, args[0], &value)); - napi_value output; - NAPI_CALL(env, napi_create_int32(env, value, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_int32(env, value, &output)); return output; } -static napi_value AsUInt32(napi_env env, napi_callback_info info) { +static node_api_value AsUInt32(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); uint32_t value; - NAPI_CALL(env, napi_get_value_uint32(env, args[0], &value)); + NODE_API_CALL(env, node_api_get_value_uint32(env, args[0], &value)); - napi_value output; - NAPI_CALL(env, napi_create_uint32(env, value, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_uint32(env, value, &output)); return output; } -static napi_value AsInt64(napi_env env, napi_callback_info info) { +static node_api_value AsInt64(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); int64_t value; - NAPI_CALL(env, napi_get_value_int64(env, args[0], &value)); + NODE_API_CALL(env, node_api_get_value_int64(env, args[0], &value)); - napi_value output; - NAPI_CALL(env, napi_create_int64(env, (double)value, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_int64(env, (double)value, &output)); return output; } -static napi_value AsDouble(napi_env env, napi_callback_info info) { +static node_api_value AsDouble(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); double value; - NAPI_CALL(env, napi_get_value_double(env, args[0], &value)); + NODE_API_CALL(env, node_api_get_value_double(env, args[0], &value)); - napi_value output; - NAPI_CALL(env, napi_create_double(env, value, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_double(env, value, &output)); return output; } -static napi_value AsString(napi_env env, napi_callback_info info) { +static node_api_value AsString(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); char value[100]; - NAPI_CALL(env, - napi_get_value_string_utf8(env, args[0], value, sizeof(value), NULL)); + NODE_API_CALL(env, + node_api_get_value_string_utf8(env, args[0], value, sizeof(value), NULL)); - napi_value output; - NAPI_CALL(env, napi_create_string_utf8( - env, value, NAPI_AUTO_LENGTH, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_string_utf8( + env, value, NODE_API_AUTO_LENGTH, &output)); return output; } -static napi_value ToBool(napi_env env, napi_callback_info info) { +static node_api_value ToBool(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value output; - NAPI_CALL(env, napi_coerce_to_bool(env, args[0], &output)); + node_api_value output; + NODE_API_CALL(env, node_api_coerce_to_bool(env, args[0], &output)); return output; } -static napi_value ToNumber(napi_env env, napi_callback_info info) { +static node_api_value ToNumber(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value output; - NAPI_CALL(env, napi_coerce_to_number(env, args[0], &output)); + node_api_value output; + NODE_API_CALL(env, node_api_coerce_to_number(env, args[0], &output)); return output; } -static napi_value ToObject(napi_env env, napi_callback_info info) { +static node_api_value ToObject(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value output; - NAPI_CALL(env, napi_coerce_to_object(env, args[0], &output)); + node_api_value output; + NODE_API_CALL(env, node_api_coerce_to_object(env, args[0], &output)); return output; } -static napi_value ToString(napi_env env, napi_callback_info info) { +static node_api_value ToString(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value output; - NAPI_CALL(env, napi_coerce_to_string(env, args[0], &output)); + node_api_value output; + NODE_API_CALL(env, node_api_coerce_to_string(env, args[0], &output)); return output; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("asBool", AsBool), - DECLARE_NAPI_PROPERTY("asInt32", AsInt32), - DECLARE_NAPI_PROPERTY("asUInt32", AsUInt32), - DECLARE_NAPI_PROPERTY("asInt64", AsInt64), - DECLARE_NAPI_PROPERTY("asDouble", AsDouble), - DECLARE_NAPI_PROPERTY("asString", AsString), - DECLARE_NAPI_PROPERTY("toBool", ToBool), - DECLARE_NAPI_PROPERTY("toNumber", ToNumber), - DECLARE_NAPI_PROPERTY("toObject", ToObject), - DECLARE_NAPI_PROPERTY("toString", ToString), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("asBool", AsBool), + DECLARE_NODE_API_PROPERTY("asInt32", AsInt32), + DECLARE_NODE_API_PROPERTY("asUInt32", AsUInt32), + DECLARE_NODE_API_PROPERTY("asInt64", AsInt64), + DECLARE_NODE_API_PROPERTY("asDouble", AsDouble), + DECLARE_NODE_API_PROPERTY("asString", AsString), + DECLARE_NODE_API_PROPERTY("toBool", ToBool), + DECLARE_NODE_API_PROPERTY("toNumber", ToNumber), + DECLARE_NODE_API_PROPERTY("toObject", ToObject), + DECLARE_NODE_API_PROPERTY("toString", ToString), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); init_test_null(env, exports); diff --git a/test/js-native-api/test_conversions/test_null.c b/test/js-native-api/test_conversions/test_null.c index 9cf73bc2d4980f..bdca8c28acd830 100644 --- a/test/js-native-api/test_conversions/test_null.c +++ b/test/js-native-api/test_conversions/test_null.c @@ -4,15 +4,16 @@ #include "test_null.h" #define GEN_NULL_CHECK_BINDING(binding_name, output_type, api) \ - static napi_value binding_name(napi_env env, napi_callback_info info) { \ - napi_value return_value; \ + static node_api_value \ + binding_name(node_api_env env, node_api_callback_info info) { \ + node_api_value return_value; \ output_type result; \ - NAPI_CALL(env, napi_create_object(env, &return_value)); \ + NODE_API_CALL(env, node_api_create_object(env, &return_value)); \ add_returned_status(env, \ "envIsNull", \ return_value, \ "Invalid argument", \ - napi_invalid_arg, \ + node_api_invalid_arg, \ api(NULL, return_value, &result)); \ api(env, NULL, &result); \ add_last_status(env, "valueIsNull", return_value); \ @@ -23,26 +24,29 @@ return return_value; \ } -GEN_NULL_CHECK_BINDING(GetValueBool, bool, napi_get_value_bool) -GEN_NULL_CHECK_BINDING(GetValueInt32, int32_t, napi_get_value_int32) -GEN_NULL_CHECK_BINDING(GetValueUint32, uint32_t, napi_get_value_uint32) -GEN_NULL_CHECK_BINDING(GetValueInt64, int64_t, napi_get_value_int64) -GEN_NULL_CHECK_BINDING(GetValueDouble, double, napi_get_value_double) -GEN_NULL_CHECK_BINDING(CoerceToBool, napi_value, napi_coerce_to_bool) -GEN_NULL_CHECK_BINDING(CoerceToObject, napi_value, napi_coerce_to_object) -GEN_NULL_CHECK_BINDING(CoerceToString, napi_value, napi_coerce_to_string) +GEN_NULL_CHECK_BINDING(GetValueBool, bool, node_api_get_value_bool) +GEN_NULL_CHECK_BINDING(GetValueInt32, int32_t, node_api_get_value_int32) +GEN_NULL_CHECK_BINDING(GetValueUint32, uint32_t, node_api_get_value_uint32) +GEN_NULL_CHECK_BINDING(GetValueInt64, int64_t, node_api_get_value_int64) +GEN_NULL_CHECK_BINDING(GetValueDouble, double, node_api_get_value_double) +GEN_NULL_CHECK_BINDING(CoerceToBool, node_api_value, node_api_coerce_to_bool) +GEN_NULL_CHECK_BINDING(CoerceToObject, node_api_value, + node_api_coerce_to_object) +GEN_NULL_CHECK_BINDING(CoerceToString, node_api_value, + node_api_coerce_to_string) #define GEN_NULL_CHECK_STRING_BINDING(binding_name, arg_type, api) \ - static napi_value binding_name(napi_env env, napi_callback_info info) { \ - napi_value return_value; \ - NAPI_CALL(env, napi_create_object(env, &return_value)); \ + static node_api_value \ + binding_name(node_api_env env, node_api_callback_info info) { \ + node_api_value return_value; \ + NODE_API_CALL(env, node_api_create_object(env, &return_value)); \ arg_type buf1[4]; \ size_t length1 = 3; \ add_returned_status(env, \ "envIsNull", \ return_value, \ "Invalid argument", \ - napi_invalid_arg, \ + node_api_invalid_arg, \ api(NULL, return_value, buf1, length1, &length1)); \ arg_type buf2[4]; \ size_t length2 = 3; \ @@ -50,11 +54,11 @@ GEN_NULL_CHECK_BINDING(CoerceToString, napi_value, napi_coerce_to_string) add_last_status(env, "valueIsNull", return_value); \ api(env, return_value, NULL, 3, NULL); \ add_last_status(env, "wrongTypeIn", return_value); \ - napi_value string; \ - NAPI_CALL(env, \ - napi_create_string_utf8(env, \ + node_api_value string; \ + NODE_API_CALL(env, \ + node_api_create_string_utf8(env, \ "Something", \ - NAPI_AUTO_LENGTH, \ + NODE_API_AUTO_LENGTH, \ &string)); \ api(env, string, NULL, 3, NULL); \ add_last_status(env, "bufAndOutLengthIsNull", return_value); \ @@ -63,40 +67,40 @@ GEN_NULL_CHECK_BINDING(CoerceToString, napi_value, napi_coerce_to_string) GEN_NULL_CHECK_STRING_BINDING(GetValueStringUtf8, char, - napi_get_value_string_utf8) + node_api_get_value_string_utf8) GEN_NULL_CHECK_STRING_BINDING(GetValueStringLatin1, char, - napi_get_value_string_latin1) + node_api_get_value_string_latin1) GEN_NULL_CHECK_STRING_BINDING(GetValueStringUtf16, char16_t, - napi_get_value_string_utf16) + node_api_get_value_string_utf16) -void init_test_null(napi_env env, napi_value exports) { - napi_value test_null; +void init_test_null(node_api_env env, node_api_value exports) { + node_api_value test_null; - const napi_property_descriptor test_null_props[] = { - DECLARE_NAPI_PROPERTY("getValueBool", GetValueBool), - DECLARE_NAPI_PROPERTY("getValueInt32", GetValueInt32), - DECLARE_NAPI_PROPERTY("getValueUint32", GetValueUint32), - DECLARE_NAPI_PROPERTY("getValueInt64", GetValueInt64), - DECLARE_NAPI_PROPERTY("getValueDouble", GetValueDouble), - DECLARE_NAPI_PROPERTY("coerceToBool", CoerceToBool), - DECLARE_NAPI_PROPERTY("coerceToObject", CoerceToObject), - DECLARE_NAPI_PROPERTY("coerceToString", CoerceToString), - DECLARE_NAPI_PROPERTY("getValueStringUtf8", GetValueStringUtf8), - DECLARE_NAPI_PROPERTY("getValueStringLatin1", GetValueStringLatin1), - DECLARE_NAPI_PROPERTY("getValueStringUtf16", GetValueStringUtf16), + const node_api_property_descriptor test_null_props[] = { + DECLARE_NODE_API_PROPERTY("getValueBool", GetValueBool), + DECLARE_NODE_API_PROPERTY("getValueInt32", GetValueInt32), + DECLARE_NODE_API_PROPERTY("getValueUint32", GetValueUint32), + DECLARE_NODE_API_PROPERTY("getValueInt64", GetValueInt64), + DECLARE_NODE_API_PROPERTY("getValueDouble", GetValueDouble), + DECLARE_NODE_API_PROPERTY("coerceToBool", CoerceToBool), + DECLARE_NODE_API_PROPERTY("coerceToObject", CoerceToObject), + DECLARE_NODE_API_PROPERTY("coerceToString", CoerceToString), + DECLARE_NODE_API_PROPERTY("getValueStringUtf8", GetValueStringUtf8), + DECLARE_NODE_API_PROPERTY("getValueStringLatin1", GetValueStringLatin1), + DECLARE_NODE_API_PROPERTY("getValueStringUtf16", GetValueStringUtf16), }; - NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &test_null)); - NAPI_CALL_RETURN_VOID(env, napi_define_properties( + NODE_API_CALL_RETURN_VOID(env, node_api_create_object(env, &test_null)); + NODE_API_CALL_RETURN_VOID(env, node_api_define_properties( env, test_null, sizeof(test_null_props) / sizeof(*test_null_props), test_null_props)); - const napi_property_descriptor test_null_set = { - "testNull", NULL, NULL, NULL, NULL, test_null, napi_enumerable, NULL + const node_api_property_descriptor test_null_set = { + "testNull", NULL, NULL, NULL, NULL, test_null, node_api_enumerable, NULL }; - NAPI_CALL_RETURN_VOID(env, - napi_define_properties(env, exports, 1, &test_null_set)); + NODE_API_CALL_RETURN_VOID(env, + node_api_define_properties(env, exports, 1, &test_null_set)); } diff --git a/test/js-native-api/test_conversions/test_null.h b/test/js-native-api/test_conversions/test_null.h index 977efdd534c4ae..d0b31b26fb02b1 100644 --- a/test/js-native-api/test_conversions/test_null.h +++ b/test/js-native-api/test_conversions/test_null.h @@ -3,6 +3,6 @@ #include -void init_test_null(napi_env env, napi_value exports); +void init_test_null(node_api_env env, node_api_value exports); #endif // TEST_JS_NATIVE_API_TEST_CONVERSIONS_TEST_NULL_H_ diff --git a/test/js-native-api/test_dataview/test_dataview.c b/test/js-native-api/test_dataview/test_dataview.c index ff3b42e63aec1e..2bc25fea7e0ee3 100644 --- a/test/js-native-api/test_dataview/test_dataview.c +++ b/test/js-native-api/test_dataview/test_dataview.c @@ -2,98 +2,99 @@ #include #include "../common.h" -static napi_value CreateDataView(napi_env env, napi_callback_info info) { +static node_api_value +CreateDataView(node_api_env env, node_api_callback_info info) { size_t argc = 3; - napi_value args [3]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args [3]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 3, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 3, "Wrong number of arguments"); - napi_valuetype valuetype0; - napi_value arraybuffer = args[0]; + node_api_valuetype valuetype0; + node_api_value arraybuffer = args[0]; - NAPI_CALL(env, napi_typeof(env, arraybuffer, &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, - "Wrong type of arguments. Expects a ArrayBuffer as the first " - "argument."); + NODE_API_CALL(env, node_api_typeof(env, arraybuffer, &valuetype0)); + NODE_API_ASSERT(env, valuetype0 == node_api_object, + "Wrong type of arguments. Expects a ArrayBuffer as the first argument."); bool is_arraybuffer; - NAPI_CALL(env, napi_is_arraybuffer(env, arraybuffer, &is_arraybuffer)); - NAPI_ASSERT(env, is_arraybuffer, - "Wrong type of arguments. Expects a ArrayBuffer as the first " - "argument."); + NODE_API_CALL(env, + node_api_is_arraybuffer(env, arraybuffer, &is_arraybuffer)); + NODE_API_ASSERT(env, is_arraybuffer, + "Wrong type of arguments. Expects a ArrayBuffer as the first argument."); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + node_api_valuetype valuetype1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); - NAPI_ASSERT(env, valuetype1 == napi_number, + NODE_API_ASSERT(env, valuetype1 == node_api_number, "Wrong type of arguments. Expects a number as second argument."); size_t byte_offset = 0; - NAPI_CALL(env, napi_get_value_uint32(env, args[1], (uint32_t*)(&byte_offset))); + NODE_API_CALL(env, + node_api_get_value_uint32(env, args[1], (uint32_t*)(&byte_offset))); - napi_valuetype valuetype2; - NAPI_CALL(env, napi_typeof(env, args[2], &valuetype2)); + node_api_valuetype valuetype2; + NODE_API_CALL(env, node_api_typeof(env, args[2], &valuetype2)); - NAPI_ASSERT(env, valuetype2 == napi_number, + NODE_API_ASSERT(env, valuetype2 == node_api_number, "Wrong type of arguments. Expects a number as third argument."); size_t length = 0; - NAPI_CALL(env, napi_get_value_uint32(env, args[2], (uint32_t*)(&length))); + NODE_API_CALL(env, + node_api_get_value_uint32(env, args[2], (uint32_t*)(&length))); - napi_value output_dataview; - NAPI_CALL(env, - napi_create_dataview(env, length, arraybuffer, - byte_offset, &output_dataview)); + node_api_value output_dataview; + NODE_API_CALL(env, + node_api_create_dataview(env, length, arraybuffer, byte_offset, + &output_dataview)); return output_dataview; } -static napi_value CreateDataViewFromJSDataView(napi_env env, napi_callback_info info) { +static node_api_value +CreateDataViewFromJSDataView(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args [1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args [1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments"); - napi_valuetype valuetype; - napi_value input_dataview = args[0]; + node_api_valuetype valuetype; + node_api_value input_dataview = args[0]; - NAPI_CALL(env, napi_typeof(env, input_dataview, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, - "Wrong type of arguments. Expects a DataView as the first " - "argument."); + NODE_API_CALL(env, node_api_typeof(env, input_dataview, &valuetype)); + NODE_API_ASSERT(env, valuetype == node_api_object, + "Wrong type of arguments. Expects a DataView as the first argument."); bool is_dataview; - NAPI_CALL(env, napi_is_dataview(env, input_dataview, &is_dataview)); - NAPI_ASSERT(env, is_dataview, - "Wrong type of arguments. Expects a DataView as the first " - "argument."); + NODE_API_CALL(env, node_api_is_dataview(env, input_dataview, &is_dataview)); + NODE_API_ASSERT(env, is_dataview, + "Wrong type of arguments. Expects a DataView as the first argument."); size_t byte_offset = 0; size_t length = 0; - napi_value buffer; - NAPI_CALL(env, - napi_get_dataview_info(env, input_dataview, &length, NULL, - &buffer, &byte_offset)); + node_api_value buffer; + NODE_API_CALL(env, + node_api_get_dataview_info(env, input_dataview, &length, NULL, &buffer, + &byte_offset)); - napi_value output_dataview; - NAPI_CALL(env, - napi_create_dataview(env, length, buffer, - byte_offset, &output_dataview)); + node_api_value output_dataview; + NODE_API_CALL(env, + node_api_create_dataview(env, length, buffer, byte_offset, + &output_dataview)); return output_dataview; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("CreateDataView", CreateDataView), - DECLARE_NAPI_PROPERTY("CreateDataViewFromJSDataView", +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("CreateDataView", CreateDataView), + DECLARE_NODE_API_PROPERTY("CreateDataViewFromJSDataView", CreateDataViewFromJSDataView) }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/js-native-api/test_date/test_date.c b/test/js-native-api/test_date/test_date.c index 7ac5008cb9b288..414a357d242869 100644 --- a/test/js-native-api/test_date/test_date.c +++ b/test/js-native-api/test_date/test_date.c @@ -1,61 +1,65 @@ #include #include "../common.h" -static napi_value createDate(napi_env env, napi_callback_info info) { +static node_api_value +createDate(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_number, - "Wrong type of arguments. Expects a number as first argument."); + NODE_API_ASSERT(env, valuetype0 == node_api_number, + "Wrong type of arguments. Expects a number as first argument."); double time; - NAPI_CALL(env, napi_get_value_double(env, args[0], &time)); + NODE_API_CALL(env, node_api_get_value_double(env, args[0], &time)); - napi_value date; - NAPI_CALL(env, napi_create_date(env, time, &date)); + node_api_value date; + NODE_API_CALL(env, node_api_create_date(env, time, &date)); return date; } -static napi_value isDate(napi_env env, napi_callback_info info) { - napi_value date, result; +static node_api_value isDate(node_api_env env, node_api_callback_info info) { + node_api_value date, result; size_t argc = 1; bool is_date; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &date, NULL, NULL)); - NAPI_CALL(env, napi_is_date(env, date, &is_date)); - NAPI_CALL(env, napi_get_boolean(env, is_date, &result)); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &date, NULL, NULL)); + NODE_API_CALL(env, node_api_is_date(env, date, &is_date)); + NODE_API_CALL(env, node_api_get_boolean(env, is_date, &result)); return result; } -static napi_value getDateValue(napi_env env, napi_callback_info info) { - napi_value date, result; +static node_api_value +getDateValue(node_api_env env, node_api_callback_info info) { + node_api_value date, result; size_t argc = 1; double value; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &date, NULL, NULL)); - NAPI_CALL(env, napi_get_date_value(env, date, &value)); - NAPI_CALL(env, napi_create_double(env, value, &result)); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &date, NULL, NULL)); + NODE_API_CALL(env, node_api_get_date_value(env, date, &value)); + NODE_API_CALL(env, node_api_create_double(env, value, &result)); return result; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("createDate", createDate), - DECLARE_NAPI_PROPERTY("isDate", isDate), - DECLARE_NAPI_PROPERTY("getDateValue", getDateValue), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("createDate", createDate), + DECLARE_NODE_API_PROPERTY("isDate", isDate), + DECLARE_NODE_API_PROPERTY("getDateValue", getDateValue), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/js-native-api/test_error/test_error.c b/test/js-native-api/test_error/test_error.c index bb55272c537468..8a113f7110eb2d 100644 --- a/test/js-native-api/test_error/test_error.c +++ b/test/js-native-api/test_error/test_error.c @@ -1,161 +1,178 @@ #include #include "../common.h" -static napi_value checkError(napi_env env, napi_callback_info info) { +static node_api_value +checkError(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); bool r; - NAPI_CALL(env, napi_is_error(env, args[0], &r)); + NODE_API_CALL(env, node_api_is_error(env, args[0], &r)); - napi_value result; - NAPI_CALL(env, napi_get_boolean(env, r, &result)); + node_api_value result; + NODE_API_CALL(env, node_api_get_boolean(env, r, &result)); return result; } -static napi_value throwExistingError(napi_env env, napi_callback_info info) { - napi_value message; - napi_value error; - NAPI_CALL(env, napi_create_string_utf8( - env, "existing error", NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_error(env, NULL, message, &error)); - NAPI_CALL(env, napi_throw(env, error)); +static node_api_value +throwExistingError(node_api_env env, node_api_callback_info info) { + node_api_value message; + node_api_value error; + NODE_API_CALL(env, node_api_create_string_utf8( + env, "existing error", NODE_API_AUTO_LENGTH, &message)); + NODE_API_CALL(env, node_api_create_error(env, NULL, message, &error)); + NODE_API_CALL(env, node_api_throw(env, error)); return NULL; } -static napi_value throwError(napi_env env, napi_callback_info info) { - NAPI_CALL(env, napi_throw_error(env, NULL, "error")); +static node_api_value +throwError(node_api_env env, node_api_callback_info info) { + NODE_API_CALL(env, node_api_throw_error(env, NULL, "error")); return NULL; } -static napi_value throwRangeError(napi_env env, napi_callback_info info) { - NAPI_CALL(env, napi_throw_range_error(env, NULL, "range error")); +static node_api_value +throwRangeError(node_api_env env, node_api_callback_info info) { + NODE_API_CALL(env, node_api_throw_range_error(env, NULL, "range error")); return NULL; } -static napi_value throwTypeError(napi_env env, napi_callback_info info) { - NAPI_CALL(env, napi_throw_type_error(env, NULL, "type error")); +static node_api_value +throwTypeError(node_api_env env, node_api_callback_info info) { + NODE_API_CALL(env, node_api_throw_type_error(env, NULL, "type error")); return NULL; } -static napi_value throwErrorCode(napi_env env, napi_callback_info info) { - NAPI_CALL(env, napi_throw_error(env, "ERR_TEST_CODE", "Error [error]")); +static node_api_value +throwErrorCode(node_api_env env, node_api_callback_info info) { + NODE_API_CALL(env, + node_api_throw_error(env, "ERR_TEST_CODE", "Error [error]")); return NULL; } -static napi_value throwRangeErrorCode(napi_env env, napi_callback_info info) { - NAPI_CALL(env, napi_throw_range_error(env, - "ERR_TEST_CODE", - "RangeError [range error]")); +static node_api_value +throwRangeErrorCode(node_api_env env, node_api_callback_info info) { + NODE_API_CALL(env, node_api_throw_range_error(env, + "ERR_TEST_CODE", + "RangeError [range error]")); return NULL; } -static napi_value throwTypeErrorCode(napi_env env, napi_callback_info info) { - NAPI_CALL(env, napi_throw_type_error(env, - "ERR_TEST_CODE", - "TypeError [type error]")); +static node_api_value +throwTypeErrorCode(node_api_env env, node_api_callback_info info) { + NODE_API_CALL(env, node_api_throw_type_error(env, + "ERR_TEST_CODE", + "TypeError [type error]")); return NULL; } -static napi_value createError(napi_env env, napi_callback_info info) { - napi_value result; - napi_value message; - NAPI_CALL(env, napi_create_string_utf8( - env, "error", NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_error(env, NULL, message, &result)); +static node_api_value +createError(node_api_env env, node_api_callback_info info) { + node_api_value result; + node_api_value message; + NODE_API_CALL(env, node_api_create_string_utf8( + env, "error", NODE_API_AUTO_LENGTH, &message)); + NODE_API_CALL(env, node_api_create_error(env, NULL, message, &result)); return result; } -static napi_value createRangeError(napi_env env, napi_callback_info info) { - napi_value result; - napi_value message; - NAPI_CALL(env, napi_create_string_utf8( - env, "range error", NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_range_error(env, NULL, message, &result)); +static node_api_value +createRangeError(node_api_env env, node_api_callback_info info) { + node_api_value result; + node_api_value message; + NODE_API_CALL(env, node_api_create_string_utf8( + env, "range error", NODE_API_AUTO_LENGTH, &message)); + NODE_API_CALL(env, node_api_create_range_error(env, NULL, message, &result)); return result; } -static napi_value createTypeError(napi_env env, napi_callback_info info) { - napi_value result; - napi_value message; - NAPI_CALL(env, napi_create_string_utf8( - env, "type error", NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_type_error(env, NULL, message, &result)); +static node_api_value +createTypeError(node_api_env env, node_api_callback_info info) { + node_api_value result; + node_api_value message; + NODE_API_CALL(env, node_api_create_string_utf8( + env, "type error", NODE_API_AUTO_LENGTH, &message)); + NODE_API_CALL(env, node_api_create_type_error(env, NULL, message, &result)); return result; } -static napi_value createErrorCode(napi_env env, napi_callback_info info) { - napi_value result; - napi_value message; - napi_value code; - NAPI_CALL(env, napi_create_string_utf8( - env, "Error [error]", NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_string_utf8( - env, "ERR_TEST_CODE", NAPI_AUTO_LENGTH, &code)); - NAPI_CALL(env, napi_create_error(env, code, message, &result)); +static node_api_value +createErrorCode(node_api_env env, node_api_callback_info info) { + node_api_value result; + node_api_value message; + node_api_value code; + NODE_API_CALL(env, node_api_create_string_utf8( + env, "Error [error]", NODE_API_AUTO_LENGTH, &message)); + NODE_API_CALL(env, node_api_create_string_utf8( + env, "ERR_TEST_CODE", NODE_API_AUTO_LENGTH, &code)); + NODE_API_CALL(env, node_api_create_error(env, code, message, &result)); return result; } -static napi_value createRangeErrorCode(napi_env env, napi_callback_info info) { - napi_value result; - napi_value message; - napi_value code; - NAPI_CALL(env, napi_create_string_utf8(env, - "RangeError [range error]", - NAPI_AUTO_LENGTH, - &message)); - NAPI_CALL(env, napi_create_string_utf8( - env, "ERR_TEST_CODE", NAPI_AUTO_LENGTH, &code)); - NAPI_CALL(env, napi_create_range_error(env, code, message, &result)); +static node_api_value +createRangeErrorCode(node_api_env env, node_api_callback_info info) { + node_api_value result; + node_api_value message; + node_api_value code; + NODE_API_CALL(env, node_api_create_string_utf8(env, + "RangeError [range error]", + NODE_API_AUTO_LENGTH, + &message)); + NODE_API_CALL(env, node_api_create_string_utf8( + env, "ERR_TEST_CODE", NODE_API_AUTO_LENGTH, &code)); + NODE_API_CALL(env, node_api_create_range_error(env, code, message, &result)); return result; } -static napi_value createTypeErrorCode(napi_env env, napi_callback_info info) { - napi_value result; - napi_value message; - napi_value code; - NAPI_CALL(env, napi_create_string_utf8(env, - "TypeError [type error]", - NAPI_AUTO_LENGTH, - &message)); - NAPI_CALL(env, napi_create_string_utf8( - env, "ERR_TEST_CODE", NAPI_AUTO_LENGTH, &code)); - NAPI_CALL(env, napi_create_type_error(env, code, message, &result)); +static node_api_value +createTypeErrorCode(node_api_env env, node_api_callback_info info) { + node_api_value result; + node_api_value message; + node_api_value code; + NODE_API_CALL(env, node_api_create_string_utf8(env, + "TypeError [type error]", + NODE_API_AUTO_LENGTH, + &message)); + NODE_API_CALL(env, node_api_create_string_utf8( + env, "ERR_TEST_CODE", NODE_API_AUTO_LENGTH, &code)); + NODE_API_CALL(env, node_api_create_type_error(env, code, message, &result)); return result; } -static napi_value throwArbitrary(napi_env env, napi_callback_info info) { - napi_value arbitrary; +static node_api_value +throwArbitrary(node_api_env env, node_api_callback_info info) { + node_api_value arbitrary; size_t argc = 1; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arbitrary, NULL, NULL)); - NAPI_CALL(env, napi_throw(env, arbitrary)); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &arbitrary, NULL, NULL)); + NODE_API_CALL(env, node_api_throw(env, arbitrary)); return NULL; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("checkError", checkError), - DECLARE_NAPI_PROPERTY("throwExistingError", throwExistingError), - DECLARE_NAPI_PROPERTY("throwError", throwError), - DECLARE_NAPI_PROPERTY("throwRangeError", throwRangeError), - DECLARE_NAPI_PROPERTY("throwTypeError", throwTypeError), - DECLARE_NAPI_PROPERTY("throwErrorCode", throwErrorCode), - DECLARE_NAPI_PROPERTY("throwRangeErrorCode", throwRangeErrorCode), - DECLARE_NAPI_PROPERTY("throwTypeErrorCode", throwTypeErrorCode), - DECLARE_NAPI_PROPERTY("throwArbitrary", throwArbitrary), - DECLARE_NAPI_PROPERTY("createError", createError), - DECLARE_NAPI_PROPERTY("createRangeError", createRangeError), - DECLARE_NAPI_PROPERTY("createTypeError", createTypeError), - DECLARE_NAPI_PROPERTY("createErrorCode", createErrorCode), - DECLARE_NAPI_PROPERTY("createRangeErrorCode", createRangeErrorCode), - DECLARE_NAPI_PROPERTY("createTypeErrorCode", createTypeErrorCode), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("checkError", checkError), + DECLARE_NODE_API_PROPERTY("throwExistingError", throwExistingError), + DECLARE_NODE_API_PROPERTY("throwError", throwError), + DECLARE_NODE_API_PROPERTY("throwRangeError", throwRangeError), + DECLARE_NODE_API_PROPERTY("throwTypeError", throwTypeError), + DECLARE_NODE_API_PROPERTY("throwErrorCode", throwErrorCode), + DECLARE_NODE_API_PROPERTY("throwRangeErrorCode", throwRangeErrorCode), + DECLARE_NODE_API_PROPERTY("throwTypeErrorCode", throwTypeErrorCode), + DECLARE_NODE_API_PROPERTY("throwArbitrary", throwArbitrary), + DECLARE_NODE_API_PROPERTY("createError", createError), + DECLARE_NODE_API_PROPERTY("createRangeError", createRangeError), + DECLARE_NODE_API_PROPERTY("createTypeError", createTypeError), + DECLARE_NODE_API_PROPERTY("createErrorCode", createErrorCode), + DECLARE_NODE_API_PROPERTY("createRangeErrorCode", createRangeErrorCode), + DECLARE_NODE_API_PROPERTY("createTypeErrorCode", createTypeErrorCode), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/js-native-api/test_exception/test_exception.c b/test/js-native-api/test_exception/test_exception.c index 01adf42c942b8f..14a4df46398726 100644 --- a/test/js-native-api/test_exception/test_exception.c +++ b/test/js-native-api/test_exception/test_exception.c @@ -3,80 +3,85 @@ static bool exceptionWasPending = false; -static napi_value returnException(napi_env env, napi_callback_info info) { +static node_api_value +returnException(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - - napi_value global; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value result; - napi_status status = napi_call_function(env, global, args[0], 0, 0, &result); - if (status == napi_pending_exception) { - napi_value ex; - NAPI_CALL(env, napi_get_and_clear_last_exception(env, &ex)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); + + node_api_value global; + NODE_API_CALL(env, node_api_get_global(env, &global)); + + node_api_value result; + node_api_status status = node_api_call_function( + env, global, args[0], 0, 0, &result); + if (status == node_api_pending_exception) { + node_api_value ex; + NODE_API_CALL(env, node_api_get_and_clear_last_exception(env, &ex)); return ex; } return NULL; } -static napi_value allowException(napi_env env, napi_callback_info info) { +static node_api_value +allowException(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value global; - NAPI_CALL(env, napi_get_global(env, &global)); + node_api_value global; + NODE_API_CALL(env, node_api_get_global(env, &global)); - napi_value result; - napi_call_function(env, global, args[0], 0, 0, &result); - // Ignore status and check napi_is_exception_pending() instead. + node_api_value result; + node_api_call_function(env, global, args[0], 0, 0, &result); + // Ignore status and check node_api_is_exception_pending() instead. - NAPI_CALL(env, napi_is_exception_pending(env, &exceptionWasPending)); + NODE_API_CALL(env, node_api_is_exception_pending(env, &exceptionWasPending)); return NULL; } -static napi_value wasPending(napi_env env, napi_callback_info info) { - napi_value result; - NAPI_CALL(env, napi_get_boolean(env, exceptionWasPending, &result)); +static node_api_value +wasPending(node_api_env env, node_api_callback_info info) { + node_api_value result; + NODE_API_CALL(env, node_api_get_boolean(env, exceptionWasPending, &result)); return result; } -static void finalizer(napi_env env, void *data, void *hint) { - NAPI_CALL_RETURN_VOID(env, - napi_throw_error(env, NULL, "Error during Finalize")); +static void finalizer(node_api_env env, void *data, void *hint) { + NODE_API_CALL_RETURN_VOID(env, + node_api_throw_error(env, NULL, "Error during Finalize")); } -static napi_value createExternal(napi_env env, napi_callback_info info) { - napi_value external; +static node_api_value +createExternal(node_api_env env, node_api_callback_info info) { + node_api_value external; - NAPI_CALL(env, - napi_create_external(env, NULL, finalizer, NULL, &external)); + NODE_API_CALL(env, + node_api_create_external(env, NULL, finalizer, NULL, &external)); return external; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("returnException", returnException), - DECLARE_NAPI_PROPERTY("allowException", allowException), - DECLARE_NAPI_PROPERTY("wasPending", wasPending), - DECLARE_NAPI_PROPERTY("createExternal", createExternal), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("returnException", returnException), + DECLARE_NODE_API_PROPERTY("allowException", allowException), + DECLARE_NODE_API_PROPERTY("wasPending", wasPending), + DECLARE_NODE_API_PROPERTY("createExternal", createExternal), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); - napi_value error, code, message; - NAPI_CALL(env, napi_create_string_utf8(env, "Error during Init", - NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &code)); - NAPI_CALL(env, napi_create_error(env, code, message, &error)); - NAPI_CALL(env, napi_set_named_property(env, error, "binding", exports)); - NAPI_CALL(env, napi_throw(env, error)); + node_api_value error, code, message; + NODE_API_CALL(env, node_api_create_string_utf8(env, "Error during Init", + NODE_API_AUTO_LENGTH, &message)); + NODE_API_CALL(env, node_api_create_string_utf8(env, "", NODE_API_AUTO_LENGTH, &code)); + NODE_API_CALL(env, node_api_create_error(env, code, message, &error)); + NODE_API_CALL(env, node_api_set_named_property(env, error, "binding", exports)); + NODE_API_CALL(env, node_api_throw(env, error)); return exports; } diff --git a/test/js-native-api/test_function/test.js b/test/js-native-api/test_function/test.js index 988f128404e429..a26d71bf1760b5 100644 --- a/test/js-native-api/test_function/test.js +++ b/test/js-native-api/test_function/test.js @@ -38,7 +38,7 @@ global.gc(); assert.deepStrictEqual(test_function.TestCreateFunctionParameters(), { envIsNull: 'Invalid argument', - nameIsNull: 'napi_ok', + nameIsNull: 'node_api_ok', cbIsNull: 'Invalid argument', resultIsNull: 'Invalid argument' }); diff --git a/test/js-native-api/test_function/test_function.c b/test/js-native-api/test_function/test_function.c index 713e935e08c972..ff3d8545eb9c6c 100644 --- a/test/js-native-api/test_function/test_function.c +++ b/test/js-native-api/test_function/test_function.c @@ -1,200 +1,203 @@ #include #include "../common.h" -static napi_value TestCreateFunctionParameters(napi_env env, - napi_callback_info info) { - napi_status status; - napi_value result, return_value; +static node_api_value +TestCreateFunctionParameters(node_api_env env, node_api_callback_info info) { + node_api_status status; + node_api_value result, return_value; - NAPI_CALL(env, napi_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); - status = napi_create_function(NULL, - "TrackedFunction", - NAPI_AUTO_LENGTH, - TestCreateFunctionParameters, - NULL, - &result); + status = node_api_create_function(NULL, + "TrackedFunction", + NODE_API_AUTO_LENGTH, + TestCreateFunctionParameters, + NULL, + &result); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, + node_api_invalid_arg, status); - napi_create_function(env, - NULL, - NAPI_AUTO_LENGTH, - TestCreateFunctionParameters, - NULL, - &result); + node_api_create_function(env, + NULL, + NODE_API_AUTO_LENGTH, + TestCreateFunctionParameters, + NULL, + &result); add_last_status(env, "nameIsNull", return_value); - napi_create_function(env, - "TrackedFunction", - NAPI_AUTO_LENGTH, - NULL, - NULL, - &result); + node_api_create_function(env, + "TrackedFunction", + NODE_API_AUTO_LENGTH, + NULL, + NULL, + &result); add_last_status(env, "cbIsNull", return_value); - napi_create_function(env, - "TrackedFunction", - NAPI_AUTO_LENGTH, - TestCreateFunctionParameters, - NULL, - NULL); + node_api_create_function(env, + "TrackedFunction", + NODE_API_AUTO_LENGTH, + TestCreateFunctionParameters, + NULL, + NULL); add_last_status(env, "resultIsNull", return_value); return return_value; } -static napi_value TestCallFunction(napi_env env, napi_callback_info info) { +static node_api_value +TestCallFunction(node_api_env env, node_api_callback_info info) { size_t argc = 10; - napi_value args[10]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[10]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc > 0, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_function, + NODE_API_ASSERT(env, valuetype0 == node_api_function, "Wrong type of arguments. Expects a function as first argument."); - napi_value* argv = args + 1; + node_api_value* argv = args + 1; argc = argc - 1; - napi_value global; - NAPI_CALL(env, napi_get_global(env, &global)); + node_api_value global; + NODE_API_CALL(env, node_api_get_global(env, &global)); - napi_value result; - NAPI_CALL(env, napi_call_function(env, global, args[0], argc, argv, &result)); + node_api_value result; + NODE_API_CALL(env, + node_api_call_function(env, global, args[0], argc, argv, &result)); return result; } -static napi_value TestFunctionName(napi_env env, napi_callback_info info) { +static node_api_value +TestFunctionName(node_api_env env, node_api_callback_info info) { return NULL; } -static void finalize_function(napi_env env, void* data, void* hint) { - napi_ref ref = data; +static void finalize_function(node_api_env env, void* data, void* hint) { + node_api_ref ref = data; // Retrieve the JavaScript undefined value. - napi_value undefined; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + node_api_value undefined; + NODE_API_CALL_RETURN_VOID(env, node_api_get_undefined(env, &undefined)); // Retrieve the JavaScript function we must call. - napi_value js_function; - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, ref, &js_function)); + node_api_value js_function; + NODE_API_CALL_RETURN_VOID(env, + node_api_get_reference_value(env, ref, &js_function)); // Call the JavaScript function to indicate that the generated JavaScript // function is about to be gc-ed. - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, - undefined, - js_function, - 0, - NULL, - NULL)); + NODE_API_CALL_RETURN_VOID(env, + node_api_call_function(env, undefined, js_function, 0, NULL, NULL)); // Destroy the persistent reference to the function we just called so as to // properly clean up. - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, ref)); + NODE_API_CALL_RETURN_VOID(env, node_api_delete_reference(env, ref)); } -static napi_value MakeTrackedFunction(napi_env env, napi_callback_info info) { +static node_api_value +MakeTrackedFunction(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value js_finalize_cb; - napi_valuetype arg_type; + node_api_value js_finalize_cb; + node_api_valuetype arg_type; // Retrieve and validate from the arguments the function we will use to // indicate to JavaScript that the function we are about to create is about to // be gc-ed. - NAPI_CALL(env, napi_get_cb_info(env, - info, - &argc, - &js_finalize_cb, - NULL, - NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); - NAPI_CALL(env, napi_typeof(env, js_finalize_cb, &arg_type)); - NAPI_ASSERT(env, arg_type == napi_function, "Argument must be a function"); + NODE_API_CALL(env, node_api_get_cb_info(env, + info, + &argc, + &js_finalize_cb, + NULL, + NULL)); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments"); + NODE_API_CALL(env, node_api_typeof(env, js_finalize_cb, &arg_type)); + NODE_API_ASSERT(env, arg_type == node_api_function, + "Argument must be a function"); // Dynamically create a function. - napi_value result; - NAPI_CALL(env, napi_create_function(env, - "TrackedFunction", - NAPI_AUTO_LENGTH, - TestFunctionName, - NULL, - &result)); + node_api_value result; + NODE_API_CALL(env, node_api_create_function(env, + "TrackedFunction", + NODE_API_AUTO_LENGTH, + TestFunctionName, + NULL, + &result)); // Create a strong reference to the function we will call when the tracked // function is about to be gc-ed. - napi_ref js_finalize_cb_ref; - NAPI_CALL(env, napi_create_reference(env, - js_finalize_cb, - 1, - &js_finalize_cb_ref)); + node_api_ref js_finalize_cb_ref; + NODE_API_CALL(env, node_api_create_reference(env, + js_finalize_cb, + 1, + &js_finalize_cb_ref)); // Attach a finalizer to the dynamically created function and pass it the // strong reference we created in the previous step. - NAPI_CALL(env, napi_wrap(env, - result, - js_finalize_cb_ref, - finalize_function, - NULL, - NULL)); + NODE_API_CALL(env, node_api_wrap(env, + result, + js_finalize_cb_ref, + finalize_function, + NULL, + NULL)); return result; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_value fn1; - NAPI_CALL(env, napi_create_function( - env, NULL, NAPI_AUTO_LENGTH, TestCallFunction, NULL, &fn1)); +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_value fn1; + NODE_API_CALL(env, node_api_create_function( + env, NULL, NODE_API_AUTO_LENGTH, TestCallFunction, NULL, &fn1)); - napi_value fn2; - NAPI_CALL(env, napi_create_function( - env, "Name", NAPI_AUTO_LENGTH, TestFunctionName, NULL, &fn2)); + node_api_value fn2; + NODE_API_CALL(env, node_api_create_function( + env, "Name", NODE_API_AUTO_LENGTH, TestFunctionName, NULL, &fn2)); - napi_value fn3; - NAPI_CALL(env, napi_create_function( + node_api_value fn3; + NODE_API_CALL(env, node_api_create_function( env, "Name_extra", 5, TestFunctionName, NULL, &fn3)); - napi_value fn4; - NAPI_CALL(env, napi_create_function(env, - "MakeTrackedFunction", - NAPI_AUTO_LENGTH, - MakeTrackedFunction, - NULL, - &fn4)); - - napi_value fn5; - NAPI_CALL(env, napi_create_function(env, - "TestCreateFunctionParameters", - NAPI_AUTO_LENGTH, - TestCreateFunctionParameters, - NULL, - &fn5)); - - NAPI_CALL(env, napi_set_named_property(env, exports, "TestCall", fn1)); - NAPI_CALL(env, napi_set_named_property(env, exports, "TestName", fn2)); - NAPI_CALL(env, napi_set_named_property(env, exports, "TestNameShort", fn3)); - NAPI_CALL(env, napi_set_named_property(env, - exports, - "MakeTrackedFunction", - fn4)); - - NAPI_CALL(env, napi_set_named_property(env, - exports, - "TestCreateFunctionParameters", - fn5)); + node_api_value fn4; + NODE_API_CALL(env, node_api_create_function(env, + "MakeTrackedFunction", + NODE_API_AUTO_LENGTH, + MakeTrackedFunction, + NULL, + &fn4)); + + node_api_value fn5; + NODE_API_CALL(env, node_api_create_function(env, + "TestCreateFunctionParameters", + NODE_API_AUTO_LENGTH, + TestCreateFunctionParameters, + NULL, + &fn5)); + + NODE_API_CALL(env, + node_api_set_named_property(env, exports, "TestCall", fn1)); + NODE_API_CALL(env, + node_api_set_named_property(env, exports, "TestName", fn2)); + NODE_API_CALL(env, + node_api_set_named_property(env, exports, "TestNameShort", fn3)); + NODE_API_CALL(env, + node_api_set_named_property(env, exports, "MakeTrackedFunction", fn4)); + + NODE_API_CALL(env, node_api_set_named_property(env, + exports, + "TestCreateFunctionParameters", + fn5)); return exports; } diff --git a/test/js-native-api/test_general/test.js b/test/js-native-api/test_general/test.js index 4dbdc37c918c37..29beca4ef602a5 100644 --- a/test/js-native-api/test_general/test.js +++ b/test/js-native-api/test_general/test.js @@ -18,12 +18,12 @@ class ExtendedClass extends BaseClass { const baseObject = new BaseClass(); const extendedObject = new ExtendedClass(); -// Test napi_strict_equals +// Test node_api_strict_equals assert.ok(test_general.testStrictEquals(val1, val1)); assert.strictEqual(test_general.testStrictEquals(val1, val2), false); assert.ok(test_general.testStrictEquals(val2, val3)); -// Test napi_get_prototype +// Test node_api_get_prototype assert.strictEqual(test_general.testGetPrototype(baseObject), Object.getPrototypeOf(baseObject)); assert.strictEqual(test_general.testGetPrototype(extendedObject), @@ -68,7 +68,7 @@ test_general.wrap(y); // Clean up here, otherwise derefItemWasCalled() will be polluted. test_general.removeWrap(y); -// Test napi_adjust_external_memory +// Test node_api_adjust_external_memory const adjustedValue = test_general.testAdjustExternalMemory(); assert.strictEqual(typeof adjustedValue, 'number'); assert(adjustedValue > 0); diff --git a/test/js-native-api/test_general/testNapiStatus.js b/test/js-native-api/test_general/testNapiStatus.js index a588862098f68f..6e963d1a321068 100644 --- a/test/js-native-api/test_general/testNapiStatus.js +++ b/test/js-native-api/test_general/testNapiStatus.js @@ -5,4 +5,5 @@ const addon = require(`./build/${common.buildType}/test_general`); const assert = require('assert'); addon.createNapiError(); -assert(addon.testNapiErrorCleanup(), 'napi_status cleaned up for second call'); +assert(addon.testNapiErrorCleanup(), + 'node_api_status cleaned up for second call'); diff --git a/test/js-native-api/test_general/test_general.c b/test/js-native-api/test_general/test_general.c index f6e641167d5bcc..60ef9a156cd836 100644 --- a/test/js-native-api/test_general/test_general.c +++ b/test/js-native-api/test_general/test_general.c @@ -4,247 +4,274 @@ #include #include "../common.h" -static napi_value testStrictEquals(napi_env env, napi_callback_info info) { +static node_api_value +testStrictEquals(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); bool bool_result; - napi_value result; - NAPI_CALL(env, napi_strict_equals(env, args[0], args[1], &bool_result)); - NAPI_CALL(env, napi_get_boolean(env, bool_result, &result)); + node_api_value result; + NODE_API_CALL(env, + node_api_strict_equals(env, args[0], args[1], &bool_result)); + NODE_API_CALL(env, node_api_get_boolean(env, bool_result, &result)); return result; } -static napi_value testGetPrototype(napi_env env, napi_callback_info info) { +static node_api_value +testGetPrototype(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value result; - NAPI_CALL(env, napi_get_prototype(env, args[0], &result)); + node_api_value result; + NODE_API_CALL(env, node_api_get_prototype(env, args[0], &result)); return result; } -static napi_value testGetVersion(napi_env env, napi_callback_info info) { +static node_api_value +testGetVersion(node_api_env env, node_api_callback_info info) { uint32_t version; - napi_value result; - NAPI_CALL(env, napi_get_version(env, &version)); - NAPI_CALL(env, napi_create_uint32(env, version, &result)); + node_api_value result; + NODE_API_CALL(env, node_api_get_version(env, &version)); + NODE_API_CALL(env, node_api_create_uint32(env, version, &result)); return result; } -static napi_value doInstanceOf(napi_env env, napi_callback_info info) { +static node_api_value +doInstanceOf(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); bool instanceof; - NAPI_CALL(env, napi_instanceof(env, args[0], args[1], &instanceof)); + NODE_API_CALL(env, node_api_instanceof(env, args[0], args[1], &instanceof)); - napi_value result; - NAPI_CALL(env, napi_get_boolean(env, instanceof, &result)); + node_api_value result; + NODE_API_CALL(env, node_api_get_boolean(env, instanceof, &result)); return result; } -static napi_value getNull(napi_env env, napi_callback_info info) { - napi_value result; - NAPI_CALL(env, napi_get_null(env, &result)); +static node_api_value +getNull(node_api_env env, node_api_callback_info info) { + node_api_value result; + NODE_API_CALL(env, node_api_get_null(env, &result)); return result; } -static napi_value getUndefined(napi_env env, napi_callback_info info) { - napi_value result; - NAPI_CALL(env, napi_get_undefined(env, &result)); +static node_api_value +getUndefined(node_api_env env, node_api_callback_info info) { + node_api_value result; + NODE_API_CALL(env, node_api_get_undefined(env, &result)); return result; } -static napi_value createNapiError(napi_env env, napi_callback_info info) { - napi_value value; - NAPI_CALL(env, napi_create_string_utf8(env, "xyz", 3, &value)); +static node_api_value +createNapiError(node_api_env env, node_api_callback_info info) { + node_api_value value; + NODE_API_CALL(env, node_api_create_string_utf8(env, "xyz", 3, &value)); double double_value; - napi_status status = napi_get_value_double(env, value, &double_value); + node_api_status status = + node_api_get_value_double(env, value, &double_value); - NAPI_ASSERT(env, status != napi_ok, "Failed to produce error condition"); + NODE_API_ASSERT(env, status != node_api_ok, + "Failed to produce error condition"); - const napi_extended_error_info *error_info = 0; - NAPI_CALL(env, napi_get_last_error_info(env, &error_info)); + const node_api_extended_error_info *error_info = 0; + NODE_API_CALL(env, node_api_get_last_error_info(env, &error_info)); - NAPI_ASSERT(env, error_info->error_code == status, + NODE_API_ASSERT(env, error_info->error_code == status, "Last error info code should match last status"); - NAPI_ASSERT(env, error_info->error_message, + NODE_API_ASSERT(env, error_info->error_message, "Last error info message should not be null"); return NULL; } -static napi_value testNapiErrorCleanup(napi_env env, napi_callback_info info) { - const napi_extended_error_info *error_info = 0; - NAPI_CALL(env, napi_get_last_error_info(env, &error_info)); +static node_api_value +testNapiErrorCleanup(node_api_env env, node_api_callback_info info) { + const node_api_extended_error_info *error_info = 0; + NODE_API_CALL(env, node_api_get_last_error_info(env, &error_info)); - napi_value result; - bool is_ok = error_info->error_code == napi_ok; - NAPI_CALL(env, napi_get_boolean(env, is_ok, &result)); + node_api_value result; + bool is_ok = error_info->error_code == node_api_ok; + NODE_API_CALL(env, node_api_get_boolean(env, is_ok, &result)); return result; } -static napi_value testNapiTypeof(napi_env env, napi_callback_info info) { +static node_api_value +testNapiTypeof(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - - napi_valuetype argument_type; - NAPI_CALL(env, napi_typeof(env, args[0], &argument_type)); - - napi_value result = NULL; - if (argument_type == napi_number) { - NAPI_CALL(env, napi_create_string_utf8( - env, "number", NAPI_AUTO_LENGTH, &result)); - } else if (argument_type == napi_string) { - NAPI_CALL(env, napi_create_string_utf8( - env, "string", NAPI_AUTO_LENGTH, &result)); - } else if (argument_type == napi_function) { - NAPI_CALL(env, napi_create_string_utf8( - env, "function", NAPI_AUTO_LENGTH, &result)); - } else if (argument_type == napi_object) { - NAPI_CALL(env, napi_create_string_utf8( - env, "object", NAPI_AUTO_LENGTH, &result)); - } else if (argument_type == napi_boolean) { - NAPI_CALL(env, napi_create_string_utf8( - env, "boolean", NAPI_AUTO_LENGTH, &result)); - } else if (argument_type == napi_undefined) { - NAPI_CALL(env, napi_create_string_utf8( - env, "undefined", NAPI_AUTO_LENGTH, &result)); - } else if (argument_type == napi_symbol) { - NAPI_CALL(env, napi_create_string_utf8( - env, "symbol", NAPI_AUTO_LENGTH, &result)); - } else if (argument_type == napi_null) { - NAPI_CALL(env, napi_create_string_utf8( - env, "null", NAPI_AUTO_LENGTH, &result)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); + + node_api_valuetype argument_type; + NODE_API_CALL(env, node_api_typeof(env, args[0], &argument_type)); + + node_api_value result = NULL; + if (argument_type == node_api_number) { + NODE_API_CALL(env, node_api_create_string_utf8( + env, "number", NODE_API_AUTO_LENGTH, &result)); + } else if (argument_type == node_api_string) { + NODE_API_CALL(env, node_api_create_string_utf8( + env, "string", NODE_API_AUTO_LENGTH, &result)); + } else if (argument_type == node_api_function) { + NODE_API_CALL(env, node_api_create_string_utf8( + env, "function", NODE_API_AUTO_LENGTH, &result)); + } else if (argument_type == node_api_object) { + NODE_API_CALL(env, node_api_create_string_utf8( + env, "object", NODE_API_AUTO_LENGTH, &result)); + } else if (argument_type == node_api_boolean) { + NODE_API_CALL(env, node_api_create_string_utf8( + env, "boolean", NODE_API_AUTO_LENGTH, &result)); + } else if (argument_type == node_api_undefined) { + NODE_API_CALL(env, node_api_create_string_utf8( + env, "undefined", NODE_API_AUTO_LENGTH, &result)); + } else if (argument_type == node_api_symbol) { + NODE_API_CALL(env, node_api_create_string_utf8( + env, "symbol", NODE_API_AUTO_LENGTH, &result)); + } else if (argument_type == node_api_null) { + NODE_API_CALL(env, node_api_create_string_utf8( + env, "null", NODE_API_AUTO_LENGTH, &result)); } return result; } static bool deref_item_called = false; -static void deref_item(napi_env env, void* data, void* hint) { +static void deref_item(node_api_env env, void* data, void* hint) { (void) hint; - NAPI_ASSERT_RETURN_VOID(env, data == &deref_item_called, + NODE_API_ASSERT_RETURN_VOID(env, data == &deref_item_called, "Finalize callback was called with the correct pointer"); deref_item_called = true; } -static napi_value deref_item_was_called(napi_env env, napi_callback_info info) { - napi_value it_was_called; +static node_api_value +deref_item_was_called(node_api_env env, node_api_callback_info info) { + node_api_value it_was_called; - NAPI_CALL(env, napi_get_boolean(env, deref_item_called, &it_was_called)); + NODE_API_CALL(env, + node_api_get_boolean(env, deref_item_called, &it_was_called)); return it_was_called; } -static napi_value wrap_first_arg(napi_env env, - napi_callback_info info, - napi_finalize finalizer, - void* data) { +static node_api_value wrap_first_arg(node_api_env env, + node_api_callback_info info, + node_api_finalize finalizer, + void* data) { size_t argc = 1; - napi_value to_wrap; + node_api_value to_wrap; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &to_wrap, NULL, NULL)); - NAPI_CALL(env, napi_wrap(env, to_wrap, data, finalizer, NULL, NULL)); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &to_wrap, NULL, NULL)); + NODE_API_CALL(env, node_api_wrap(env, to_wrap, data, finalizer, NULL, NULL)); return to_wrap; } -static napi_value wrap(napi_env env, napi_callback_info info) { +static node_api_value wrap(node_api_env env, node_api_callback_info info) { deref_item_called = false; return wrap_first_arg(env, info, deref_item, &deref_item_called); } -static napi_value unwrap(napi_env env, napi_callback_info info) { +static node_api_value unwrap(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value wrapped; + node_api_value wrapped; void* data; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &wrapped, NULL, NULL)); - NAPI_CALL(env, napi_unwrap(env, wrapped, &data)); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &wrapped, NULL, NULL)); + NODE_API_CALL(env, node_api_unwrap(env, wrapped, &data)); return NULL; } -static napi_value remove_wrap(napi_env env, napi_callback_info info) { +static node_api_value +remove_wrap(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value wrapped; + node_api_value wrapped; void* data; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &wrapped, NULL, NULL)); - NAPI_CALL(env, napi_remove_wrap(env, wrapped, &data)); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &wrapped, NULL, NULL)); + NODE_API_CALL(env, node_api_remove_wrap(env, wrapped, &data)); return NULL; } static bool finalize_called = false; -static void test_finalize(napi_env env, void* data, void* hint) { +static void test_finalize(node_api_env env, void* data, void* hint) { finalize_called = true; } -static napi_value test_finalize_wrap(napi_env env, napi_callback_info info) { +static node_api_value +test_finalize_wrap(node_api_env env, node_api_callback_info info) { return wrap_first_arg(env, info, test_finalize, NULL); } -static napi_value finalize_was_called(napi_env env, napi_callback_info info) { - napi_value it_was_called; +static node_api_value +finalize_was_called(node_api_env env, node_api_callback_info info) { + node_api_value it_was_called; - NAPI_CALL(env, napi_get_boolean(env, finalize_called, &it_was_called)); + NODE_API_CALL(env, + node_api_get_boolean(env, finalize_called, &it_was_called)); return it_was_called; } -static napi_value testAdjustExternalMemory(napi_env env, napi_callback_info info) { - napi_value result; +static node_api_value +testAdjustExternalMemory(node_api_env env, node_api_callback_info info) { + node_api_value result; int64_t adjustedValue; - NAPI_CALL(env, napi_adjust_external_memory(env, 1, &adjustedValue)); - NAPI_CALL(env, napi_create_double(env, (double)adjustedValue, &result)); + NODE_API_CALL(env, node_api_adjust_external_memory(env, 1, &adjustedValue)); + NODE_API_CALL(env, + node_api_create_double(env, (double)adjustedValue, &result)); return result; } -static napi_value testNapiRun(napi_env env, napi_callback_info info) { - napi_value script, result; +static node_api_value +testNapiRun(node_api_env env, node_api_callback_info info) { + node_api_value script, result; size_t argc = 1; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &script, NULL, NULL)); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &script, NULL, NULL)); - NAPI_CALL(env, napi_run_script(env, script, &result)); + NODE_API_CALL(env, node_api_run_script(env, script, &result)); return result; } -static void finalizer_only_callback(napi_env env, void* data, void* hint) { - napi_ref js_cb_ref = data; - napi_value js_cb, undefined; - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, js_cb_ref, &js_cb)); - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, - napi_call_function(env, undefined, js_cb, 0, NULL, NULL)); - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, js_cb_ref)); +static void finalizer_only_callback(node_api_env env, void* data, void* hint) { + node_api_ref js_cb_ref = data; + node_api_value js_cb, undefined; + NODE_API_CALL_RETURN_VOID(env, + node_api_get_reference_value(env, js_cb_ref, &js_cb)); + NODE_API_CALL_RETURN_VOID(env, node_api_get_undefined(env, &undefined)); + NODE_API_CALL_RETURN_VOID(env, + node_api_call_function(env, undefined, js_cb, 0, NULL, NULL)); + NODE_API_CALL_RETURN_VOID(env, node_api_delete_reference(env, js_cb_ref)); } -static napi_value add_finalizer_only(napi_env env, napi_callback_info info) { +static node_api_value +add_finalizer_only(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value argv[2]; - napi_ref js_cb_ref; + node_api_value argv[2]; + node_api_ref js_cb_ref; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_CALL(env, napi_create_reference(env, argv[1], 1, &js_cb_ref)); - NAPI_CALL(env, - napi_add_finalizer(env, + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NODE_API_CALL(env, node_api_create_reference(env, argv[1], 1, &js_cb_ref)); + NODE_API_CALL(env, + node_api_add_finalizer(env, argv[0], js_cb_ref, finalizer_only_callback, @@ -260,7 +287,7 @@ static const char* env_cleanup_finalizer_messages[] = { "second wrap" }; -static void cleanup_env_finalizer(napi_env env, void* data, void* hint) { +static void cleanup_env_finalizer(node_api_env env, void* data, void* hint) { (void) env; (void) hint; @@ -268,44 +295,46 @@ static void cleanup_env_finalizer(napi_env env, void* data, void* hint) { env_cleanup_finalizer_messages[(uintptr_t)data]); } -static napi_value env_cleanup_wrap(napi_env env, napi_callback_info info) { +static node_api_value +env_cleanup_wrap(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value argv[2]; + node_api_value argv[2]; uint32_t value; uintptr_t ptr_value; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_CALL(env, napi_get_value_uint32(env, argv[1], &value)); + NODE_API_CALL(env, node_api_get_value_uint32(env, argv[1], &value)); ptr_value = value; return wrap_first_arg(env, info, cleanup_env_finalizer, (void*)ptr_value); } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("testStrictEquals", testStrictEquals), - DECLARE_NAPI_PROPERTY("testGetPrototype", testGetPrototype), - DECLARE_NAPI_PROPERTY("testGetVersion", testGetVersion), - DECLARE_NAPI_PROPERTY("testNapiRun", testNapiRun), - DECLARE_NAPI_PROPERTY("doInstanceOf", doInstanceOf), - DECLARE_NAPI_PROPERTY("getUndefined", getUndefined), - DECLARE_NAPI_PROPERTY("getNull", getNull), - DECLARE_NAPI_PROPERTY("createNapiError", createNapiError), - DECLARE_NAPI_PROPERTY("testNapiErrorCleanup", testNapiErrorCleanup), - DECLARE_NAPI_PROPERTY("testNapiTypeof", testNapiTypeof), - DECLARE_NAPI_PROPERTY("wrap", wrap), - DECLARE_NAPI_PROPERTY("envCleanupWrap", env_cleanup_wrap), - DECLARE_NAPI_PROPERTY("unwrap", unwrap), - DECLARE_NAPI_PROPERTY("removeWrap", remove_wrap), - DECLARE_NAPI_PROPERTY("addFinalizerOnly", add_finalizer_only), - DECLARE_NAPI_PROPERTY("testFinalizeWrap", test_finalize_wrap), - DECLARE_NAPI_PROPERTY("finalizeWasCalled", finalize_was_called), - DECLARE_NAPI_PROPERTY("derefItemWasCalled", deref_item_was_called), - DECLARE_NAPI_PROPERTY("testAdjustExternalMemory", testAdjustExternalMemory) +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("testStrictEquals", testStrictEquals), + DECLARE_NODE_API_PROPERTY("testGetPrototype", testGetPrototype), + DECLARE_NODE_API_PROPERTY("testGetVersion", testGetVersion), + DECLARE_NODE_API_PROPERTY("testNapiRun", testNapiRun), + DECLARE_NODE_API_PROPERTY("doInstanceOf", doInstanceOf), + DECLARE_NODE_API_PROPERTY("getUndefined", getUndefined), + DECLARE_NODE_API_PROPERTY("getNull", getNull), + DECLARE_NODE_API_PROPERTY("createNapiError", createNapiError), + DECLARE_NODE_API_PROPERTY("testNapiErrorCleanup", testNapiErrorCleanup), + DECLARE_NODE_API_PROPERTY("testNapiTypeof", testNapiTypeof), + DECLARE_NODE_API_PROPERTY("wrap", wrap), + DECLARE_NODE_API_PROPERTY("envCleanupWrap", env_cleanup_wrap), + DECLARE_NODE_API_PROPERTY("unwrap", unwrap), + DECLARE_NODE_API_PROPERTY("removeWrap", remove_wrap), + DECLARE_NODE_API_PROPERTY("addFinalizerOnly", add_finalizer_only), + DECLARE_NODE_API_PROPERTY("testFinalizeWrap", test_finalize_wrap), + DECLARE_NODE_API_PROPERTY("finalizeWasCalled", finalize_was_called), + DECLARE_NODE_API_PROPERTY("derefItemWasCalled", deref_item_was_called), + DECLARE_NODE_API_PROPERTY( + "testAdjustExternalMemory", testAdjustExternalMemory) }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/js-native-api/test_handle_scope/test_handle_scope.c b/test/js-native-api/test_handle_scope/test_handle_scope.c index e6029398aa66dc..4de48243fcf303 100644 --- a/test/js-native-api/test_handle_scope/test_handle_scope.c +++ b/test/js-native-api/test_handle_scope/test_handle_scope.c @@ -7,77 +7,81 @@ // the right right thing would be quite hard so we keep it // simple for now. -static napi_value NewScope(napi_env env, napi_callback_info info) { - napi_handle_scope scope; - napi_value output = NULL; +static node_api_value NewScope(node_api_env env, node_api_callback_info info) { + node_api_handle_scope scope; + node_api_value output = NULL; - NAPI_CALL(env, napi_open_handle_scope(env, &scope)); - NAPI_CALL(env, napi_create_object(env, &output)); - NAPI_CALL(env, napi_close_handle_scope(env, scope)); + NODE_API_CALL(env, node_api_open_handle_scope(env, &scope)); + NODE_API_CALL(env, node_api_create_object(env, &output)); + NODE_API_CALL(env, node_api_close_handle_scope(env, scope)); return NULL; } -static napi_value NewScopeEscape(napi_env env, napi_callback_info info) { - napi_escapable_handle_scope scope; - napi_value output = NULL; - napi_value escapee = NULL; +static node_api_value +NewScopeEscape(node_api_env env, node_api_callback_info info) { + node_api_escapable_handle_scope scope; + node_api_value output = NULL; + node_api_value escapee = NULL; - NAPI_CALL(env, napi_open_escapable_handle_scope(env, &scope)); - NAPI_CALL(env, napi_create_object(env, &output)); - NAPI_CALL(env, napi_escape_handle(env, scope, output, &escapee)); - NAPI_CALL(env, napi_close_escapable_handle_scope(env, scope)); + NODE_API_CALL(env, node_api_open_escapable_handle_scope(env, &scope)); + NODE_API_CALL(env, node_api_create_object(env, &output)); + NODE_API_CALL(env, node_api_escape_handle(env, scope, output, &escapee)); + NODE_API_CALL(env, node_api_close_escapable_handle_scope(env, scope)); return escapee; } -static napi_value NewScopeEscapeTwice(napi_env env, napi_callback_info info) { - napi_escapable_handle_scope scope; - napi_value output = NULL; - napi_value escapee = NULL; - napi_status status; +static node_api_value +NewScopeEscapeTwice(node_api_env env, node_api_callback_info info) { + node_api_escapable_handle_scope scope; + node_api_value output = NULL; + node_api_value escapee = NULL; + node_api_status status; - NAPI_CALL(env, napi_open_escapable_handle_scope(env, &scope)); - NAPI_CALL(env, napi_create_object(env, &output)); - NAPI_CALL(env, napi_escape_handle(env, scope, output, &escapee)); - status = napi_escape_handle(env, scope, output, &escapee); - NAPI_ASSERT(env, status == napi_escape_called_twice, "Escaping twice fails"); - NAPI_CALL(env, napi_close_escapable_handle_scope(env, scope)); + NODE_API_CALL(env, node_api_open_escapable_handle_scope(env, &scope)); + NODE_API_CALL(env, node_api_create_object(env, &output)); + NODE_API_CALL(env, node_api_escape_handle(env, scope, output, &escapee)); + status = node_api_escape_handle(env, scope, output, &escapee); + NODE_API_ASSERT(env, status == node_api_escape_called_twice, + "Escaping twice fails"); + NODE_API_CALL(env, node_api_close_escapable_handle_scope(env, scope)); return NULL; } -static napi_value NewScopeWithException(napi_env env, napi_callback_info info) { - napi_handle_scope scope; +static node_api_value +NewScopeWithException(node_api_env env, node_api_callback_info info) { + node_api_handle_scope scope; size_t argc; - napi_value exception_function; - napi_status status; - napi_value output = NULL; + node_api_value exception_function; + node_api_status status; + node_api_value output = NULL; - NAPI_CALL(env, napi_open_handle_scope(env, &scope)); - NAPI_CALL(env, napi_create_object(env, &output)); + NODE_API_CALL(env, node_api_open_handle_scope(env, &scope)); + NODE_API_CALL(env, node_api_create_object(env, &output)); argc = 1; - NAPI_CALL(env, napi_get_cb_info( + NODE_API_CALL(env, node_api_get_cb_info( env, info, &argc, &exception_function, NULL, NULL)); - status = napi_call_function( + status = node_api_call_function( env, output, exception_function, 0, NULL, NULL); - NAPI_ASSERT(env, status == napi_pending_exception, + NODE_API_ASSERT(env, status == node_api_pending_exception, "Function should have thrown."); // Closing a handle scope should still work while an exception is pending. - NAPI_CALL(env, napi_close_handle_scope(env, scope)); + NODE_API_CALL(env, node_api_close_handle_scope(env, scope)); return NULL; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("NewScope", NewScope), - DECLARE_NAPI_PROPERTY("NewScopeEscape", NewScopeEscape), - DECLARE_NAPI_PROPERTY("NewScopeEscapeTwice", NewScopeEscapeTwice), - DECLARE_NAPI_PROPERTY("NewScopeWithException", NewScopeWithException), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor properties[] = { + DECLARE_NODE_API_PROPERTY("NewScope", NewScope), + DECLARE_NODE_API_PROPERTY("NewScopeEscape", NewScopeEscape), + DECLARE_NODE_API_PROPERTY("NewScopeEscapeTwice", NewScopeEscapeTwice), + DECLARE_NODE_API_PROPERTY("NewScopeWithException", NewScopeWithException), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; diff --git a/test/js-native-api/test_instance_data/test_instance_data.c b/test/js-native-api/test_instance_data/test_instance_data.c index 5255c3e4a02b94..d34a2ab846bf8e 100644 --- a/test/js-native-api/test_instance_data/test_instance_data.c +++ b/test/js-native-api/test_instance_data/test_instance_data.c @@ -6,90 +6,99 @@ typedef struct { size_t value; bool print; - napi_ref js_cb_ref; + node_api_ref js_cb_ref; } AddonData; -static napi_value Increment(napi_env env, napi_callback_info info) { +static node_api_value +Increment(node_api_env env, node_api_callback_info info) { AddonData* data; - napi_value result; + node_api_value result; - NAPI_CALL(env, napi_get_instance_data(env, (void**)&data)); - NAPI_CALL(env, napi_create_uint32(env, ++data->value, &result)); + NODE_API_CALL(env, node_api_get_instance_data(env, (void**)&data)); + NODE_API_CALL(env, node_api_create_uint32(env, ++data->value, &result)); return result; } -static void DeleteAddonData(napi_env env, void* raw_data, void* hint) { +static void DeleteAddonData(node_api_env env, void* raw_data, void* hint) { AddonData* data = raw_data; if (data->print) { printf("deleting addon data\n"); } if (data->js_cb_ref != NULL) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, data->js_cb_ref)); + NODE_API_CALL_RETURN_VOID(env, + node_api_delete_reference(env, data->js_cb_ref)); } free(data); } -static napi_value SetPrintOnDelete(napi_env env, napi_callback_info info) { +static node_api_value +SetPrintOnDelete(node_api_env env, node_api_callback_info info) { AddonData* data; - NAPI_CALL(env, napi_get_instance_data(env, (void**)&data)); + NODE_API_CALL(env, node_api_get_instance_data(env, (void**)&data)); data->print = true; return NULL; } -static void TestFinalizer(napi_env env, void* raw_data, void* hint) { +static void TestFinalizer(node_api_env env, void* raw_data, void* hint) { (void) raw_data; (void) hint; AddonData* data; - NAPI_CALL_RETURN_VOID(env, napi_get_instance_data(env, (void**)&data)); - napi_value js_cb, undefined; - NAPI_CALL_RETURN_VOID(env, - napi_get_reference_value(env, data->js_cb_ref, &js_cb)); - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, - napi_call_function(env, undefined, js_cb, 0, NULL, NULL)); - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, data->js_cb_ref)); + NODE_API_CALL_RETURN_VOID(env, + node_api_get_instance_data(env, (void**)&data)); + node_api_value js_cb, undefined; + NODE_API_CALL_RETURN_VOID(env, + node_api_get_reference_value(env, data->js_cb_ref, &js_cb)); + NODE_API_CALL_RETURN_VOID(env, node_api_get_undefined(env, &undefined)); + NODE_API_CALL_RETURN_VOID(env, + node_api_call_function(env, undefined, js_cb, 0, NULL, NULL)); + NODE_API_CALL_RETURN_VOID(env, + node_api_delete_reference(env, data->js_cb_ref)); data->js_cb_ref = NULL; } -static napi_value ObjectWithFinalizer(napi_env env, napi_callback_info info) { +static node_api_value +ObjectWithFinalizer(node_api_env env, node_api_callback_info info) { AddonData* data; - napi_value result, js_cb; + node_api_value result, js_cb; size_t argc = 1; - NAPI_CALL(env, napi_get_instance_data(env, (void**)&data)); - NAPI_ASSERT(env, data->js_cb_ref == NULL, "reference must be NULL"); - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &js_cb, NULL, NULL)); - NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL(env, - napi_add_finalizer(env, result, NULL, TestFinalizer, NULL, NULL)); - NAPI_CALL(env, napi_create_reference(env, js_cb, 1, &data->js_cb_ref)); + NODE_API_CALL(env, node_api_get_instance_data(env, (void**)&data)); + NODE_API_ASSERT(env, data->js_cb_ref == NULL, "reference must be NULL"); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &js_cb, NULL, NULL)); + NODE_API_CALL(env, node_api_create_object(env, &result)); + NODE_API_CALL(env, + node_api_add_finalizer(env, result, NULL, TestFinalizer, NULL, NULL)); + NODE_API_CALL(env, + node_api_create_reference(env, js_cb, 1, &data->js_cb_ref)); return result; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { +node_api_value Init(node_api_env env, node_api_value exports) { AddonData* data = malloc(sizeof(*data)); data->value = 41; data->print = false; data->js_cb_ref = NULL; - NAPI_CALL(env, napi_set_instance_data(env, data, DeleteAddonData, NULL)); + NODE_API_CALL(env, + node_api_set_instance_data(env, data, DeleteAddonData, NULL)); - napi_property_descriptor props[] = { - DECLARE_NAPI_PROPERTY("increment", Increment), - DECLARE_NAPI_PROPERTY("setPrintOnDelete", SetPrintOnDelete), - DECLARE_NAPI_PROPERTY("objectWithFinalizer", ObjectWithFinalizer), + node_api_property_descriptor props[] = { + DECLARE_NODE_API_PROPERTY("increment", Increment), + DECLARE_NODE_API_PROPERTY("setPrintOnDelete", SetPrintOnDelete), + DECLARE_NODE_API_PROPERTY("objectWithFinalizer", ObjectWithFinalizer), }; - NAPI_CALL(env, napi_define_properties(env, - exports, - sizeof(props) / sizeof(*props), - props)); + NODE_API_CALL(env, node_api_define_properties(env, + exports, + sizeof(props) / sizeof(*props), + props)); return exports; } diff --git a/test/js-native-api/test_new_target/binding.c b/test/js-native-api/test_new_target/binding.c index bfb4138f719faf..272aeb6ef7a7fa 100644 --- a/test/js-native-api/test_new_target/binding.c +++ b/test/js-native-api/test_new_target/binding.c @@ -1,69 +1,77 @@ #include #include "../common.h" -static napi_value BaseClass(napi_env env, napi_callback_info info) { - napi_value newTargetArg; - NAPI_CALL(env, napi_get_new_target(env, info, &newTargetArg)); - napi_value thisArg; - NAPI_CALL(env, napi_get_cb_info(env, info, NULL, NULL, &thisArg, NULL)); - napi_value undefined; - NAPI_CALL(env, napi_get_undefined(env, &undefined)); +static node_api_value +BaseClass(node_api_env env, node_api_callback_info info) { + node_api_value newTargetArg; + NODE_API_CALL(env, node_api_get_new_target(env, info, &newTargetArg)); + node_api_value thisArg; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, NULL, NULL, &thisArg, NULL)); + node_api_value undefined; + NODE_API_CALL(env, node_api_get_undefined(env, &undefined)); // this !== new.target since we are being invoked through super() bool result; - NAPI_CALL(env, napi_strict_equals(env, newTargetArg, thisArg, &result)); - NAPI_ASSERT(env, !result, "this !== new.target"); + NODE_API_CALL(env, + node_api_strict_equals(env, newTargetArg, thisArg, &result)); + NODE_API_ASSERT(env, !result, "this !== new.target"); // new.target !== undefined because we should be called as a new expression - NAPI_ASSERT(env, newTargetArg != NULL, "newTargetArg != NULL"); - NAPI_CALL(env, napi_strict_equals(env, newTargetArg, undefined, &result)); - NAPI_ASSERT(env, !result, "new.target !== undefined"); + NODE_API_ASSERT(env, newTargetArg != NULL, "newTargetArg != NULL"); + NODE_API_CALL(env, + node_api_strict_equals(env, newTargetArg, undefined, &result)); + NODE_API_ASSERT(env, !result, "new.target !== undefined"); return thisArg; } -static napi_value Constructor(napi_env env, napi_callback_info info) { +static node_api_value +Constructor(node_api_env env, node_api_callback_info info) { bool result; - napi_value newTargetArg; - NAPI_CALL(env, napi_get_new_target(env, info, &newTargetArg)); + node_api_value newTargetArg; + NODE_API_CALL(env, node_api_get_new_target(env, info, &newTargetArg)); size_t argc = 1; - napi_value argv; - napi_value thisArg; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &argv, &thisArg, NULL)); - napi_value undefined; - NAPI_CALL(env, napi_get_undefined(env, &undefined)); + node_api_value argv; + node_api_value thisArg; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &argv, &thisArg, NULL)); + node_api_value undefined; + NODE_API_CALL(env, node_api_get_undefined(env, &undefined)); // new.target !== undefined because we should be called as a new expression - NAPI_ASSERT(env, newTargetArg != NULL, "newTargetArg != NULL"); - NAPI_CALL(env, napi_strict_equals(env, newTargetArg, undefined, &result)); - NAPI_ASSERT(env, !result, "new.target !== undefined"); + NODE_API_ASSERT(env, newTargetArg != NULL, "newTargetArg != NULL"); + NODE_API_CALL(env, + node_api_strict_equals(env, newTargetArg, undefined, &result)); + NODE_API_ASSERT(env, !result, "new.target !== undefined"); // arguments[0] should be Constructor itself (test harness passed it) - NAPI_CALL(env, napi_strict_equals(env, newTargetArg, argv, &result)); - NAPI_ASSERT(env, result, "new.target === Constructor"); + NODE_API_CALL(env, node_api_strict_equals(env, newTargetArg, argv, &result)); + NODE_API_ASSERT(env, result, "new.target === Constructor"); return thisArg; } -static napi_value OrdinaryFunction(napi_env env, napi_callback_info info) { - napi_value newTargetArg; - NAPI_CALL(env, napi_get_new_target(env, info, &newTargetArg)); +static node_api_value +OrdinaryFunction(node_api_env env, node_api_callback_info info) { + node_api_value newTargetArg; + NODE_API_CALL(env, node_api_get_new_target(env, info, &newTargetArg)); - NAPI_ASSERT(env, newTargetArg == NULL, "newTargetArg == NULL"); + NODE_API_ASSERT(env, newTargetArg == NULL, "newTargetArg == NULL"); - napi_value _true; - NAPI_CALL(env, napi_get_boolean(env, true, &_true)); + node_api_value _true; + NODE_API_CALL(env, node_api_get_boolean(env, true, &_true)); return _true; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - const napi_property_descriptor desc[] = { - DECLARE_NAPI_PROPERTY("BaseClass", BaseClass), - DECLARE_NAPI_PROPERTY("OrdinaryFunction", OrdinaryFunction), - DECLARE_NAPI_PROPERTY("Constructor", Constructor) +node_api_value Init(node_api_env env, node_api_value exports) { + const node_api_property_descriptor desc[] = { + DECLARE_NODE_API_PROPERTY("BaseClass", BaseClass), + DECLARE_NODE_API_PROPERTY("OrdinaryFunction", OrdinaryFunction), + DECLARE_NODE_API_PROPERTY("Constructor", Constructor) }; - NAPI_CALL(env, napi_define_properties(env, exports, 3, desc)); + NODE_API_CALL(env, node_api_define_properties(env, exports, 3, desc)); return exports; } EXTERN_C_END diff --git a/test/js-native-api/test_number/test.js b/test/js-native-api/test_number/test.js index 8ab8ad5e8be7f3..512a7cb4fcef17 100644 --- a/test/js-native-api/test_number/test.js +++ b/test/js-native-api/test_number/test.js @@ -51,7 +51,7 @@ testUint32(17 * 4294967296 + 1, 1); testUint32(-1, 0xffffffff); // Validate documented behavior when value is retrieved as 32-bit integer with -// `napi_get_value_int32` +// `node_api_get_value_int32` function testInt32(input, expected = input) { assert.strictEqual(expected, test_number.TestInt32Truncation(input)); } @@ -94,7 +94,7 @@ testInt32(Number.NEGATIVE_INFINITY, 0); testInt32(Number.NaN, 0); // Validate documented behavior when value is retrieved as 64-bit integer with -// `napi_get_value_int64` +// `node_api_get_value_int64` function testInt64(input, expected = input) { assert.strictEqual(expected, test_number.TestInt64Truncation(input)); } diff --git a/test/js-native-api/test_number/test_number.c b/test/js-native-api/test_number/test_number.c index d49bac29eff3f5..6e1f90bdcb7ce2 100644 --- a/test/js-native-api/test_number/test_number.c +++ b/test/js-native-api/test_number/test_number.c @@ -1,104 +1,107 @@ #include #include "../common.h" -static napi_value Test(napi_env env, napi_callback_info info) { +static node_api_value Test(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_number, + NODE_API_ASSERT(env, valuetype0 == node_api_number, "Wrong type of arguments. Expects a number as first argument."); double input; - NAPI_CALL(env, napi_get_value_double(env, args[0], &input)); + NODE_API_CALL(env, node_api_get_value_double(env, args[0], &input)); - napi_value output; - NAPI_CALL(env, napi_create_double(env, input, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_double(env, input, &output)); return output; } -static napi_value TestUint32Truncation(napi_env env, napi_callback_info info) { +static node_api_value +TestUint32Truncation(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_number, + NODE_API_ASSERT(env, valuetype0 == node_api_number, "Wrong type of arguments. Expects a number as first argument."); uint32_t input; - NAPI_CALL(env, napi_get_value_uint32(env, args[0], &input)); + NODE_API_CALL(env, node_api_get_value_uint32(env, args[0], &input)); - napi_value output; - NAPI_CALL(env, napi_create_uint32(env, input, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_uint32(env, input, &output)); return output; } -static napi_value TestInt32Truncation(napi_env env, napi_callback_info info) { +static node_api_value +TestInt32Truncation(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_number, + NODE_API_ASSERT(env, valuetype0 == node_api_number, "Wrong type of arguments. Expects a number as first argument."); int32_t input; - NAPI_CALL(env, napi_get_value_int32(env, args[0], &input)); + NODE_API_CALL(env, node_api_get_value_int32(env, args[0], &input)); - napi_value output; - NAPI_CALL(env, napi_create_int32(env, input, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_int32(env, input, &output)); return output; } -static napi_value TestInt64Truncation(napi_env env, napi_callback_info info) { +static node_api_value +TestInt64Truncation(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_number, + NODE_API_ASSERT(env, valuetype0 == node_api_number, "Wrong type of arguments. Expects a number as first argument."); int64_t input; - NAPI_CALL(env, napi_get_value_int64(env, args[0], &input)); + NODE_API_CALL(env, node_api_get_value_int64(env, args[0], &input)); - napi_value output; - NAPI_CALL(env, napi_create_int64(env, input, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_int64(env, input, &output)); return output; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("Test", Test), - DECLARE_NAPI_PROPERTY("TestInt32Truncation", TestInt32Truncation), - DECLARE_NAPI_PROPERTY("TestUint32Truncation", TestUint32Truncation), - DECLARE_NAPI_PROPERTY("TestInt64Truncation", TestInt64Truncation), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("Test", Test), + DECLARE_NODE_API_PROPERTY("TestInt32Truncation", TestInt32Truncation), + DECLARE_NODE_API_PROPERTY("TestUint32Truncation", TestUint32Truncation), + DECLARE_NODE_API_PROPERTY("TestInt64Truncation", TestInt64Truncation), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/js-native-api/test_object/test.js b/test/js-native-api/test_object/test.js index e5923ecd16c2cf..d486389c4d7e59 100644 --- a/test/js-native-api/test_object/test.js +++ b/test/js-native-api/test_object/test.js @@ -34,7 +34,7 @@ assert.strictEqual(newObject.test_number, 987654321); assert.strictEqual(newObject.test_string, 'test string'); { - // Verify that napi_get_property() walks the prototype chain. + // Verify that node_api_get_property() walks the prototype chain. function MyObject() { this.foo = 42; this.bar = 43; @@ -53,7 +53,7 @@ assert.strictEqual(newObject.test_string, 'test string'); } { - // Verify that napi_has_own_property() fails if property is not a name. + // Verify that node_api_has_own_property() fails if property is not a name. [true, false, null, undefined, {}, [], 0, 1, () => {}].forEach((value) => { assert.throws(() => { test_object.HasOwn({}, value); @@ -62,7 +62,7 @@ assert.strictEqual(newObject.test_string, 'test string'); } { - // Verify that napi_has_own_property() does not walk the prototype chain. + // Verify that node_api_has_own_property() does not walk the prototype chain. const symbol1 = Symbol(); const symbol2 = Symbol(); @@ -222,9 +222,9 @@ assert.strictEqual(newObject.test_string, 'test string'); } { - // Verify that napi_get_property_names gets the right set of property names, - // i.e.: includes prototypes, only enumerable properties, skips symbols, - // and includes indices and converts them to strings. + // Verify that node_api_get_property_names gets the right set of property + // names, i.e.: includes prototypes, only enumerable properties, skips + // symbols, and includes indices and converts them to strings. const object = Object.create({ inherited: 1 @@ -249,7 +249,7 @@ assert.strictEqual(newObject.test_string, 'test string'); [fooSymbol]); } -// Verify that passing NULL to napi_set_property() results in the correct +// Verify that passing NULL to node_api_set_property() results in the correct // error. assert.deepStrictEqual(test_object.TestSetProperty(), { envIsNull: 'Invalid argument', @@ -258,7 +258,7 @@ assert.deepStrictEqual(test_object.TestSetProperty(), { valueIsNull: 'Invalid argument' }); -// Verify that passing NULL to napi_has_property() results in the correct +// Verify that passing NULL to node_api_has_property() results in the correct // error. assert.deepStrictEqual(test_object.TestHasProperty(), { envIsNull: 'Invalid argument', @@ -267,7 +267,7 @@ assert.deepStrictEqual(test_object.TestHasProperty(), { resultIsNull: 'Invalid argument' }); -// Verify that passing NULL to napi_get_property() results in the correct +// Verify that passing NULL to node_api_get_property() results in the correct // error. assert.deepStrictEqual(test_object.TestGetProperty(), { envIsNull: 'Invalid argument', diff --git a/test/js-native-api/test_object/test_null.c b/test/js-native-api/test_object/test_null.c index b6bf4df31cc918..d8c12cfe3964a9 100644 --- a/test/js-native-api/test_object/test_null.c +++ b/test/js-native-api/test_object/test_null.c @@ -3,75 +3,84 @@ #include "../common.h" #include "test_null.h" -static napi_value SetProperty(napi_env env, napi_callback_info info) { - napi_value return_value, object, key; +static node_api_value +SetProperty(node_api_env env, node_api_callback_info info) { + node_api_value return_value, object, key; - NAPI_CALL(env, napi_create_object(env, &return_value)); - NAPI_CALL(env, napi_create_object(env, &object)); - NAPI_CALL(env, - napi_create_string_utf8(env, "someString", NAPI_AUTO_LENGTH, &key)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &object)); + NODE_API_CALL(env, + node_api_create_string_utf8( + env, "someString", NODE_API_AUTO_LENGTH, &key)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, - napi_set_property(NULL, object, key, object)); + node_api_invalid_arg, + node_api_set_property(NULL, object, key, object)); - napi_set_property(env, NULL, key, object); + node_api_set_property(env, NULL, key, object); add_last_status(env, "objectIsNull", return_value); - napi_set_property(env, object, NULL, object); + node_api_set_property(env, object, NULL, object); add_last_status(env, "keyIsNull", return_value); - napi_set_property(env, object, key, NULL); + node_api_set_property(env, object, key, NULL); add_last_status(env, "valueIsNull", return_value); return return_value; } -static napi_value GetProperty(napi_env env, napi_callback_info info) { - napi_value return_value, object, key, prop; +static node_api_value +GetProperty(node_api_env env, node_api_callback_info info) { + node_api_value return_value, object, key, prop; - NAPI_CALL(env, napi_create_object(env, &return_value)); - NAPI_CALL(env, napi_create_object(env, &object)); - NAPI_CALL(env, - napi_create_string_utf8(env, "someString", NAPI_AUTO_LENGTH, &key)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &object)); + NODE_API_CALL(env, + node_api_create_string_utf8( + env, "someString", NODE_API_AUTO_LENGTH, &key)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, - napi_get_property(NULL, object, key, &prop)); + node_api_invalid_arg, + node_api_get_property(NULL, object, key, &prop)); - napi_get_property(env, NULL, key, &prop); + node_api_get_property(env, NULL, key, &prop); add_last_status(env, "objectIsNull", return_value); - napi_get_property(env, object, NULL, &prop); + node_api_get_property(env, object, NULL, &prop); add_last_status(env, "keyIsNull", return_value); - napi_get_property(env, object, key, NULL); + node_api_get_property(env, object, key, NULL); add_last_status(env, "valueIsNull", return_value); return return_value; } -static napi_value TestBoolValuedPropApi(napi_env env, - napi_status (*api)(napi_env, napi_value, napi_value, bool*)) { - napi_value return_value, object, key; +static node_api_value +TestBoolValuedPropApi(node_api_env env, + node_api_status (*api)(node_api_env, + node_api_value, + node_api_value, + bool*)) { + node_api_value return_value, object, key; bool result; - NAPI_CALL(env, napi_create_object(env, &return_value)); - NAPI_CALL(env, napi_create_object(env, &object)); - NAPI_CALL(env, - napi_create_string_utf8(env, "someString", NAPI_AUTO_LENGTH, &key)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &object)); + NODE_API_CALL(env, + node_api_create_string_utf8( + env, "someString", NODE_API_AUTO_LENGTH, &key)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, + node_api_invalid_arg, api(NULL, object, key, &result)); api(env, NULL, key, &result); @@ -86,151 +95,165 @@ static napi_value TestBoolValuedPropApi(napi_env env, return return_value; } -static napi_value HasProperty(napi_env env, napi_callback_info info) { - return TestBoolValuedPropApi(env, napi_has_property); +static node_api_value +HasProperty(node_api_env env, node_api_callback_info info) { + return TestBoolValuedPropApi(env, node_api_has_property); } -static napi_value HasOwnProperty(napi_env env, napi_callback_info info) { - return TestBoolValuedPropApi(env, napi_has_own_property); +static node_api_value +HasOwnProperty(node_api_env env, node_api_callback_info info) { + return TestBoolValuedPropApi(env, node_api_has_own_property); } -static napi_value DeleteProperty(napi_env env, napi_callback_info info) { - return TestBoolValuedPropApi(env, napi_delete_property); +static node_api_value +DeleteProperty(node_api_env env, node_api_callback_info info) { + return TestBoolValuedPropApi(env, node_api_delete_property); } -static napi_value SetNamedProperty(napi_env env, napi_callback_info info) { - napi_value return_value, object; +static node_api_value +SetNamedProperty(node_api_env env, node_api_callback_info info) { + node_api_value return_value, object; - NAPI_CALL(env, napi_create_object(env, &return_value)); - NAPI_CALL(env, napi_create_object(env, &object)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &object)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, - napi_set_named_property(NULL, object, "key", object)); + node_api_invalid_arg, + node_api_set_named_property( + NULL, object, "key", object)); - napi_set_named_property(env, NULL, "key", object); + node_api_set_named_property(env, NULL, "key", object); add_last_status(env, "objectIsNull", return_value); - napi_set_named_property(env, object, NULL, object); + node_api_set_named_property(env, object, NULL, object); add_last_status(env, "keyIsNull", return_value); - napi_set_named_property(env, object, "key", NULL); + node_api_set_named_property(env, object, "key", NULL); add_last_status(env, "valueIsNull", return_value); return return_value; } -static napi_value GetNamedProperty(napi_env env, napi_callback_info info) { - napi_value return_value, object, prop; +static node_api_value +GetNamedProperty(node_api_env env, node_api_callback_info info) { + node_api_value return_value, object, prop; - NAPI_CALL(env, napi_create_object(env, &return_value)); - NAPI_CALL(env, napi_create_object(env, &object)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &object)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, - napi_get_named_property(NULL, object, "key", &prop)); + node_api_invalid_arg, + node_api_get_named_property(NULL, object, "key", &prop)); - napi_get_named_property(env, NULL, "key", &prop); + node_api_get_named_property(env, NULL, "key", &prop); add_last_status(env, "objectIsNull", return_value); - napi_get_named_property(env, object, NULL, &prop); + node_api_get_named_property(env, object, NULL, &prop); add_last_status(env, "keyIsNull", return_value); - napi_get_named_property(env, object, "key", NULL); + node_api_get_named_property(env, object, "key", NULL); add_last_status(env, "valueIsNull", return_value); return return_value; } -static napi_value HasNamedProperty(napi_env env, napi_callback_info info) { - napi_value return_value, object; +static node_api_value +HasNamedProperty(node_api_env env, node_api_callback_info info) { + node_api_value return_value, object; bool result; - NAPI_CALL(env, napi_create_object(env, &return_value)); - NAPI_CALL(env, napi_create_object(env, &object)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &object)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, - napi_has_named_property(NULL, object, "key", &result)); + node_api_invalid_arg, + node_api_has_named_property( + NULL, object, "key", &result)); - napi_has_named_property(env, NULL, "key", &result); + node_api_has_named_property(env, NULL, "key", &result); add_last_status(env, "objectIsNull", return_value); - napi_has_named_property(env, object, NULL, &result); + node_api_has_named_property(env, object, NULL, &result); add_last_status(env, "keyIsNull", return_value); - napi_has_named_property(env, object, "key", NULL); + node_api_has_named_property(env, object, "key", NULL); add_last_status(env, "valueIsNull", return_value); return return_value; } -static napi_value SetElement(napi_env env, napi_callback_info info) { - napi_value return_value, object; +static node_api_value +SetElement(node_api_env env, node_api_callback_info info) { + node_api_value return_value, object; - NAPI_CALL(env, napi_create_object(env, &return_value)); - NAPI_CALL(env, napi_create_object(env, &object)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &object)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, - napi_set_element(NULL, object, 0, object)); + node_api_invalid_arg, + node_api_set_element(NULL, object, 0, object)); - napi_set_element(env, NULL, 0, object); + node_api_set_element(env, NULL, 0, object); add_last_status(env, "objectIsNull", return_value); - napi_set_property(env, object, 0, NULL); + node_api_set_property(env, object, 0, NULL); add_last_status(env, "valueIsNull", return_value); return return_value; } -static napi_value GetElement(napi_env env, napi_callback_info info) { - napi_value return_value, object, prop; +static node_api_value +GetElement(node_api_env env, node_api_callback_info info) { + node_api_value return_value, object, prop; - NAPI_CALL(env, napi_create_object(env, &return_value)); - NAPI_CALL(env, napi_create_object(env, &object)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &object)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, - napi_get_element(NULL, object, 0, &prop)); + node_api_invalid_arg, + node_api_get_element(NULL, object, 0, &prop)); - napi_get_property(env, NULL, 0, &prop); + node_api_get_property(env, NULL, 0, &prop); add_last_status(env, "objectIsNull", return_value); - napi_get_property(env, object, 0, NULL); + node_api_get_property(env, object, 0, NULL); add_last_status(env, "valueIsNull", return_value); return return_value; } -static napi_value TestBoolValuedElementApi(napi_env env, - napi_status (*api)(napi_env, napi_value, uint32_t, bool*)) { - napi_value return_value, object; +static node_api_value +TestBoolValuedElementApi( + node_api_env env, node_api_status (*api)(node_api_env, + node_api_value, + uint32_t, + bool*)) { + node_api_value return_value, object; bool result; - NAPI_CALL(env, napi_create_object(env, &return_value)); - NAPI_CALL(env, napi_create_object(env, &object)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &object)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, + node_api_invalid_arg, api(NULL, object, 0, &result)); api(env, NULL, 0, &result); @@ -242,159 +265,165 @@ static napi_value TestBoolValuedElementApi(napi_env env, return return_value; } -static napi_value HasElement(napi_env env, napi_callback_info info) { - return TestBoolValuedElementApi(env, napi_has_element); +static node_api_value +HasElement(node_api_env env, node_api_callback_info info) { + return TestBoolValuedElementApi(env, node_api_has_element); } -static napi_value DeleteElement(napi_env env, napi_callback_info info) { - return TestBoolValuedElementApi(env, napi_delete_element); +static node_api_value +DeleteElement(node_api_env env, node_api_callback_info info) { + return TestBoolValuedElementApi(env, node_api_delete_element); } -static napi_value DefineProperties(napi_env env, napi_callback_info info) { - napi_value object, return_value; +static node_api_value +DefineProperties(node_api_env env, node_api_callback_info info) { + node_api_value object, return_value; - napi_property_descriptor desc = { - "prop", NULL, DefineProperties, NULL, NULL, NULL, napi_enumerable, NULL + node_api_property_descriptor desc = { + "prop", NULL, DefineProperties, NULL, NULL, NULL, node_api_enumerable, NULL }; - NAPI_CALL(env, napi_create_object(env, &object)); - NAPI_CALL(env, napi_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &object)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, - napi_define_properties(NULL, object, 1, &desc)); + node_api_invalid_arg, + node_api_define_properties(NULL, object, 1, &desc)); - napi_define_properties(env, NULL, 1, &desc); + node_api_define_properties(env, NULL, 1, &desc); add_last_status(env, "objectIsNull", return_value); - napi_define_properties(env, object, 1, NULL); + node_api_define_properties(env, object, 1, NULL); add_last_status(env, "descriptorListIsNull", return_value); desc.utf8name = NULL; - napi_define_properties(env, object, 1, NULL); + node_api_define_properties(env, object, 1, NULL); add_last_status(env, "utf8nameIsNull", return_value); desc.utf8name = "prop"; desc.method = NULL; - napi_define_properties(env, object, 1, NULL); + node_api_define_properties(env, object, 1, NULL); add_last_status(env, "methodIsNull", return_value); desc.method = DefineProperties; return return_value; } -static napi_value GetPropertyNames(napi_env env, napi_callback_info info) { - napi_value return_value, props; +static node_api_value +GetPropertyNames(node_api_env env, node_api_callback_info info) { + node_api_value return_value, props; - NAPI_CALL(env, napi_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, - napi_get_property_names(NULL, return_value, &props)); + node_api_invalid_arg, + node_api_get_property_names(NULL, return_value, &props)); - napi_get_property_names(env, NULL, &props); + node_api_get_property_names(env, NULL, &props); add_last_status(env, "objectIsNull", return_value); - napi_get_property_names(env, return_value, NULL); + node_api_get_property_names(env, return_value, NULL); add_last_status(env, "valueIsNull", return_value); return return_value; } -static napi_value GetAllPropertyNames(napi_env env, napi_callback_info info) { - napi_value return_value, props; +static node_api_value +GetAllPropertyNames(node_api_env env, node_api_callback_info info) { + node_api_value return_value, props; - NAPI_CALL(env, napi_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, - napi_get_all_property_names(NULL, - return_value, - napi_key_own_only, - napi_key_writable, - napi_key_keep_numbers, - &props)); - - napi_get_all_property_names(env, - NULL, - napi_key_own_only, - napi_key_writable, - napi_key_keep_numbers, - &props); + node_api_invalid_arg, + node_api_get_all_property_names(NULL, + return_value, + node_api_key_own_only, + node_api_key_writable, + node_api_key_keep_numbers, + &props)); + + node_api_get_all_property_names(env, + NULL, + node_api_key_own_only, + node_api_key_writable, + node_api_key_keep_numbers, + &props); add_last_status(env, "objectIsNull", return_value); - napi_get_all_property_names(env, - return_value, - napi_key_own_only, - napi_key_writable, - napi_key_keep_numbers, - NULL); + node_api_get_all_property_names(env, + return_value, + node_api_key_own_only, + node_api_key_writable, + node_api_key_keep_numbers, + NULL); add_last_status(env, "valueIsNull", return_value); return return_value; } -static napi_value GetPrototype(napi_env env, napi_callback_info info) { - napi_value return_value, proto; +static node_api_value +GetPrototype(node_api_env env, node_api_callback_info info) { + node_api_value return_value, proto; - NAPI_CALL(env, napi_create_object(env, &return_value)); + NODE_API_CALL(env, node_api_create_object(env, &return_value)); add_returned_status(env, "envIsNull", return_value, "Invalid argument", - napi_invalid_arg, - napi_get_prototype(NULL, return_value, &proto)); + node_api_invalid_arg, + node_api_get_prototype(NULL, return_value, &proto)); - napi_get_prototype(env, NULL, &proto); + node_api_get_prototype(env, NULL, &proto); add_last_status(env, "objectIsNull", return_value); - napi_get_prototype(env, return_value, NULL); + node_api_get_prototype(env, return_value, NULL); add_last_status(env, "valueIsNull", return_value); return return_value; } -void init_test_null(napi_env env, napi_value exports) { - napi_value test_null; - - const napi_property_descriptor test_null_props[] = { - DECLARE_NAPI_PROPERTY("setProperty", SetProperty), - DECLARE_NAPI_PROPERTY("getProperty", GetProperty), - DECLARE_NAPI_PROPERTY("hasProperty", HasProperty), - DECLARE_NAPI_PROPERTY("hasOwnProperty", HasOwnProperty), - DECLARE_NAPI_PROPERTY("deleteProperty", DeleteProperty), - DECLARE_NAPI_PROPERTY("setNamedProperty", SetNamedProperty), - DECLARE_NAPI_PROPERTY("getNamedProperty", GetNamedProperty), - DECLARE_NAPI_PROPERTY("hasNamedProperty", HasNamedProperty), - DECLARE_NAPI_PROPERTY("setElement", SetElement), - DECLARE_NAPI_PROPERTY("getElement", GetElement), - DECLARE_NAPI_PROPERTY("hasElement", HasElement), - DECLARE_NAPI_PROPERTY("deleteElement", DeleteElement), - DECLARE_NAPI_PROPERTY("defineProperties", DefineProperties), - DECLARE_NAPI_PROPERTY("getPropertyNames", GetPropertyNames), - DECLARE_NAPI_PROPERTY("getAllPropertyNames", GetAllPropertyNames), - DECLARE_NAPI_PROPERTY("getPrototype", GetPrototype), +void init_test_null(node_api_env env, node_api_value exports) { + node_api_value test_null; + + const node_api_property_descriptor test_null_props[] = { + DECLARE_NODE_API_PROPERTY("setProperty", SetProperty), + DECLARE_NODE_API_PROPERTY("getProperty", GetProperty), + DECLARE_NODE_API_PROPERTY("hasProperty", HasProperty), + DECLARE_NODE_API_PROPERTY("hasOwnProperty", HasOwnProperty), + DECLARE_NODE_API_PROPERTY("deleteProperty", DeleteProperty), + DECLARE_NODE_API_PROPERTY("setNamedProperty", SetNamedProperty), + DECLARE_NODE_API_PROPERTY("getNamedProperty", GetNamedProperty), + DECLARE_NODE_API_PROPERTY("hasNamedProperty", HasNamedProperty), + DECLARE_NODE_API_PROPERTY("setElement", SetElement), + DECLARE_NODE_API_PROPERTY("getElement", GetElement), + DECLARE_NODE_API_PROPERTY("hasElement", HasElement), + DECLARE_NODE_API_PROPERTY("deleteElement", DeleteElement), + DECLARE_NODE_API_PROPERTY("defineProperties", DefineProperties), + DECLARE_NODE_API_PROPERTY("getPropertyNames", GetPropertyNames), + DECLARE_NODE_API_PROPERTY("getAllPropertyNames", GetAllPropertyNames), + DECLARE_NODE_API_PROPERTY("getPrototype", GetPrototype), }; - NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &test_null)); - NAPI_CALL_RETURN_VOID(env, napi_define_properties( + NODE_API_CALL_RETURN_VOID(env, node_api_create_object(env, &test_null)); + NODE_API_CALL_RETURN_VOID(env, node_api_define_properties( env, test_null, sizeof(test_null_props) / sizeof(*test_null_props), test_null_props)); - const napi_property_descriptor test_null_set = { - "testNull", NULL, NULL, NULL, NULL, test_null, napi_enumerable, NULL + const node_api_property_descriptor test_null_set = { + "testNull", NULL, NULL, NULL, NULL, test_null, node_api_enumerable, NULL }; - NAPI_CALL_RETURN_VOID(env, - napi_define_properties(env, exports, 1, &test_null_set)); + NODE_API_CALL_RETURN_VOID(env, + node_api_define_properties(env, exports, 1, &test_null_set)); } diff --git a/test/js-native-api/test_object/test_null.h b/test/js-native-api/test_object/test_null.h index e10b708372c3b1..bd4623dd4bb94a 100644 --- a/test/js-native-api/test_object/test_null.h +++ b/test/js-native-api/test_object/test_null.h @@ -3,6 +3,6 @@ #include -void init_test_null(napi_env env, napi_value exports); +void init_test_null(node_api_env env, node_api_value exports); #endif // TEST_JS_NATIVE_API_TEST_OBJECT_TEST_NULL_H_ diff --git a/test/js-native-api/test_object/test_null.js b/test/js-native-api/test_object/test_null.js index c94aa0fc84f19d..42b841c65b3aff 100644 --- a/test/js-native-api/test_object/test_null.js +++ b/test/js-native-api/test_object/test_null.js @@ -19,7 +19,7 @@ assert.deepStrictEqual(testNull.hasOwnProperty(), expectedForProperty); assert.deepStrictEqual(testNull.deleteProperty(), Object.assign({}, expectedForProperty, - { valueIsNull: 'napi_ok' })); + { valueIsNull: 'node_api_ok' })); assert.deepStrictEqual(testNull.setNamedProperty(), expectedForProperty); assert.deepStrictEqual(testNull.getNamedProperty(), expectedForProperty); assert.deepStrictEqual(testNull.hasNamedProperty(), expectedForProperty); @@ -36,7 +36,7 @@ assert.deepStrictEqual(testNull.hasElement(), expectedForElement); assert.deepStrictEqual(testNull.deleteElement(), Object.assign({}, expectedForElement, - { valueIsNull: 'napi_ok' })); + { valueIsNull: 'node_api_ok' })); assert.deepStrictEqual(testNull.defineProperties(), { envIsNull: 'Invalid argument', diff --git a/test/js-native-api/test_object/test_object.c b/test/js-native-api/test_object/test_object.c index 70a85e03c725dd..7c7012066add51 100644 --- a/test/js-native-api/test_object/test_object.c +++ b/test/js-native-api/test_object/test_object.c @@ -1,4 +1,4 @@ -#define NAPI_EXPERIMENTAL +#define NODE_API_EXPERIMENTAL #include #include "../common.h" #include @@ -6,563 +6,581 @@ static int test_value = 3; -static napi_value Get(napi_env env, napi_callback_info info) { +static node_api_value Get(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 2, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 2, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + node_api_valuetype valuetype1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); - NAPI_ASSERT(env, valuetype1 == napi_string || valuetype1 == napi_symbol, + NODE_API_ASSERT(env, + valuetype1 == node_api_string || valuetype1 == node_api_symbol, "Wrong type of arguments. Expects a string or symbol as second."); - napi_value object = args[0]; - napi_value output; - NAPI_CALL(env, napi_get_property(env, object, args[1], &output)); + node_api_value object = args[0]; + node_api_value output; + NODE_API_CALL(env, node_api_get_property(env, object, args[1], &output)); return output; } -static napi_value GetNamed(napi_env env, napi_callback_info info) { +static node_api_value GetNamed(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; + node_api_value args[2]; char key[256] = ""; size_t key_length; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 2, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 2, "Wrong number of arguments"); - napi_valuetype value_type0; - NAPI_CALL(env, napi_typeof(env, args[0], &value_type0)); + node_api_valuetype value_type0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &value_type0)); - NAPI_ASSERT(env, value_type0 == napi_object, + NODE_API_ASSERT(env, value_type0 == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - napi_valuetype value_type1; - NAPI_CALL(env, napi_typeof(env, args[1], &value_type1)); + node_api_valuetype value_type1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &value_type1)); - NAPI_ASSERT(env, value_type1 == napi_string, + NODE_API_ASSERT(env, value_type1 == node_api_string, "Wrong type of arguments. Expects a string as second."); - napi_value object = args[0]; - NAPI_CALL(env, - napi_get_value_string_utf8(env, args[1], key, 255, &key_length)); + node_api_value object = args[0]; + NODE_API_CALL(env, + node_api_get_value_string_utf8(env, args[1], key, 255, &key_length)); key[255] = 0; - NAPI_ASSERT(env, key_length <= 255, + NODE_API_ASSERT(env, key_length <= 255, "Cannot accommodate keys longer than 255 bytes"); - napi_value output; - NAPI_CALL(env, napi_get_named_property(env, object, key, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_get_named_property(env, object, key, &output)); return output; } -static napi_value GetPropertyNames(napi_env env, napi_callback_info info) { +static node_api_value +GetPropertyNames(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype value_type0; - NAPI_CALL(env, napi_typeof(env, args[0], &value_type0)); + node_api_valuetype value_type0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &value_type0)); - NAPI_ASSERT(env, value_type0 == napi_object, + NODE_API_ASSERT(env, value_type0 == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - napi_value output; - NAPI_CALL(env, napi_get_property_names(env, args[0], &output)); + node_api_value output; + NODE_API_CALL(env, node_api_get_property_names(env, args[0], &output)); return output; } -static napi_value GetSymbolNames(napi_env env, napi_callback_info info) { +static node_api_value +GetSymbolNames(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype value_type0; - NAPI_CALL(env, napi_typeof(env, args[0], &value_type0)); + node_api_valuetype value_type0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &value_type0)); - NAPI_ASSERT(env, - value_type0 == napi_object, + NODE_API_ASSERT(env, + value_type0 == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - napi_value output; - NAPI_CALL(env, - napi_get_all_property_names( + node_api_value output; + NODE_API_CALL(env, + node_api_get_all_property_names( env, args[0], - napi_key_include_prototypes, - napi_key_skip_strings, - napi_key_numbers_to_strings, + node_api_key_include_prototypes, + node_api_key_skip_strings, + node_api_key_numbers_to_strings, &output)); return output; } -static napi_value Set(napi_env env, napi_callback_info info) { +static node_api_value Set(node_api_env env, node_api_callback_info info) { size_t argc = 3; - napi_value args[3]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[3]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 3, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 3, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + node_api_valuetype valuetype1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); - NAPI_ASSERT(env, valuetype1 == napi_string || valuetype1 == napi_symbol, + NODE_API_ASSERT(env, + valuetype1 == node_api_string || valuetype1 == node_api_symbol, "Wrong type of arguments. Expects a string or symbol as second."); - NAPI_CALL(env, napi_set_property(env, args[0], args[1], args[2])); + NODE_API_CALL(env, node_api_set_property(env, args[0], args[1], args[2])); - napi_value valuetrue; - NAPI_CALL(env, napi_get_boolean(env, true, &valuetrue)); + node_api_value valuetrue; + NODE_API_CALL(env, node_api_get_boolean(env, true, &valuetrue)); return valuetrue; } -static napi_value SetNamed(napi_env env, napi_callback_info info) { +static node_api_value SetNamed(node_api_env env, node_api_callback_info info) { size_t argc = 3; - napi_value args[3]; + node_api_value args[3]; char key[256] = ""; size_t key_length; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 3, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 3, "Wrong number of arguments"); - napi_valuetype value_type0; - NAPI_CALL(env, napi_typeof(env, args[0], &value_type0)); + node_api_valuetype value_type0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &value_type0)); - NAPI_ASSERT(env, value_type0 == napi_object, + NODE_API_ASSERT(env, value_type0 == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - napi_valuetype value_type1; - NAPI_CALL(env, napi_typeof(env, args[1], &value_type1)); + node_api_valuetype value_type1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &value_type1)); - NAPI_ASSERT(env, value_type1 == napi_string, + NODE_API_ASSERT(env, value_type1 == node_api_string, "Wrong type of arguments. Expects a string as second."); - NAPI_CALL(env, - napi_get_value_string_utf8(env, args[1], key, 255, &key_length)); + NODE_API_CALL(env, + node_api_get_value_string_utf8(env, args[1], key, 255, &key_length)); key[255] = 0; - NAPI_ASSERT(env, key_length <= 255, + NODE_API_ASSERT(env, key_length <= 255, "Cannot accommodate keys longer than 255 bytes"); - NAPI_CALL(env, napi_set_named_property(env, args[0], key, args[2])); + NODE_API_CALL(env, node_api_set_named_property(env, args[0], key, args[2])); - napi_value value_true; - NAPI_CALL(env, napi_get_boolean(env, true, &value_true)); + node_api_value value_true; + NODE_API_CALL(env, node_api_get_boolean(env, true, &value_true)); return value_true; } -static napi_value Has(napi_env env, napi_callback_info info) { +static node_api_value Has(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 2, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 2, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + node_api_valuetype valuetype1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); - NAPI_ASSERT(env, valuetype1 == napi_string || valuetype1 == napi_symbol, + NODE_API_ASSERT(env, + valuetype1 == node_api_string || valuetype1 == node_api_symbol, "Wrong type of arguments. Expects a string or symbol as second."); bool has_property; - NAPI_CALL(env, napi_has_property(env, args[0], args[1], &has_property)); + NODE_API_CALL(env, + node_api_has_property(env, args[0], args[1], &has_property)); - napi_value ret; - NAPI_CALL(env, napi_get_boolean(env, has_property, &ret)); + node_api_value ret; + NODE_API_CALL(env, node_api_get_boolean(env, has_property, &ret)); return ret; } -static napi_value HasNamed(napi_env env, napi_callback_info info) { +static node_api_value HasNamed(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; + node_api_value args[2]; char key[256] = ""; size_t key_length; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 2, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 2, "Wrong number of arguments"); - napi_valuetype value_type0; - NAPI_CALL(env, napi_typeof(env, args[0], &value_type0)); + node_api_valuetype value_type0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &value_type0)); - NAPI_ASSERT(env, value_type0 == napi_object, + NODE_API_ASSERT(env, value_type0 == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - napi_valuetype value_type1; - NAPI_CALL(env, napi_typeof(env, args[1], &value_type1)); + node_api_valuetype value_type1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &value_type1)); - NAPI_ASSERT(env, value_type1 == napi_string || value_type1 == napi_symbol, + NODE_API_ASSERT(env, + value_type1 == node_api_string || value_type1 == node_api_symbol, "Wrong type of arguments. Expects a string as second."); - NAPI_CALL(env, - napi_get_value_string_utf8(env, args[1], key, 255, &key_length)); + NODE_API_CALL(env, + node_api_get_value_string_utf8(env, args[1], key, 255, &key_length)); key[255] = 0; - NAPI_ASSERT(env, key_length <= 255, + NODE_API_ASSERT(env, key_length <= 255, "Cannot accommodate keys longer than 255 bytes"); bool has_property; - NAPI_CALL(env, napi_has_named_property(env, args[0], key, &has_property)); + NODE_API_CALL(env, + node_api_has_named_property(env, args[0], key, &has_property)); - napi_value ret; - NAPI_CALL(env, napi_get_boolean(env, has_property, &ret)); + node_api_value ret; + NODE_API_CALL(env, node_api_get_boolean(env, has_property, &ret)); return ret; } -static napi_value HasOwn(napi_env env, napi_callback_info info) { +static node_api_value HasOwn(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 2, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - // napi_valuetype valuetype1; - // NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + // node_api_valuetype valuetype1; + // NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); // - // NAPI_ASSERT(env, valuetype1 == napi_string || valuetype1 == napi_symbol, + // NODE_API_ASSERT(env, + // valuetype1 == node_api_string || valuetype1 == node_api_symbol, // "Wrong type of arguments. Expects a string or symbol as second."); bool has_property; - NAPI_CALL(env, napi_has_own_property(env, args[0], args[1], &has_property)); + NODE_API_CALL(env, + node_api_has_own_property(env, args[0], args[1], &has_property)); - napi_value ret; - NAPI_CALL(env, napi_get_boolean(env, has_property, &ret)); + node_api_value ret; + NODE_API_CALL(env, node_api_get_boolean(env, has_property, &ret)); return ret; } -static napi_value Delete(napi_env env, napi_callback_info info) { +static node_api_value Delete(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; + node_api_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_ASSERT(env, argc == 2, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); - NAPI_ASSERT(env, valuetype1 == napi_string || valuetype1 == napi_symbol, + node_api_valuetype valuetype1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); + NODE_API_ASSERT(env, + valuetype1 == node_api_string || valuetype1 == node_api_symbol, "Wrong type of arguments. Expects a string or symbol as second."); bool result; - napi_value ret; - NAPI_CALL(env, napi_delete_property(env, args[0], args[1], &result)); - NAPI_CALL(env, napi_get_boolean(env, result, &ret)); + node_api_value ret; + NODE_API_CALL(env, node_api_delete_property(env, args[0], args[1], &result)); + NODE_API_CALL(env, node_api_get_boolean(env, result, &ret)); return ret; } -static napi_value New(napi_env env, napi_callback_info info) { - napi_value ret; - NAPI_CALL(env, napi_create_object(env, &ret)); +static node_api_value New(node_api_env env, node_api_callback_info info) { + node_api_value ret; + NODE_API_CALL(env, node_api_create_object(env, &ret)); - napi_value num; - NAPI_CALL(env, napi_create_int32(env, 987654321, &num)); + node_api_value num; + NODE_API_CALL(env, node_api_create_int32(env, 987654321, &num)); - NAPI_CALL(env, napi_set_named_property(env, ret, "test_number", num)); + NODE_API_CALL(env, + node_api_set_named_property(env, ret, "test_number", num)); - napi_value str; + node_api_value str; const char* str_val = "test string"; size_t str_len = strlen(str_val); - NAPI_CALL(env, napi_create_string_utf8(env, str_val, str_len, &str)); + NODE_API_CALL(env, node_api_create_string_utf8(env, str_val, str_len, &str)); - NAPI_CALL(env, napi_set_named_property(env, ret, "test_string", str)); + NODE_API_CALL(env, + node_api_set_named_property(env, ret, "test_string", str)); return ret; } -static napi_value Inflate(napi_env env, napi_callback_info info) { +static node_api_value Inflate(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - napi_value obj = args[0]; - napi_value propertynames; - NAPI_CALL(env, napi_get_property_names(env, obj, &propertynames)); + node_api_value obj = args[0]; + node_api_value propertynames; + NODE_API_CALL(env, node_api_get_property_names(env, obj, &propertynames)); uint32_t i, length; - NAPI_CALL(env, napi_get_array_length(env, propertynames, &length)); + NODE_API_CALL(env, node_api_get_array_length(env, propertynames, &length)); for (i = 0; i < length; i++) { - napi_value property_str; - NAPI_CALL(env, napi_get_element(env, propertynames, i, &property_str)); + node_api_value property_str; + NODE_API_CALL(env, + node_api_get_element(env, propertynames, i, &property_str)); - napi_value value; - NAPI_CALL(env, napi_get_property(env, obj, property_str, &value)); + node_api_value value; + NODE_API_CALL(env, node_api_get_property(env, obj, property_str, &value)); double double_val; - NAPI_CALL(env, napi_get_value_double(env, value, &double_val)); - NAPI_CALL(env, napi_create_double(env, double_val + 1, &value)); - NAPI_CALL(env, napi_set_property(env, obj, property_str, value)); + NODE_API_CALL(env, node_api_get_value_double(env, value, &double_val)); + NODE_API_CALL(env, node_api_create_double(env, double_val + 1, &value)); + NODE_API_CALL(env, node_api_set_property(env, obj, property_str, value)); } return obj; } -static napi_value Wrap(napi_env env, napi_callback_info info) { +static node_api_value Wrap(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value arg; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arg, NULL, NULL)); + node_api_value arg; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, &arg, NULL, NULL)); - NAPI_CALL(env, napi_wrap(env, arg, &test_value, NULL, NULL, NULL)); + NODE_API_CALL(env, node_api_wrap(env, arg, &test_value, NULL, NULL, NULL)); return NULL; } -static napi_value Unwrap(napi_env env, napi_callback_info info) { +static node_api_value Unwrap(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value arg; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arg, NULL, NULL)); + node_api_value arg; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, &arg, NULL, NULL)); void* data; - NAPI_CALL(env, napi_unwrap(env, arg, &data)); + NODE_API_CALL(env, node_api_unwrap(env, arg, &data)); bool is_expected = (data != NULL && *(int*)data == 3); - napi_value result; - NAPI_CALL(env, napi_get_boolean(env, is_expected, &result)); + node_api_value result; + NODE_API_CALL(env, node_api_get_boolean(env, is_expected, &result)); return result; } -static napi_value TestSetProperty(napi_env env, - napi_callback_info info) { - napi_status status; - napi_value object, key, value; +static node_api_value +TestSetProperty(node_api_env env, node_api_callback_info info) { + node_api_status status; + node_api_value object, key, value; - NAPI_CALL(env, napi_create_object(env, &object)); + NODE_API_CALL(env, node_api_create_object(env, &object)); - NAPI_CALL(env, napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &key)); + NODE_API_CALL(env, + node_api_create_string_utf8(env, "", NODE_API_AUTO_LENGTH, &key)); - NAPI_CALL(env, napi_create_object(env, &value)); + NODE_API_CALL(env, node_api_create_object(env, &value)); - status = napi_set_property(NULL, object, key, value); + status = node_api_set_property(NULL, object, key, value); add_returned_status(env, "envIsNull", object, "Invalid argument", - napi_invalid_arg, + node_api_invalid_arg, status); - napi_set_property(env, NULL, key, value); + node_api_set_property(env, NULL, key, value); add_last_status(env, "objectIsNull", object); - napi_set_property(env, object, NULL, value); + node_api_set_property(env, object, NULL, value); add_last_status(env, "keyIsNull", object); - napi_set_property(env, object, key, NULL); + node_api_set_property(env, object, key, NULL); add_last_status(env, "valueIsNull", object); return object; } -static napi_value TestHasProperty(napi_env env, - napi_callback_info info) { - napi_status status; - napi_value object, key; +static node_api_value +TestHasProperty(node_api_env env, node_api_callback_info info) { + node_api_status status; + node_api_value object, key; bool result; - NAPI_CALL(env, napi_create_object(env, &object)); + NODE_API_CALL(env, node_api_create_object(env, &object)); - NAPI_CALL(env, napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &key)); + NODE_API_CALL(env, + node_api_create_string_utf8(env, "", NODE_API_AUTO_LENGTH, &key)); - status = napi_has_property(NULL, object, key, &result); + status = node_api_has_property(NULL, object, key, &result); add_returned_status(env, "envIsNull", object, "Invalid argument", - napi_invalid_arg, + node_api_invalid_arg, status); - napi_has_property(env, NULL, key, &result); + node_api_has_property(env, NULL, key, &result); add_last_status(env, "objectIsNull", object); - napi_has_property(env, object, NULL, &result); + node_api_has_property(env, object, NULL, &result); add_last_status(env, "keyIsNull", object); - napi_has_property(env, object, key, NULL); + node_api_has_property(env, object, key, NULL); add_last_status(env, "resultIsNull", object); return object; } -static napi_value TestGetProperty(napi_env env, - napi_callback_info info) { - napi_status status; - napi_value object, key, result; +static node_api_value +TestGetProperty(node_api_env env, node_api_callback_info info) { + node_api_status status; + node_api_value object, key, result; - NAPI_CALL(env, napi_create_object(env, &object)); + NODE_API_CALL(env, node_api_create_object(env, &object)); - NAPI_CALL(env, napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &key)); + NODE_API_CALL(env, + node_api_create_string_utf8(env, "", NODE_API_AUTO_LENGTH, &key)); - NAPI_CALL(env, napi_create_object(env, &result)); + NODE_API_CALL(env, node_api_create_object(env, &result)); - status = napi_get_property(NULL, object, key, &result); + status = node_api_get_property(NULL, object, key, &result); add_returned_status(env, "envIsNull", object, "Invalid argument", - napi_invalid_arg, + node_api_invalid_arg, status); - napi_get_property(env, NULL, key, &result); + node_api_get_property(env, NULL, key, &result); add_last_status(env, "objectIsNull", object); - napi_get_property(env, object, NULL, &result); + node_api_get_property(env, object, NULL, &result); add_last_status(env, "keyIsNull", object); - napi_get_property(env, object, key, NULL); + node_api_get_property(env, object, key, NULL); add_last_status(env, "resultIsNull", object); return object; } -static napi_value TestFreeze(napi_env env, - napi_callback_info info) { +static node_api_value +TestFreeze(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value object = args[0]; - NAPI_CALL(env, napi_object_freeze(env, object)); + node_api_value object = args[0]; + NODE_API_CALL(env, node_api_object_freeze(env, object)); return object; } -static napi_value TestSeal(napi_env env, - napi_callback_info info) { +static node_api_value TestSeal(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value object = args[0]; - NAPI_CALL(env, napi_object_seal(env, object)); + node_api_value object = args[0]; + NODE_API_CALL(env, node_api_object_seal(env, object)); return object; } // We create two type tags. They are basically 128-bit UUIDs. -static const napi_type_tag type_tags[2] = { +static const node_api_type_tag type_tags[2] = { { 0xdaf987b3cc62481a, 0xb745b0497f299531 }, { 0xbb7936c374084d9b, 0xa9548d0762eeedb9 } }; -static napi_value -TypeTaggedInstance(napi_env env, napi_callback_info info) { +static node_api_value +TypeTaggedInstance(node_api_env env, node_api_callback_info info) { size_t argc = 1; uint32_t type_index; - napi_value instance, which_type; + node_api_value instance, which_type; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &which_type, NULL, NULL)); - NAPI_CALL(env, napi_get_value_uint32(env, which_type, &type_index)); - NAPI_CALL(env, napi_create_object(env, &instance)); - NAPI_CALL(env, napi_type_tag_object(env, instance, &type_tags[type_index])); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &which_type, NULL, NULL)); + NODE_API_CALL(env, node_api_get_value_uint32(env, which_type, &type_index)); + NODE_API_CALL(env, node_api_create_object(env, &instance)); + NODE_API_CALL(env, + node_api_type_tag_object(env, instance, &type_tags[type_index])); return instance; } -static napi_value -CheckTypeTag(napi_env env, napi_callback_info info) { +static node_api_value +CheckTypeTag(node_api_env env, node_api_callback_info info) { size_t argc = 2; bool result; - napi_value argv[2], js_result; + node_api_value argv[2], js_result; uint32_t type_index; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_CALL(env, napi_get_value_uint32(env, argv[0], &type_index)); - NAPI_CALL(env, napi_check_object_type_tag(env, - argv[1], - &type_tags[type_index], - &result)); - NAPI_CALL(env, napi_get_boolean(env, result, &js_result)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NODE_API_CALL(env, node_api_get_value_uint32(env, argv[0], &type_index)); + NODE_API_CALL(env, node_api_check_object_type_tag(env, + argv[1], + &type_tags[type_index], + &result)); + NODE_API_CALL(env, node_api_get_boolean(env, result, &js_result)); return js_result; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("Get", Get), - DECLARE_NAPI_PROPERTY("GetNamed", GetNamed), - DECLARE_NAPI_PROPERTY("GetPropertyNames", GetPropertyNames), - DECLARE_NAPI_PROPERTY("GetSymbolNames", GetSymbolNames), - DECLARE_NAPI_PROPERTY("Set", Set), - DECLARE_NAPI_PROPERTY("SetNamed", SetNamed), - DECLARE_NAPI_PROPERTY("Has", Has), - DECLARE_NAPI_PROPERTY("HasNamed", HasNamed), - DECLARE_NAPI_PROPERTY("HasOwn", HasOwn), - DECLARE_NAPI_PROPERTY("Delete", Delete), - DECLARE_NAPI_PROPERTY("New", New), - DECLARE_NAPI_PROPERTY("Inflate", Inflate), - DECLARE_NAPI_PROPERTY("Wrap", Wrap), - DECLARE_NAPI_PROPERTY("Unwrap", Unwrap), - DECLARE_NAPI_PROPERTY("TestSetProperty", TestSetProperty), - DECLARE_NAPI_PROPERTY("TestHasProperty", TestHasProperty), - DECLARE_NAPI_PROPERTY("TypeTaggedInstance", TypeTaggedInstance), - DECLARE_NAPI_PROPERTY("CheckTypeTag", CheckTypeTag), - DECLARE_NAPI_PROPERTY("TestGetProperty", TestGetProperty), - DECLARE_NAPI_PROPERTY("TestFreeze", TestFreeze), - DECLARE_NAPI_PROPERTY("TestSeal", TestSeal), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("Get", Get), + DECLARE_NODE_API_PROPERTY("GetNamed", GetNamed), + DECLARE_NODE_API_PROPERTY("GetPropertyNames", GetPropertyNames), + DECLARE_NODE_API_PROPERTY("GetSymbolNames", GetSymbolNames), + DECLARE_NODE_API_PROPERTY("Set", Set), + DECLARE_NODE_API_PROPERTY("SetNamed", SetNamed), + DECLARE_NODE_API_PROPERTY("Has", Has), + DECLARE_NODE_API_PROPERTY("HasNamed", HasNamed), + DECLARE_NODE_API_PROPERTY("HasOwn", HasOwn), + DECLARE_NODE_API_PROPERTY("Delete", Delete), + DECLARE_NODE_API_PROPERTY("New", New), + DECLARE_NODE_API_PROPERTY("Inflate", Inflate), + DECLARE_NODE_API_PROPERTY("Wrap", Wrap), + DECLARE_NODE_API_PROPERTY("Unwrap", Unwrap), + DECLARE_NODE_API_PROPERTY("TestSetProperty", TestSetProperty), + DECLARE_NODE_API_PROPERTY("TestHasProperty", TestHasProperty), + DECLARE_NODE_API_PROPERTY("TypeTaggedInstance", TypeTaggedInstance), + DECLARE_NODE_API_PROPERTY("CheckTypeTag", CheckTypeTag), + DECLARE_NODE_API_PROPERTY("TestGetProperty", TestGetProperty), + DECLARE_NODE_API_PROPERTY("TestFreeze", TestFreeze), + DECLARE_NODE_API_PROPERTY("TestSeal", TestSeal), }; init_test_null(env, exports); - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/js-native-api/test_promise/test_promise.c b/test/js-native-api/test_promise/test_promise.c index 11f7dea1917723..3cacb081e10aab 100644 --- a/test/js-native-api/test_promise/test_promise.c +++ b/test/js-native-api/test_promise/test_promise.c @@ -1,33 +1,34 @@ #include #include "../common.h" -napi_deferred deferred = NULL; +node_api_deferred deferred = NULL; -static napi_value createPromise(napi_env env, napi_callback_info info) { - napi_value promise; +static node_api_value +createPromise(node_api_env env, node_api_callback_info info) { + node_api_value promise; // We do not overwrite an existing deferred. if (deferred != NULL) { return NULL; } - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + NODE_API_CALL(env, node_api_create_promise(env, &deferred, &promise)); return promise; } -static napi_value -concludeCurrentPromise(napi_env env, napi_callback_info info) { - napi_value argv[2]; +static node_api_value +concludeCurrentPromise(node_api_env env, node_api_callback_info info) { + node_api_value argv[2]; size_t argc = 2; bool resolution; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_CALL(env, napi_get_value_bool(env, argv[1], &resolution)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NODE_API_CALL(env, node_api_get_value_bool(env, argv[1], &resolution)); if (resolution) { - NAPI_CALL(env, napi_resolve_deferred(env, deferred, argv[0])); + NODE_API_CALL(env, node_api_resolve_deferred(env, deferred, argv[0])); } else { - NAPI_CALL(env, napi_reject_deferred(env, deferred, argv[0])); + NODE_API_CALL(env, node_api_reject_deferred(env, deferred, argv[0])); } deferred = NULL; @@ -35,27 +36,30 @@ concludeCurrentPromise(napi_env env, napi_callback_info info) { return NULL; } -static napi_value isPromise(napi_env env, napi_callback_info info) { - napi_value promise, result; +static node_api_value +isPromise(node_api_env env, node_api_callback_info info) { + node_api_value promise, result; size_t argc = 1; bool is_promise; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &promise, NULL, NULL)); - NAPI_CALL(env, napi_is_promise(env, promise, &is_promise)); - NAPI_CALL(env, napi_get_boolean(env, is_promise, &result)); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &promise, NULL, NULL)); + NODE_API_CALL(env, node_api_is_promise(env, promise, &is_promise)); + NODE_API_CALL(env, node_api_get_boolean(env, is_promise, &result)); return result; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("createPromise", createPromise), - DECLARE_NAPI_PROPERTY("concludeCurrentPromise", concludeCurrentPromise), - DECLARE_NAPI_PROPERTY("isPromise", isPromise), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("createPromise", createPromise), + DECLARE_NODE_API_PROPERTY("concludeCurrentPromise", + concludeCurrentPromise), + DECLARE_NODE_API_PROPERTY("isPromise", isPromise), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/js-native-api/test_properties/test.js b/test/js-native-api/test_properties/test.js index 704002dfc74f3a..574610b54eb9ea 100644 --- a/test/js-native-api/test_properties/test.js +++ b/test/js-native-api/test_properties/test.js @@ -20,7 +20,7 @@ assert.throws(() => { test_object.readonlyValue = 3; }, readonlyErrorRE); assert.ok(test_object.hiddenValue); -// Properties with napi_enumerable attribute should be enumerable. +// Properties with node_api_enumerable attribute should be enumerable. const propertyNames = []; for (const name in test_object) { propertyNames.push(name); @@ -42,7 +42,7 @@ const symbolDescription = String(Object.getOwnPropertySymbols(test_object)[0]).slice(start, end); assert.strictEqual(symbolDescription, 'NameKeySymbol'); -// The napi_writable attribute should be ignored for accessors. +// The node_api_writable attribute should be ignored for accessors. const readwriteAccessor1Descriptor = Object.getOwnPropertyDescriptor(test_object, 'readwriteAccessor1'); const readonlyAccessor1Descriptor = diff --git a/test/js-native-api/test_properties/test_properties.c b/test/js-native-api/test_properties/test_properties.c index f26335ef1be842..bde19274711a47 100644 --- a/test/js-native-api/test_properties/test_properties.c +++ b/test/js-native-api/test_properties/test_properties.c @@ -3,98 +3,102 @@ static double value_ = 1; -static napi_value GetValue(napi_env env, napi_callback_info info) { +static node_api_value GetValue(node_api_env env, node_api_callback_info info) { size_t argc = 0; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, NULL, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, NULL, NULL, NULL)); - NAPI_ASSERT(env, argc == 0, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 0, "Wrong number of arguments"); - napi_value number; - NAPI_CALL(env, napi_create_double(env, value_, &number)); + node_api_value number; + NODE_API_CALL(env, node_api_create_double(env, value_, &number)); return number; } -static napi_value SetValue(napi_env env, napi_callback_info info) { +static node_api_value SetValue(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments"); - NAPI_CALL(env, napi_get_value_double(env, args[0], &value_)); + NODE_API_CALL(env, node_api_get_value_double(env, args[0], &value_)); return NULL; } -static napi_value Echo(napi_env env, napi_callback_info info) { +static node_api_value Echo(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments"); return args[0]; } -static napi_value HasNamedProperty(napi_env env, napi_callback_info info) { +static node_api_value +HasNamedProperty(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 2, "Wrong number of arguments"); // Extract the name of the property to check char buffer[128]; size_t copied; - NAPI_CALL(env, - napi_get_value_string_utf8(env, args[1], buffer, sizeof(buffer), &copied)); + NODE_API_CALL(env, + node_api_get_value_string_utf8( + env, args[1], buffer, sizeof(buffer), &copied)); // do the check and create the boolean return value bool value; - napi_value result; - NAPI_CALL(env, napi_has_named_property(env, args[0], buffer, &value)); - NAPI_CALL(env, napi_get_boolean(env, value, &result)); + node_api_value result; + NODE_API_CALL(env, + node_api_has_named_property(env, args[0], buffer, &value)); + NODE_API_CALL(env, node_api_get_boolean(env, value, &result)); return result; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_value number; - NAPI_CALL(env, napi_create_double(env, value_, &number)); - - napi_value name_value; - NAPI_CALL(env, napi_create_string_utf8(env, - "NameKeyValue", - NAPI_AUTO_LENGTH, - &name_value)); - - napi_value symbol_description; - napi_value name_symbol; - NAPI_CALL(env, napi_create_string_utf8(env, - "NameKeySymbol", - NAPI_AUTO_LENGTH, - &symbol_description)); - NAPI_CALL(env, napi_create_symbol(env, +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_value number; + NODE_API_CALL(env, node_api_create_double(env, value_, &number)); + + node_api_value name_value; + NODE_API_CALL(env, node_api_create_string_utf8(env, + "NameKeyValue", + NODE_API_AUTO_LENGTH, + &name_value)); + + node_api_value symbol_description; + node_api_value name_symbol; + NODE_API_CALL(env, node_api_create_string_utf8(env, + "NameKeySymbol", + NODE_API_AUTO_LENGTH, + &symbol_description)); + NODE_API_CALL(env, node_api_create_symbol(env, symbol_description, &name_symbol)); - napi_property_descriptor properties[] = { - { "echo", 0, Echo, 0, 0, 0, napi_enumerable, 0 }, - { "readwriteValue", 0, 0, 0, 0, number, napi_enumerable | napi_writable, 0 }, - { "readonlyValue", 0, 0, 0, 0, number, napi_enumerable, 0}, - { "hiddenValue", 0, 0, 0, 0, number, napi_default, 0}, - { NULL, name_value, 0, 0, 0, number, napi_enumerable, 0}, - { NULL, name_symbol, 0, 0, 0, number, napi_enumerable, 0}, - { "readwriteAccessor1", 0, 0, GetValue, SetValue, 0, napi_default, 0}, - { "readwriteAccessor2", 0, 0, GetValue, SetValue, 0, napi_writable, 0}, - { "readonlyAccessor1", 0, 0, GetValue, NULL, 0, napi_default, 0}, - { "readonlyAccessor2", 0, 0, GetValue, NULL, 0, napi_writable, 0}, - { "hasNamedProperty", 0, HasNamedProperty, 0, 0, 0, napi_default, 0 }, + node_api_property_descriptor properties[] = { + { "echo", 0, Echo, 0, 0, 0, node_api_enumerable, 0 }, + { "readwriteValue", 0, 0, 0, 0, number, + node_api_enumerable | node_api_writable, 0 }, + { "readonlyValue", 0, 0, 0, 0, number, node_api_enumerable, 0}, + { "hiddenValue", 0, 0, 0, 0, number, node_api_default, 0}, + { NULL, name_value, 0, 0, 0, number, node_api_enumerable, 0}, + { NULL, name_symbol, 0, 0, 0, number, node_api_enumerable, 0}, + { "readwriteAccessor1", 0, 0, GetValue, SetValue, 0, node_api_default, 0}, + { "readwriteAccessor2", 0, 0, GetValue, SetValue, 0, node_api_writable, 0}, + { "readonlyAccessor1", 0, 0, GetValue, NULL, 0, node_api_default, 0}, + { "readonlyAccessor2", 0, 0, GetValue, NULL, 0, node_api_writable, 0}, + { "hasNamedProperty", 0, HasNamedProperty, 0, 0, 0, node_api_default, 0 }, }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; diff --git a/test/js-native-api/test_reference/test.js b/test/js-native-api/test_reference/test.js index 0c9d13075f2aa0..df221f4cc91cb8 100644 --- a/test/js-native-api/test_reference/test.js +++ b/test/js-native-api/test_reference/test.js @@ -88,18 +88,18 @@ async function runTests() { } runTests(); -// This test creates a napi_ref on an object that has -// been wrapped by napi_wrap and for which the finalizer -// for the wrap calls napi_delete_ref on that napi_ref. +// This test creates a node_api_ref on an object that has +// been wrapped by node_api_wrap and for which the finalizer +// for the wrap calls node_api_delete_ref on that node_api_ref. // // Since both the wrap and the reference use the same // object the finalizer for the wrap and reference // may run in the same gc and in any order. // -// It does that to validate that napi_delete_ref can be +// It does that to validate that node_api_delete_ref can be // called before the finalizer has been run for the // reference (there is a finalizer behind the scenes even -// though it cannot be passed to napi_create_reference). +// though it cannot be passed to node_api_create_reference). // // Since the order is not guarranteed, run the // test a number of times maximize the chance that we diff --git a/test/js-native-api/test_reference/test_reference.c b/test/js-native-api/test_reference/test_reference.c index 05d5ae3eab8eb5..9eb057ff9205ef 100644 --- a/test/js-native-api/test_reference/test_reference.c +++ b/test/js-native-api/test_reference/test_reference.c @@ -5,188 +5,202 @@ static int test_value = 1; static int finalize_count = 0; -static napi_ref test_reference = NULL; +static node_api_ref test_reference = NULL; -static napi_value GetFinalizeCount(napi_env env, napi_callback_info info) { - napi_value result; - NAPI_CALL(env, napi_create_int32(env, finalize_count, &result)); +static node_api_value +GetFinalizeCount(node_api_env env, node_api_callback_info info) { + node_api_value result; + NODE_API_CALL(env, node_api_create_int32(env, finalize_count, &result)); return result; } -static void FinalizeExternal(napi_env env, void* data, void* hint) { +static void FinalizeExternal(node_api_env env, void* data, void* hint) { int *actual_value = data; - NAPI_ASSERT_RETURN_VOID(env, actual_value == &test_value, + NODE_API_ASSERT_RETURN_VOID(env, actual_value == &test_value, "The correct pointer was passed to the finalizer"); finalize_count++; } -static napi_value CreateExternal(napi_env env, napi_callback_info info) { +static node_api_value +CreateExternal(node_api_env env, node_api_callback_info info) { int* data = &test_value; - napi_value result; - NAPI_CALL(env, - napi_create_external(env, - data, - NULL, /* finalize_cb */ - NULL, /* finalize_hint */ - &result)); + node_api_value result; + NODE_API_CALL(env, + node_api_create_external(env, + data, + NULL, /* finalize_cb */ + NULL, /* finalize_hint */ + &result)); finalize_count = 0; return result; } -static napi_value -CreateExternalWithFinalize(napi_env env, napi_callback_info info) { - napi_value result; - NAPI_CALL(env, - napi_create_external(env, - &test_value, - FinalizeExternal, - NULL, /* finalize_hint */ - &result)); +static node_api_value +CreateExternalWithFinalize(node_api_env env, node_api_callback_info info) { + node_api_value result; + NODE_API_CALL(env, + node_api_create_external(env, + &test_value, + FinalizeExternal, + NULL, /* finalize_hint */ + &result)); finalize_count = 0; return result; } -static napi_value CheckExternal(napi_env env, napi_callback_info info) { +static node_api_value +CheckExternal(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value arg; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arg, NULL, NULL)); + node_api_value arg; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, &arg, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Expected one argument."); + NODE_API_ASSERT(env, argc == 1, "Expected one argument."); - napi_valuetype argtype; - NAPI_CALL(env, napi_typeof(env, arg, &argtype)); + node_api_valuetype argtype; + NODE_API_CALL(env, node_api_typeof(env, arg, &argtype)); - NAPI_ASSERT(env, argtype == napi_external, "Expected an external value."); + NODE_API_ASSERT(env, argtype == node_api_external, + "Expected an external value."); void* data; - NAPI_CALL(env, napi_get_value_external(env, arg, &data)); + NODE_API_CALL(env, node_api_get_value_external(env, arg, &data)); - NAPI_ASSERT(env, data != NULL && *(int*)data == test_value, + NODE_API_ASSERT(env, data != NULL && *(int*)data == test_value, "An external data value of 1 was expected."); return NULL; } -static napi_value CreateReference(napi_env env, napi_callback_info info) { - NAPI_ASSERT(env, test_reference == NULL, +static node_api_value +CreateReference(node_api_env env, node_api_callback_info info) { + NODE_API_ASSERT(env, test_reference == NULL, "The test allows only one reference at a time."); size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 2, "Expected two arguments."); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_ASSERT(env, argc == 2, "Expected two arguments."); uint32_t initial_refcount; - NAPI_CALL(env, napi_get_value_uint32(env, args[1], &initial_refcount)); + NODE_API_CALL(env, + node_api_get_value_uint32(env, args[1], &initial_refcount)); - NAPI_CALL(env, - napi_create_reference(env, args[0], initial_refcount, &test_reference)); + NODE_API_CALL(env, + node_api_create_reference( + env, args[0], initial_refcount, &test_reference)); - NAPI_ASSERT(env, test_reference != NULL, + NODE_API_ASSERT(env, test_reference != NULL, "A reference should have been created."); return NULL; } -static napi_value DeleteReference(napi_env env, napi_callback_info info) { - NAPI_ASSERT(env, test_reference != NULL, +static node_api_value +DeleteReference(node_api_env env, node_api_callback_info info) { + NODE_API_ASSERT(env, test_reference != NULL, "A reference must have been created."); - NAPI_CALL(env, napi_delete_reference(env, test_reference)); + NODE_API_CALL(env, node_api_delete_reference(env, test_reference)); test_reference = NULL; return NULL; } -static napi_value IncrementRefcount(napi_env env, napi_callback_info info) { - NAPI_ASSERT(env, test_reference != NULL, +static node_api_value +IncrementRefcount(node_api_env env, node_api_callback_info info) { + NODE_API_ASSERT(env, test_reference != NULL, "A reference must have been created."); uint32_t refcount; - NAPI_CALL(env, napi_reference_ref(env, test_reference, &refcount)); + NODE_API_CALL(env, node_api_reference_ref(env, test_reference, &refcount)); - napi_value result; - NAPI_CALL(env, napi_create_uint32(env, refcount, &result)); + node_api_value result; + NODE_API_CALL(env, node_api_create_uint32(env, refcount, &result)); return result; } -static napi_value DecrementRefcount(napi_env env, napi_callback_info info) { - NAPI_ASSERT(env, test_reference != NULL, +static node_api_value +DecrementRefcount(node_api_env env, node_api_callback_info info) { + NODE_API_ASSERT(env, test_reference != NULL, "A reference must have been created."); uint32_t refcount; - NAPI_CALL(env, napi_reference_unref(env, test_reference, &refcount)); + NODE_API_CALL(env, node_api_reference_unref(env, test_reference, &refcount)); - napi_value result; - NAPI_CALL(env, napi_create_uint32(env, refcount, &result)); + node_api_value result; + NODE_API_CALL(env, node_api_create_uint32(env, refcount, &result)); return result; } -static napi_value GetReferenceValue(napi_env env, napi_callback_info info) { - NAPI_ASSERT(env, test_reference != NULL, +static node_api_value +GetReferenceValue(node_api_env env, node_api_callback_info info) { + NODE_API_ASSERT(env, test_reference != NULL, "A reference must have been created."); - napi_value result; - NAPI_CALL(env, napi_get_reference_value(env, test_reference, &result)); + node_api_value result; + NODE_API_CALL(env, + node_api_get_reference_value(env, test_reference, &result)); return result; } static void DeleteBeforeFinalizeFinalizer( - napi_env env, void* finalize_data, void* finalize_hint) { - napi_ref* ref = (napi_ref*)finalize_data; - napi_value value; - assert(napi_get_reference_value(env, *ref, &value) == napi_ok); + node_api_env env, void* finalize_data, void* finalize_hint) { + node_api_ref* ref = (node_api_ref*)finalize_data; + node_api_value value; + assert(node_api_get_reference_value(env, *ref, &value) == node_api_ok); assert(value == NULL); - napi_delete_reference(env, *ref); + node_api_delete_reference(env, *ref); free(ref); } -static napi_value ValidateDeleteBeforeFinalize(napi_env env, napi_callback_info info) { - napi_value wrapObject; +static node_api_value +ValidateDeleteBeforeFinalize(node_api_env env, node_api_callback_info info) { + node_api_value wrapObject; size_t argc = 1; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &wrapObject, NULL, NULL)); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, &wrapObject, NULL, NULL)); - napi_ref* ref_t = malloc(sizeof(napi_ref)); - NAPI_CALL(env, napi_wrap(env, - wrapObject, - ref_t, - DeleteBeforeFinalizeFinalizer, - NULL, - NULL)); + node_api_ref* ref_t = malloc(sizeof(node_api_ref)); + NODE_API_CALL(env, node_api_wrap(env, + wrapObject, + ref_t, + DeleteBeforeFinalizeFinalizer, + NULL, + NULL)); // Create a reference that will be eligible for collection at the same // time as the wrapped object by passing in the same wrapObject. // This means that the FinalizeOrderValidation callback may be run // before the finalizer for the newly created reference (there is a finalizer - // behind the scenes even though it cannot be passed to napi_create_reference) - // The Finalizer for the wrap (which is different than the finalizer - // for the reference) calls napi_delete_reference validating that - // napi_delete_reference can be called before the finalizer for the - // reference runs. - NAPI_CALL(env, napi_create_reference(env, wrapObject, 0, ref_t)); + // behind the scenes even though it cannot be passed to + // node_api_create_reference). The Finalizer for the wrap (which is different + // than the finalizer for the reference) calls node_api_delete_reference + // validating that node_api_delete_reference can be called before the + // finalizer for the reference runs. + NODE_API_CALL(env, node_api_create_reference(env, wrapObject, 0, ref_t)); return wrapObject; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_GETTER("finalizeCount", GetFinalizeCount), - DECLARE_NAPI_PROPERTY("createExternal", CreateExternal), - DECLARE_NAPI_PROPERTY("createExternalWithFinalize", +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_GETTER("finalizeCount", GetFinalizeCount), + DECLARE_NODE_API_PROPERTY("createExternal", CreateExternal), + DECLARE_NODE_API_PROPERTY("createExternalWithFinalize", CreateExternalWithFinalize), - DECLARE_NAPI_PROPERTY("checkExternal", CheckExternal), - DECLARE_NAPI_PROPERTY("createReference", CreateReference), - DECLARE_NAPI_PROPERTY("deleteReference", DeleteReference), - DECLARE_NAPI_PROPERTY("incrementRefcount", IncrementRefcount), - DECLARE_NAPI_PROPERTY("decrementRefcount", DecrementRefcount), - DECLARE_NAPI_GETTER("referenceValue", GetReferenceValue), - DECLARE_NAPI_PROPERTY("validateDeleteBeforeFinalize", + DECLARE_NODE_API_PROPERTY("checkExternal", CheckExternal), + DECLARE_NODE_API_PROPERTY("createReference", CreateReference), + DECLARE_NODE_API_PROPERTY("deleteReference", DeleteReference), + DECLARE_NODE_API_PROPERTY("incrementRefcount", IncrementRefcount), + DECLARE_NODE_API_PROPERTY("decrementRefcount", DecrementRefcount), + DECLARE_NODE_API_GETTER("referenceValue", GetReferenceValue), + DECLARE_NODE_API_PROPERTY("validateDeleteBeforeFinalize", ValidateDeleteBeforeFinalize), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/js-native-api/test_string/test_string.c b/test/js-native-api/test_string/test_string.c index e840feeacf2110..aeb3a512b743d1 100644 --- a/test/js-native-api/test_string/test_string.c +++ b/test/js-native-api/test_string/test_string.c @@ -3,284 +3,314 @@ #include #include "../common.h" -static napi_value TestLatin1(napi_env env, napi_callback_info info) { +static node_api_value +TestLatin1(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, + NODE_API_ASSERT(env, valuetype == node_api_string, "Wrong type of argment. Expects a string."); char buffer[128]; size_t buffer_size = 128; size_t copied; - NAPI_CALL(env, - napi_get_value_string_latin1(env, args[0], buffer, buffer_size, &copied)); + NODE_API_CALL(env, + node_api_get_value_string_latin1( + env, args[0], buffer, buffer_size, &copied)); - napi_value output; - NAPI_CALL(env, napi_create_string_latin1(env, buffer, copied, &output)); + node_api_value output; + NODE_API_CALL(env, + node_api_create_string_latin1(env, buffer, copied, &output)); return output; } -static napi_value TestUtf8(napi_env env, napi_callback_info info) { +static node_api_value TestUtf8(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, + NODE_API_ASSERT(env, valuetype == node_api_string, "Wrong type of argment. Expects a string."); char buffer[128]; size_t buffer_size = 128; size_t copied; - NAPI_CALL(env, - napi_get_value_string_utf8(env, args[0], buffer, buffer_size, &copied)); + NODE_API_CALL(env, + node_api_get_value_string_utf8( + env, args[0], buffer, buffer_size, &copied)); - napi_value output; - NAPI_CALL(env, napi_create_string_utf8(env, buffer, copied, &output)); + node_api_value output; + NODE_API_CALL(env, + node_api_create_string_utf8(env, buffer, copied, &output)); return output; } -static napi_value TestUtf16(napi_env env, napi_callback_info info) { +static node_api_value +TestUtf16(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, + NODE_API_ASSERT(env, valuetype == node_api_string, "Wrong type of argment. Expects a string."); char16_t buffer[128]; size_t buffer_size = 128; size_t copied; - NAPI_CALL(env, - napi_get_value_string_utf16(env, args[0], buffer, buffer_size, &copied)); + NODE_API_CALL(env, + node_api_get_value_string_utf16( + env, args[0], buffer, buffer_size, &copied)); - napi_value output; - NAPI_CALL(env, napi_create_string_utf16(env, buffer, copied, &output)); + node_api_value output; + NODE_API_CALL(env, + node_api_create_string_utf16(env, buffer, copied, &output)); return output; } -static napi_value -TestLatin1Insufficient(napi_env env, napi_callback_info info) { +static node_api_value +TestLatin1Insufficient(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, + NODE_API_ASSERT(env, valuetype == node_api_string, "Wrong type of argment. Expects a string."); char buffer[4]; size_t buffer_size = 4; size_t copied; - NAPI_CALL(env, - napi_get_value_string_latin1(env, args[0], buffer, buffer_size, &copied)); + NODE_API_CALL(env, + node_api_get_value_string_latin1( + env, args[0], buffer, buffer_size, &copied)); - napi_value output; - NAPI_CALL(env, napi_create_string_latin1(env, buffer, copied, &output)); + node_api_value output; + NODE_API_CALL(env, + node_api_create_string_latin1(env, buffer, copied, &output)); return output; } -static napi_value TestUtf8Insufficient(napi_env env, napi_callback_info info) { +static node_api_value +TestUtf8Insufficient(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, + NODE_API_ASSERT(env, valuetype == node_api_string, "Wrong type of argment. Expects a string."); char buffer[4]; size_t buffer_size = 4; size_t copied; - NAPI_CALL(env, - napi_get_value_string_utf8(env, args[0], buffer, buffer_size, &copied)); + NODE_API_CALL(env, + node_api_get_value_string_utf8( + env, args[0], buffer, buffer_size, &copied)); - napi_value output; - NAPI_CALL(env, napi_create_string_utf8(env, buffer, copied, &output)); + node_api_value output; + NODE_API_CALL(env, + node_api_create_string_utf8(env, buffer, copied, &output)); return output; } -static napi_value TestUtf16Insufficient(napi_env env, napi_callback_info info) { +static node_api_value +TestUtf16Insufficient(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, + NODE_API_ASSERT(env, valuetype == node_api_string, "Wrong type of argment. Expects a string."); char16_t buffer[4]; size_t buffer_size = 4; size_t copied; - NAPI_CALL(env, - napi_get_value_string_utf16(env, args[0], buffer, buffer_size, &copied)); + NODE_API_CALL(env, + node_api_get_value_string_utf16( + env, args[0], buffer, buffer_size, &copied)); - napi_value output; - NAPI_CALL(env, napi_create_string_utf16(env, buffer, copied, &output)); + node_api_value output; + NODE_API_CALL(env, + node_api_create_string_utf16(env, buffer, copied, &output)); return output; } -static napi_value Utf16Length(napi_env env, napi_callback_info info) { +static node_api_value +Utf16Length(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, + NODE_API_ASSERT(env, valuetype == node_api_string, "Wrong type of argment. Expects a string."); size_t length; - NAPI_CALL(env, napi_get_value_string_utf16(env, args[0], NULL, 0, &length)); + NODE_API_CALL(env, + node_api_get_value_string_utf16(env, args[0], NULL, 0, &length)); - napi_value output; - NAPI_CALL(env, napi_create_uint32(env, (uint32_t)length, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_uint32(env, (uint32_t)length, &output)); return output; } -static napi_value Utf8Length(napi_env env, napi_callback_info info) { +static node_api_value +Utf8Length(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc >= 1, "Wrong number of arguments"); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, + NODE_API_ASSERT(env, valuetype == node_api_string, "Wrong type of argment. Expects a string."); size_t length; - NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], NULL, 0, &length)); + NODE_API_CALL(env, + node_api_get_value_string_utf8(env, args[0], NULL, 0, &length)); - napi_value output; - NAPI_CALL(env, napi_create_uint32(env, (uint32_t)length, &output)); + node_api_value output; + NODE_API_CALL(env, node_api_create_uint32(env, (uint32_t)length, &output)); return output; } -static napi_value TestLargeUtf8(napi_env env, napi_callback_info info) { - napi_value output; +static node_api_value +TestLargeUtf8(node_api_env env, node_api_callback_info info) { + node_api_value output; if (SIZE_MAX > INT_MAX) { - NAPI_CALL(env, napi_create_string_utf8(env, "", ((size_t)INT_MAX) + 1, &output)); + NODE_API_CALL(env, + node_api_create_string_utf8(env, "", ((size_t)INT_MAX) + 1, &output)); } else { // just throw the expected error as there is nothing to test // in this case since we can't overflow - NAPI_CALL(env, napi_throw_error(env, NULL, "Invalid argument")); + NODE_API_CALL(env, node_api_throw_error(env, NULL, "Invalid argument")); } return output; } -static napi_value TestLargeLatin1(napi_env env, napi_callback_info info) { - napi_value output; +static node_api_value +TestLargeLatin1(node_api_env env, node_api_callback_info info) { + node_api_value output; if (SIZE_MAX > INT_MAX) { - NAPI_CALL(env, napi_create_string_latin1(env, "", ((size_t)INT_MAX) + 1, &output)); + NODE_API_CALL(env, + node_api_create_string_latin1( + env, "", ((size_t)INT_MAX) + 1, &output)); } else { // just throw the expected error as there is nothing to test // in this case since we can't overflow - NAPI_CALL(env, napi_throw_error(env, NULL, "Invalid argument")); + NODE_API_CALL(env, node_api_throw_error(env, NULL, "Invalid argument")); } return output; } -static napi_value TestLargeUtf16(napi_env env, napi_callback_info info) { - napi_value output; +static node_api_value +TestLargeUtf16(node_api_env env, node_api_callback_info info) { + node_api_value output; if (SIZE_MAX > INT_MAX) { - NAPI_CALL(env, napi_create_string_utf16(env, - ((const char16_t*)""), - ((size_t)INT_MAX) + 1, &output)); + NODE_API_CALL(env, + node_api_create_string_utf16( + env, ((const char16_t*)""), ((size_t)INT_MAX) + 1, &output)); } else { // just throw the expected error as there is nothing to test // in this case since we can't overflow - NAPI_CALL(env, napi_throw_error(env, NULL, "Invalid argument")); + NODE_API_CALL(env, node_api_throw_error(env, NULL, "Invalid argument")); } return output; } -static napi_value TestMemoryCorruption(napi_env env, napi_callback_info info) { +static node_api_value +TestMemoryCorruption(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments"); char buf[10] = { 0 }; - NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], buf, 0, NULL)); + NODE_API_CALL(env, + node_api_get_value_string_utf8(env, args[0], buf, 0, NULL)); char zero[10] = { 0 }; if (memcmp(buf, zero, sizeof(buf)) != 0) { - NAPI_CALL(env, napi_throw_error(env, NULL, "Buffer overwritten")); + NODE_API_CALL(env, node_api_throw_error(env, NULL, "Buffer overwritten")); } return NULL; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("TestLatin1", TestLatin1), - DECLARE_NAPI_PROPERTY("TestLatin1Insufficient", TestLatin1Insufficient), - DECLARE_NAPI_PROPERTY("TestUtf8", TestUtf8), - DECLARE_NAPI_PROPERTY("TestUtf8Insufficient", TestUtf8Insufficient), - DECLARE_NAPI_PROPERTY("TestUtf16", TestUtf16), - DECLARE_NAPI_PROPERTY("TestUtf16Insufficient", TestUtf16Insufficient), - DECLARE_NAPI_PROPERTY("Utf16Length", Utf16Length), - DECLARE_NAPI_PROPERTY("Utf8Length", Utf8Length), - DECLARE_NAPI_PROPERTY("TestLargeUtf8", TestLargeUtf8), - DECLARE_NAPI_PROPERTY("TestLargeLatin1", TestLargeLatin1), - DECLARE_NAPI_PROPERTY("TestLargeUtf16", TestLargeUtf16), - DECLARE_NAPI_PROPERTY("TestMemoryCorruption", TestMemoryCorruption), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor properties[] = { + DECLARE_NODE_API_PROPERTY("TestLatin1", TestLatin1), + DECLARE_NODE_API_PROPERTY("TestLatin1Insufficient", + TestLatin1Insufficient), + DECLARE_NODE_API_PROPERTY("TestUtf8", TestUtf8), + DECLARE_NODE_API_PROPERTY("TestUtf8Insufficient", TestUtf8Insufficient), + DECLARE_NODE_API_PROPERTY("TestUtf16", TestUtf16), + DECLARE_NODE_API_PROPERTY("TestUtf16Insufficient", TestUtf16Insufficient), + DECLARE_NODE_API_PROPERTY("Utf16Length", Utf16Length), + DECLARE_NODE_API_PROPERTY("Utf8Length", Utf8Length), + DECLARE_NODE_API_PROPERTY("TestLargeUtf8", TestLargeUtf8), + DECLARE_NODE_API_PROPERTY("TestLargeLatin1", TestLargeLatin1), + DECLARE_NODE_API_PROPERTY("TestLargeUtf16", TestLargeUtf16), + DECLARE_NODE_API_PROPERTY("TestMemoryCorruption", TestMemoryCorruption), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; diff --git a/test/js-native-api/test_symbol/test_symbol.c b/test/js-native-api/test_symbol/test_symbol.c index b50ae78928f84f..a5bb3cdc0773b4 100644 --- a/test/js-native-api/test_symbol/test_symbol.c +++ b/test/js-native-api/test_symbol/test_symbol.c @@ -1,35 +1,35 @@ #include #include "../common.h" -static napi_value New(napi_env env, napi_callback_info info) { +static node_api_value New(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value description = NULL; + node_api_value description = NULL; if (argc >= 1) { - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, + NODE_API_ASSERT(env, valuetype == node_api_string, "Wrong type of arguments. Expects a string."); description = args[0]; } - napi_value symbol; - NAPI_CALL(env, napi_create_symbol(env, description, &symbol)); + node_api_value symbol; + NODE_API_CALL(env, node_api_create_symbol(env, description, &symbol)); return symbol; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("New", New), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor properties[] = { + DECLARE_NODE_API_PROPERTY("New", New), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; diff --git a/test/js-native-api/test_typedarray/test_typedarray.c b/test/js-native-api/test_typedarray/test_typedarray.c index 1714b5fe717f87..b1b17379595847 100644 --- a/test/js-native-api/test_typedarray/test_typedarray.c +++ b/test/js-native-api/test_typedarray/test_typedarray.c @@ -3,70 +3,70 @@ #include #include "../common.h" -static napi_value Multiply(napi_env env, napi_callback_info info) { +static node_api_value Multiply(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 2, "Wrong number of arguments"); - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects a typed array as first argument."); - napi_value input_array = args[0]; + node_api_value input_array = args[0]; bool is_typedarray; - NAPI_CALL(env, napi_is_typedarray(env, input_array, &is_typedarray)); + NODE_API_CALL(env, node_api_is_typedarray(env, input_array, &is_typedarray)); - NAPI_ASSERT(env, is_typedarray, + NODE_API_ASSERT(env, is_typedarray, "Wrong type of arguments. Expects a typed array as first argument."); - napi_valuetype valuetype1; - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + node_api_valuetype valuetype1; + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype1)); - NAPI_ASSERT(env, valuetype1 == napi_number, + NODE_API_ASSERT(env, valuetype1 == node_api_number, "Wrong type of arguments. Expects a number as second argument."); double multiplier; - NAPI_CALL(env, napi_get_value_double(env, args[1], &multiplier)); + NODE_API_CALL(env, node_api_get_value_double(env, args[1], &multiplier)); - napi_typedarray_type type; - napi_value input_buffer; + node_api_typedarray_type type; + node_api_value input_buffer; size_t byte_offset; size_t i, length; - NAPI_CALL(env, napi_get_typedarray_info( + NODE_API_CALL(env, node_api_get_typedarray_info( env, input_array, &type, &length, NULL, &input_buffer, &byte_offset)); void* data; size_t byte_length; - NAPI_CALL(env, napi_get_arraybuffer_info( + NODE_API_CALL(env, node_api_get_arraybuffer_info( env, input_buffer, &data, &byte_length)); - napi_value output_buffer; + node_api_value output_buffer; void* output_ptr = NULL; - NAPI_CALL(env, napi_create_arraybuffer( + NODE_API_CALL(env, node_api_create_arraybuffer( env, byte_length, &output_ptr, &output_buffer)); - napi_value output_array; - NAPI_CALL(env, napi_create_typedarray( + node_api_value output_array; + NODE_API_CALL(env, node_api_create_typedarray( env, type, length, output_buffer, byte_offset, &output_array)); - if (type == napi_uint8_array) { + if (type == node_api_uint8_array) { uint8_t* input_bytes = (uint8_t*)(data) + byte_offset; uint8_t* output_bytes = (uint8_t*)(output_ptr); for (i = 0; i < length; i++) { output_bytes[i] = (uint8_t)(input_bytes[i] * multiplier); } - } else if (type == napi_float64_array) { + } else if (type == node_api_float64_array) { double* input_doubles = (double*)((uint8_t*)(data) + byte_offset); double* output_doubles = (double*)(output_ptr); for (i = 0; i < length; i++) { output_doubles[i] = input_doubles[i] * multiplier; } } else { - napi_throw_error(env, NULL, + node_api_throw_error(env, NULL, "Typed array was of a type not expected by test."); return NULL; } @@ -74,22 +74,22 @@ static napi_value Multiply(napi_env env, napi_callback_info info) { return output_array; } -static void FinalizeCallback(napi_env env, +static void FinalizeCallback(node_api_env env, void* finalize_data, void* finalize_hint) { free(finalize_data); } -static napi_value External(napi_env env, napi_callback_info info) { +static node_api_value External(node_api_env env, node_api_callback_info info) { const uint8_t nElem = 3; int8_t* externalData = malloc(nElem*sizeof(int8_t)); externalData[0] = 0; externalData[1] = 1; externalData[2] = 2; - napi_value output_buffer; - NAPI_CALL(env, napi_create_external_arraybuffer( + node_api_value output_buffer; + NODE_API_CALL(env, node_api_create_external_arraybuffer( env, externalData, nElem*sizeof(int8_t), @@ -97,9 +97,9 @@ static napi_value External(napi_env env, napi_callback_info info) { NULL, // finalize_hint &output_buffer)); - napi_value output_array; - NAPI_CALL(env, napi_create_typedarray(env, - napi_int8_array, + node_api_value output_array; + NODE_API_CALL(env, node_api_create_typedarray(env, + node_api_int8_array, nElem, output_buffer, 0, @@ -109,133 +109,145 @@ static napi_value External(napi_env env, napi_callback_info info) { } -static napi_value NullArrayBuffer(napi_env env, napi_callback_info info) { +static node_api_value +NullArrayBuffer(node_api_env env, node_api_callback_info info) { static void* data = NULL; - napi_value arraybuffer; - NAPI_CALL(env, - napi_create_external_arraybuffer(env, data, 0, NULL, NULL, &arraybuffer)); + node_api_value arraybuffer; + NODE_API_CALL(env, + node_api_create_external_arraybuffer( + env, data, 0, NULL, NULL, &arraybuffer)); return arraybuffer; } -static napi_value CreateTypedArray(napi_env env, napi_callback_info info) { +static node_api_value +CreateTypedArray(node_api_env env, node_api_callback_info info) { size_t argc = 4; - napi_value args[4]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + node_api_value args[4]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 2 || argc == 4, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc == 2 || argc == 4, "Wrong number of arguments"); - napi_value input_array = args[0]; - napi_valuetype valuetype0; - NAPI_CALL(env, napi_typeof(env, input_array, &valuetype0)); + node_api_value input_array = args[0]; + node_api_valuetype valuetype0; + NODE_API_CALL(env, node_api_typeof(env, input_array, &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_object, + NODE_API_ASSERT(env, valuetype0 == node_api_object, "Wrong type of arguments. Expects a typed array as first argument."); bool is_typedarray; - NAPI_CALL(env, napi_is_typedarray(env, input_array, &is_typedarray)); + NODE_API_CALL(env, node_api_is_typedarray(env, input_array, &is_typedarray)); - NAPI_ASSERT(env, is_typedarray, + NODE_API_ASSERT(env, is_typedarray, "Wrong type of arguments. Expects a typed array as first argument."); - napi_valuetype valuetype1; - napi_value input_buffer = args[1]; - NAPI_CALL(env, napi_typeof(env, input_buffer, &valuetype1)); + node_api_valuetype valuetype1; + node_api_value input_buffer = args[1]; + NODE_API_CALL(env, node_api_typeof(env, input_buffer, &valuetype1)); - NAPI_ASSERT(env, valuetype1 == napi_object, + NODE_API_ASSERT(env, valuetype1 == node_api_object, "Wrong type of arguments. Expects an array buffer as second argument."); bool is_arraybuffer; - NAPI_CALL(env, napi_is_arraybuffer(env, input_buffer, &is_arraybuffer)); + NODE_API_CALL(env, + node_api_is_arraybuffer(env, input_buffer, &is_arraybuffer)); - NAPI_ASSERT(env, is_arraybuffer, + NODE_API_ASSERT(env, is_arraybuffer, "Wrong type of arguments. Expects an array buffer as second argument."); - napi_typedarray_type type; - napi_value in_array_buffer; + node_api_typedarray_type type; + node_api_value in_array_buffer; size_t byte_offset; size_t length; - NAPI_CALL(env, napi_get_typedarray_info( + NODE_API_CALL(env, node_api_get_typedarray_info( env, input_array, &type, &length, NULL, &in_array_buffer, &byte_offset)); if (argc == 4) { - napi_valuetype valuetype2; - NAPI_CALL(env, napi_typeof(env, args[2], &valuetype2)); + node_api_valuetype valuetype2; + NODE_API_CALL(env, node_api_typeof(env, args[2], &valuetype2)); - NAPI_ASSERT(env, valuetype2 == napi_number, + NODE_API_ASSERT(env, valuetype2 == node_api_number, "Wrong type of arguments. Expects a number as third argument."); uint32_t uint32_length; - NAPI_CALL(env, napi_get_value_uint32(env, args[2], &uint32_length)); + NODE_API_CALL(env, + node_api_get_value_uint32(env, args[2], &uint32_length)); length = uint32_length; - napi_valuetype valuetype3; - NAPI_CALL(env, napi_typeof(env, args[3], &valuetype3)); + node_api_valuetype valuetype3; + NODE_API_CALL(env, node_api_typeof(env, args[3], &valuetype3)); - NAPI_ASSERT(env, valuetype3 == napi_number, + NODE_API_ASSERT(env, valuetype3 == node_api_number, "Wrong type of arguments. Expects a number as third argument."); uint32_t uint32_byte_offset; - NAPI_CALL(env, napi_get_value_uint32(env, args[3], &uint32_byte_offset)); + NODE_API_CALL(env, + node_api_get_value_uint32(env, args[3], &uint32_byte_offset)); byte_offset = uint32_byte_offset; } - napi_value output_array; - NAPI_CALL(env, napi_create_typedarray( + node_api_value output_array; + NODE_API_CALL(env, node_api_create_typedarray( env, type, length, input_buffer, byte_offset, &output_array)); return output_array; } -static napi_value Detach(napi_env env, napi_callback_info info) { +static node_api_value Detach(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments."); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments."); bool is_typedarray; - NAPI_CALL(env, napi_is_typedarray(env, args[0], &is_typedarray)); - NAPI_ASSERT(env, is_typedarray, "Wrong type of arguments. Expects a typedarray as first argument."); + NODE_API_CALL(env, node_api_is_typedarray(env, args[0], &is_typedarray)); + NODE_API_ASSERT(env, is_typedarray, + "Wrong type of arguments. Expects a typedarray as first argument."); - napi_value arraybuffer; - NAPI_CALL(env, napi_get_typedarray_info(env, args[0], NULL, NULL, NULL, &arraybuffer, NULL)); - NAPI_CALL(env, napi_detach_arraybuffer(env, arraybuffer)); + node_api_value arraybuffer; + NODE_API_CALL(env, + node_api_get_typedarray_info( + env, args[0], NULL, NULL, NULL, &arraybuffer, NULL)); + NODE_API_CALL(env, node_api_detach_arraybuffer(env, arraybuffer)); return NULL; } -static napi_value IsDetached(napi_env env, napi_callback_info info) { +static node_api_value +IsDetached(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments."); + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments."); - napi_value array_buffer = args[0]; + node_api_value array_buffer = args[0]; bool is_arraybuffer; - NAPI_CALL(env, napi_is_arraybuffer(env, array_buffer, &is_arraybuffer)); - NAPI_ASSERT(env, is_arraybuffer, + NODE_API_CALL(env, + node_api_is_arraybuffer(env, array_buffer, &is_arraybuffer)); + NODE_API_ASSERT(env, is_arraybuffer, "Wrong type of arguments. Expects an array buffer as first argument."); bool is_detached; - NAPI_CALL(env, napi_is_detached_arraybuffer(env, array_buffer, &is_detached)); + NODE_API_CALL(env, + node_api_is_detached_arraybuffer(env, array_buffer, &is_detached)); - napi_value result; - NAPI_CALL(env, napi_get_boolean(env, is_detached, &result)); + node_api_value result; + NODE_API_CALL(env, node_api_get_boolean(env, is_detached, &result)); return result; } EXTERN_C_START -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("Multiply", Multiply), - DECLARE_NAPI_PROPERTY("External", External), - DECLARE_NAPI_PROPERTY("NullArrayBuffer", NullArrayBuffer), - DECLARE_NAPI_PROPERTY("CreateTypedArray", CreateTypedArray), - DECLARE_NAPI_PROPERTY("Detach", Detach), - DECLARE_NAPI_PROPERTY("IsDetached", IsDetached), +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("Multiply", Multiply), + DECLARE_NODE_API_PROPERTY("External", External), + DECLARE_NODE_API_PROPERTY("NullArrayBuffer", NullArrayBuffer), + DECLARE_NODE_API_PROPERTY("CreateTypedArray", CreateTypedArray), + DECLARE_NODE_API_PROPERTY("Detach", Detach), + DECLARE_NODE_API_PROPERTY("IsDetached", IsDetached), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; diff --git a/test/node-api/1_hello_world/binding.c b/test/node-api/1_hello_world/binding.c index b896da2cba4d84..6c453b4d0bf2fb 100644 --- a/test/node-api/1_hello_world/binding.c +++ b/test/node-api/1_hello_world/binding.c @@ -2,16 +2,17 @@ #include "../../js-native-api/common.h" #include -static napi_value Method(napi_env env, napi_callback_info info) { - napi_value world; +static node_api_value Method(node_api_env env, node_api_callback_info info) { + node_api_value world; const char* str = "world"; size_t str_len = strlen(str); - NAPI_CALL(env, napi_create_string_utf8(env, str, str_len, &world)); + NODE_API_CALL(env, node_api_create_string_utf8(env, str, str_len, &world)); return world; } -NAPI_MODULE_INIT() { - napi_property_descriptor desc = DECLARE_NAPI_PROPERTY("hello", Method); - NAPI_CALL(env, napi_define_properties(env, exports, 1, &desc)); +NODE_API_MODULE_INIT() { + node_api_property_descriptor desc = + DECLARE_NODE_API_PROPERTY("hello", Method); + NODE_API_CALL(env, node_api_define_properties(env, exports, 1, &desc)); return exports; } diff --git a/test/node-api/1_hello_world/test.js b/test/node-api/1_hello_world/test.js index dd28e26a561295..07bdb948bb0267 100644 --- a/test/node-api/1_hello_world/test.js +++ b/test/node-api/1_hello_world/test.js @@ -14,7 +14,7 @@ const rebinding = require(bindingPath); assert.strictEqual(rebinding.hello(), 'world'); assert.notStrictEqual(binding.hello, rebinding.hello); -// Test that workers can load addons declared using NAPI_MODULE_INIT(). +// Test that workers can load addons declared using NODE_API_MODULE_INIT(). new Worker(` const { parentPort } = require('worker_threads'); const msg = require(${JSON.stringify(bindingPath)}).hello(); diff --git a/test/node-api/test_async/test_async.c b/test/node-api/test_async/test_async.c index 44ad08366b1908..33ff4c33108f93 100644 --- a/test/node-api/test_async/test_async.c +++ b/test/node-api/test_async/test_async.c @@ -15,14 +15,14 @@ typedef struct { int32_t _input; int32_t _output; - napi_ref _callback; - napi_async_work _request; + node_api_ref _callback; + node_api_async_work _request; } carrier; static carrier the_carrier; static carrier async_carrier[MAX_CANCEL_THREADS]; -static void Execute(napi_env env, void* data) { +static void Execute(node_api_env env, void* data) { #if defined _WIN32 Sleep(1000); #else @@ -35,101 +35,104 @@ static void Execute(napi_env env, void* data) { c->_output = c->_input * 2; } -static void Complete(napi_env env, napi_status status, void* data) { +static void Complete(node_api_env env, node_api_status status, void* data) { carrier* c = (carrier*)(data); if (c != &the_carrier) { - napi_throw_type_error(env, NULL, "Wrong data parameter to Complete."); + node_api_throw_type_error(env, NULL, "Wrong data parameter to Complete."); return; } - if (status != napi_ok) { - napi_throw_type_error(env, NULL, "Execute callback failed."); + if (status != node_api_ok) { + node_api_throw_type_error(env, NULL, "Execute callback failed."); return; } - napi_value argv[2]; + node_api_value argv[2]; - NAPI_CALL_RETURN_VOID(env, napi_get_null(env, &argv[0])); - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, c->_output, &argv[1])); - napi_value callback; - NAPI_CALL_RETURN_VOID(env, - napi_get_reference_value(env, c->_callback, &callback)); - napi_value global; - NAPI_CALL_RETURN_VOID(env, napi_get_global(env, &global)); + NODE_API_CALL_RETURN_VOID(env, node_api_get_null(env, &argv[0])); + NODE_API_CALL_RETURN_VOID(env, + node_api_create_int32(env, c->_output, &argv[1])); + node_api_value callback; + NODE_API_CALL_RETURN_VOID(env, + node_api_get_reference_value(env, c->_callback, &callback)); + node_api_value global; + NODE_API_CALL_RETURN_VOID(env, node_api_get_global(env, &global)); - napi_value result; - NAPI_CALL_RETURN_VOID(env, - napi_call_function(env, global, callback, 2, argv, &result)); + node_api_value result; + NODE_API_CALL_RETURN_VOID(env, + node_api_call_function(env, global, callback, 2, argv, &result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, c->_callback)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, c->_request)); + NODE_API_CALL_RETURN_VOID(env, node_api_delete_reference(env, c->_callback)); + NODE_API_CALL_RETURN_VOID(env, node_api_delete_async_work(env, c->_request)); } -static napi_value Test(napi_env env, napi_callback_info info) { +static node_api_value Test(node_api_env env, node_api_callback_info info) { size_t argc = 3; - napi_value argv[3]; - napi_value _this; - napi_value resource_name; + node_api_value argv[3]; + node_api_value _this; + node_api_value resource_name; void* data; - NAPI_CALL(env, - napi_get_cb_info(env, info, &argc, argv, &_this, &data)); - NAPI_ASSERT(env, argc >= 3, "Not enough arguments, expected 2."); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, argv, &_this, &data)); + NODE_API_ASSERT(env, argc >= 3, "Not enough arguments, expected 2."); - napi_valuetype t; - NAPI_CALL(env, napi_typeof(env, argv[0], &t)); - NAPI_ASSERT(env, t == napi_number, + node_api_valuetype t; + NODE_API_CALL(env, node_api_typeof(env, argv[0], &t)); + NODE_API_ASSERT(env, t == node_api_number, "Wrong first argument, integer expected."); - NAPI_CALL(env, napi_typeof(env, argv[1], &t)); - NAPI_ASSERT(env, t == napi_object, + NODE_API_CALL(env, node_api_typeof(env, argv[1], &t)); + NODE_API_ASSERT(env, t == node_api_object, "Wrong second argument, object expected."); - NAPI_CALL(env, napi_typeof(env, argv[2], &t)); - NAPI_ASSERT(env, t == napi_function, + NODE_API_CALL(env, node_api_typeof(env, argv[2], &t)); + NODE_API_ASSERT(env, t == node_api_function, "Wrong third argument, function expected."); the_carrier._output = 0; - NAPI_CALL(env, - napi_get_value_int32(env, argv[0], &the_carrier._input)); - NAPI_CALL(env, - napi_create_reference(env, argv[2], 1, &the_carrier._callback)); + NODE_API_CALL(env, + node_api_get_value_int32(env, argv[0], &the_carrier._input)); + NODE_API_CALL(env, + node_api_create_reference(env, argv[2], 1, &the_carrier._callback)); - NAPI_CALL(env, napi_create_string_utf8( - env, "TestResource", NAPI_AUTO_LENGTH, &resource_name)); - NAPI_CALL(env, napi_create_async_work(env, argv[1], resource_name, + NODE_API_CALL(env, node_api_create_string_utf8( + env, "TestResource", NODE_API_AUTO_LENGTH, &resource_name)); + NODE_API_CALL(env, node_api_create_async_work(env, argv[1], resource_name, Execute, Complete, &the_carrier, &the_carrier._request)); - NAPI_CALL(env, - napi_queue_async_work(env, the_carrier._request)); + NODE_API_CALL(env, + node_api_queue_async_work(env, the_carrier._request)); return NULL; } -static void BusyCancelComplete(napi_env env, napi_status status, void* data) { +static void +BusyCancelComplete(node_api_env env, node_api_status status, void* data) { carrier* c = (carrier*)(data); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, c->_request)); + NODE_API_CALL_RETURN_VOID(env, node_api_delete_async_work(env, c->_request)); } -static void CancelComplete(napi_env env, napi_status status, void* data) { +static void +CancelComplete(node_api_env env, node_api_status status, void* data) { carrier* c = (carrier*)(data); - if (status == napi_cancelled) { + if (status == node_api_cancelled) { // ok we got the status we expected so make the callback to // indicate the cancel succeeded. - napi_value callback; - NAPI_CALL_RETURN_VOID(env, - napi_get_reference_value(env, c->_callback, &callback)); - napi_value global; - NAPI_CALL_RETURN_VOID(env, napi_get_global(env, &global)); - napi_value result; - NAPI_CALL_RETURN_VOID(env, - napi_call_function(env, global, callback, 0, NULL, &result)); + node_api_value callback; + NODE_API_CALL_RETURN_VOID(env, + node_api_get_reference_value(env, c->_callback, &callback)); + node_api_value global; + NODE_API_CALL_RETURN_VOID(env, node_api_get_global(env, &global)); + node_api_value result; + NODE_API_CALL_RETURN_VOID(env, + node_api_call_function(env, global, callback, 0, NULL, &result)); } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, c->_request)); - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, c->_callback)); + NODE_API_CALL_RETURN_VOID(env, node_api_delete_async_work(env, c->_request)); + NODE_API_CALL_RETURN_VOID(env, node_api_delete_reference(env, c->_callback)); } -static void CancelExecute(napi_env env, void* data) { +static void CancelExecute(node_api_env env, void* data) { #if defined _WIN32 Sleep(1000); #else @@ -137,93 +140,102 @@ static void CancelExecute(napi_env env, void* data) { #endif } -static napi_value TestCancel(napi_env env, napi_callback_info info) { +static node_api_value +TestCancel(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value argv[1]; - napi_value _this; - napi_value resource_name; + node_api_value argv[1]; + node_api_value _this; + node_api_value resource_name; void* data; - NAPI_CALL(env, napi_create_string_utf8( - env, "TestResource", NAPI_AUTO_LENGTH, &resource_name)); + NODE_API_CALL(env, node_api_create_string_utf8( + env, "TestResource", NODE_API_AUTO_LENGTH, &resource_name)); // make sure the work we are going to cancel will not be // able to start by using all the threads in the pool for (int i = 1; i < MAX_CANCEL_THREADS; i++) { - NAPI_CALL(env, napi_create_async_work(env, NULL, resource_name, + NODE_API_CALL(env, node_api_create_async_work(env, NULL, resource_name, CancelExecute, BusyCancelComplete, &async_carrier[i], &async_carrier[i]._request)); - NAPI_CALL(env, napi_queue_async_work(env, async_carrier[i]._request)); + NODE_API_CALL(env, + node_api_queue_async_work(env, async_carrier[i]._request)); } // now queue the work we are going to cancel and then cancel it. // cancel will fail if the work has already started, but // we have prevented it from starting by consuming all of the // workers above. - NAPI_CALL(env, - napi_get_cb_info(env, info, &argc, argv, &_this, &data)); - NAPI_CALL(env, napi_create_async_work(env, NULL, resource_name, + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, argv, &_this, &data)); + NODE_API_CALL(env, node_api_create_async_work(env, NULL, resource_name, CancelExecute, CancelComplete, &async_carrier[0], &async_carrier[0]._request)); - NAPI_CALL(env, - napi_create_reference(env, argv[0], 1, &async_carrier[0]._callback)); - NAPI_CALL(env, napi_queue_async_work(env, async_carrier[0]._request)); - NAPI_CALL(env, napi_cancel_async_work(env, async_carrier[0]._request)); + NODE_API_CALL(env, + node_api_create_reference(env, argv[0], 1, &async_carrier[0]._callback)); + NODE_API_CALL(env, + node_api_queue_async_work(env, async_carrier[0]._request)); + NODE_API_CALL(env, + node_api_cancel_async_work(env, async_carrier[0]._request)); return NULL; } struct { - napi_ref ref; - napi_async_work work; + node_api_ref ref; + node_api_async_work work; } repeated_work_info = { NULL, NULL }; -static void RepeatedWorkerThread(napi_env env, void* data) {} - -static void RepeatedWorkComplete(napi_env env, napi_status status, void* data) { - napi_value cb, js_status; - NAPI_CALL_RETURN_VOID(env, - napi_get_reference_value(env, repeated_work_info.ref, &cb)); - NAPI_CALL_RETURN_VOID(env, - napi_delete_async_work(env, repeated_work_info.work)); - NAPI_CALL_RETURN_VOID(env, - napi_delete_reference(env, repeated_work_info.ref)); +static void RepeatedWorkerThread(node_api_env env, void* data) {} + +static void +RepeatedWorkComplete(node_api_env env, node_api_status status, void* data) { + node_api_value cb, js_status; + NODE_API_CALL_RETURN_VOID(env, + node_api_get_reference_value(env, repeated_work_info.ref, &cb)); + NODE_API_CALL_RETURN_VOID(env, + node_api_delete_async_work(env, repeated_work_info.work)); + NODE_API_CALL_RETURN_VOID(env, + node_api_delete_reference(env, repeated_work_info.ref)); repeated_work_info.work = NULL; repeated_work_info.ref = NULL; - NAPI_CALL_RETURN_VOID(env, - napi_create_uint32(env, (uint32_t)status, &js_status)); - NAPI_CALL_RETURN_VOID(env, - napi_call_function(env, cb, cb, 1, &js_status, NULL)); + NODE_API_CALL_RETURN_VOID(env, + node_api_create_uint32(env, (uint32_t)status, &js_status)); + NODE_API_CALL_RETURN_VOID(env, + node_api_call_function(env, cb, cb, 1, &js_status, NULL)); } -static napi_value DoRepeatedWork(napi_env env, napi_callback_info info) { +static node_api_value +DoRepeatedWork(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value cb, name; - NAPI_ASSERT(env, repeated_work_info.ref == NULL, + node_api_value cb, name; + NODE_API_ASSERT(env, repeated_work_info.ref == NULL, "Reference left over from previous work"); - NAPI_ASSERT(env, repeated_work_info.work == NULL, + NODE_API_ASSERT(env, repeated_work_info.work == NULL, "Work pointer left over from previous work"); - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &cb, NULL, NULL)); - NAPI_CALL(env, napi_create_reference(env, cb, 1, &repeated_work_info.ref)); - NAPI_CALL(env, - napi_create_string_utf8(env, "Repeated Work", NAPI_AUTO_LENGTH, &name)); - NAPI_CALL(env, - napi_create_async_work(env, NULL, name, RepeatedWorkerThread, - RepeatedWorkComplete, &repeated_work_info, &repeated_work_info.work)); - NAPI_CALL(env, napi_queue_async_work(env, repeated_work_info.work)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, &cb, NULL, NULL)); + NODE_API_CALL(env, + node_api_create_reference(env, cb, 1, &repeated_work_info.ref)); + NODE_API_CALL(env, + node_api_create_string_utf8( + env, "Repeated Work", NODE_API_AUTO_LENGTH, &name)); + NODE_API_CALL(env, + node_api_create_async_work(env, NULL, name, RepeatedWorkerThread, + RepeatedWorkComplete, &repeated_work_info, + &repeated_work_info.work)); + NODE_API_CALL(env, node_api_queue_async_work(env, repeated_work_info.work)); return NULL; } -static napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("Test", Test), - DECLARE_NAPI_PROPERTY("TestCancel", TestCancel), - DECLARE_NAPI_PROPERTY("DoRepeatedWork", DoRepeatedWork), +static node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor properties[] = { + DECLARE_NODE_API_PROPERTY("Test", Test), + DECLARE_NODE_API_PROPERTY("TestCancel", TestCancel), + DECLARE_NODE_API_PROPERTY("DoRepeatedWork", DoRepeatedWork), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_async_cleanup_hook/binding.c b/test/node-api/test_async_cleanup_hook/binding.c index 7bbde56bb0ec88..3d7e7ebb0dc955 100644 --- a/test/node-api/test_async_cleanup_hook/binding.c +++ b/test/node-api/test_async_cleanup_hook/binding.c @@ -1,18 +1,18 @@ -#define NAPI_EXPERIMENTAL +#define NODE_API_EXPERIMENTAL #include "node_api.h" #include "assert.h" #include "uv.h" #include #include "../../js-native-api/common.h" -static void MustNotCall(napi_async_cleanup_hook_handle hook, void* arg) { +static void MustNotCall(node_api_async_cleanup_hook_handle hook, void* arg) { assert(0); } struct AsyncData { uv_async_t async; - napi_env env; - napi_async_cleanup_hook_handle handle; + node_api_env env; + node_api_async_cleanup_hook_handle handle; }; static struct AsyncData* CreateAsyncData() { @@ -23,8 +23,8 @@ static struct AsyncData* CreateAsyncData() { static void AfterCleanupHookTwo(uv_handle_t* handle) { struct AsyncData* data = (struct AsyncData*) handle->data; - napi_status status = napi_remove_async_cleanup_hook(data->handle); - assert(status == napi_ok); + node_api_status status = node_api_remove_async_cleanup_hook(data->handle); + assert(status == node_api_ok); free(data); } @@ -32,11 +32,11 @@ static void AfterCleanupHookOne(uv_async_t* async) { uv_close((uv_handle_t*) async, AfterCleanupHookTwo); } -static void AsyncCleanupHook(napi_async_cleanup_hook_handle handle, void* arg) { +static void AsyncCleanupHook(node_api_async_cleanup_hook_handle handle, void* arg) { struct AsyncData* data = (struct AsyncData*) arg; uv_loop_t* loop; - napi_status status = napi_get_uv_event_loop(data->env, &loop); - assert(status == napi_ok); + node_api_status status = node_api_get_uv_event_loop(data->env, &loop); + assert(status == node_api_ok); int err = uv_async_init(loop, &data->async, AfterCleanupHookOne); assert(err == 0); @@ -45,27 +45,27 @@ static void AsyncCleanupHook(napi_async_cleanup_hook_handle handle, void* arg) { uv_async_send(&data->async); } -static napi_value Init(napi_env env, napi_value exports) { +static node_api_value Init(node_api_env env, node_api_value exports) { { struct AsyncData* data = CreateAsyncData(); data->env = env; - napi_add_async_cleanup_hook(env, AsyncCleanupHook, data, &data->handle); + node_api_add_async_cleanup_hook(env, AsyncCleanupHook, data, &data->handle); } { struct AsyncData* data = CreateAsyncData(); data->env = env; - napi_add_async_cleanup_hook(env, AsyncCleanupHook, data, NULL); + node_api_add_async_cleanup_hook(env, AsyncCleanupHook, data, NULL); } { - napi_async_cleanup_hook_handle must_not_call_handle; - napi_add_async_cleanup_hook( + node_api_async_cleanup_hook_handle must_not_call_handle; + node_api_add_async_cleanup_hook( env, MustNotCall, NULL, &must_not_call_handle); - napi_remove_async_cleanup_hook(must_not_call_handle); + node_api_remove_async_cleanup_hook(must_not_call_handle); } return NULL; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_async_context/binding.c b/test/node-api/test_async_context/binding.c index 3dab0fd0e818dd..15fbf35d2b919e 100644 --- a/test/node-api/test_async_context/binding.c +++ b/test/node-api/test_async_context/binding.c @@ -5,125 +5,135 @@ #define MAX_ARGUMENTS 10 #define RESERVED_ARGS 3 -static napi_value MakeCallback(napi_env env, napi_callback_info info) { +static node_api_value +MakeCallback(node_api_env env, node_api_callback_info info) { size_t argc = MAX_ARGUMENTS; size_t n; - napi_value args[MAX_ARGUMENTS]; + node_api_value args[MAX_ARGUMENTS]; // NOLINTNEXTLINE (readability/null_usage) - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc > 0, "Wrong number of arguments"); - napi_value async_context_wrap = args[0]; - napi_value recv = args[1]; - napi_value func = args[2]; + node_api_value async_context_wrap = args[0]; + node_api_value recv = args[1]; + node_api_value func = args[2]; - napi_value argv[MAX_ARGUMENTS - RESERVED_ARGS]; + node_api_value argv[MAX_ARGUMENTS - RESERVED_ARGS]; for (n = RESERVED_ARGS; n < argc; n += 1) { argv[n - RESERVED_ARGS] = args[n]; } - napi_valuetype func_type; - NAPI_CALL(env, napi_typeof(env, func, &func_type)); + node_api_valuetype func_type; + NODE_API_CALL(env, node_api_typeof(env, func, &func_type)); - napi_async_context context; - NAPI_CALL(env, napi_unwrap(env, async_context_wrap, (void**)&context)); + node_api_async_context context; + NODE_API_CALL(env, + node_api_unwrap(env, async_context_wrap, (void**)&context)); - napi_value result; - if (func_type == napi_function) { - NAPI_CALL(env, napi_make_callback( + node_api_value result; + if (func_type == node_api_function) { + NODE_API_CALL(env, node_api_make_callback( env, context, recv, func, argc - RESERVED_ARGS, argv, &result)); } else { - NAPI_ASSERT(env, false, "Unexpected argument type"); + NODE_API_ASSERT(env, false, "Unexpected argument type"); } return result; } -static void AsyncDestroyCb(napi_env env, void* data, void* hint) { - napi_status status = napi_async_destroy(env, (napi_async_context)data); - // We cannot use NAPI_ASSERT_RETURN_VOID because we need to have a JS stack - // below in order to use exceptions. - assert(status == napi_ok); +static void AsyncDestroyCb(node_api_env env, void* data, void* hint) { + node_api_status status = + node_api_async_destroy(env, (node_api_async_context)data); + // We cannot use NODE_API_ASSERT_RETURN_VOID because we need to have a JS + // stack below in order to use exceptions. + assert(status == node_api_ok); } #define CREATE_ASYNC_RESOURCE_ARGC 2 -static napi_value CreateAsyncResource(napi_env env, napi_callback_info info) { - napi_value async_context_wrap; - NAPI_CALL(env, napi_create_object(env, &async_context_wrap)); +static node_api_value +CreateAsyncResource(node_api_env env, node_api_callback_info info) { + node_api_value async_context_wrap; + NODE_API_CALL(env, node_api_create_object(env, &async_context_wrap)); size_t argc = CREATE_ASYNC_RESOURCE_ARGC; - napi_value args[CREATE_ASYNC_RESOURCE_ARGC]; + node_api_value args[CREATE_ASYNC_RESOURCE_ARGC]; // NOLINTNEXTLINE (readability/null_usage) - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value resource = args[0]; - napi_value js_destroy_on_finalizer = args[1]; - napi_valuetype resource_type; - NAPI_CALL(env, napi_typeof(env, resource, &resource_type)); - if (resource_type != napi_object) { + node_api_value resource = args[0]; + node_api_value js_destroy_on_finalizer = args[1]; + node_api_valuetype resource_type; + NODE_API_CALL(env, node_api_typeof(env, resource, &resource_type)); + if (resource_type != node_api_object) { resource = NULL; } - napi_value resource_name; - NAPI_CALL(env, napi_create_string_utf8( - env, "test_async", NAPI_AUTO_LENGTH, &resource_name)); + node_api_value resource_name; + NODE_API_CALL(env, node_api_create_string_utf8( + env, "test_async", NODE_API_AUTO_LENGTH, &resource_name)); - napi_async_context context; - NAPI_CALL(env, napi_async_init(env, resource, resource_name, &context)); + node_api_async_context context; + NODE_API_CALL(env, + node_api_async_init(env, resource, resource_name, &context)); bool destroy_on_finalizer = true; if (argc == 2) { - NAPI_CALL(env, napi_get_value_bool(env, js_destroy_on_finalizer, &destroy_on_finalizer)); + NODE_API_CALL(env, + node_api_get_value_bool( + env, js_destroy_on_finalizer, &destroy_on_finalizer)); } - if (resource_type == napi_object && destroy_on_finalizer) { - NAPI_CALL(env, napi_add_finalizer( + if (resource_type == node_api_object && destroy_on_finalizer) { + NODE_API_CALL(env, node_api_add_finalizer( env, resource, (void*)context, AsyncDestroyCb, NULL, NULL)); } - NAPI_CALL(env, napi_wrap(env, async_context_wrap, context, NULL, NULL, NULL)); + NODE_API_CALL(env, + node_api_wrap(env, async_context_wrap, context, NULL, NULL, NULL)); return async_context_wrap; } #define DESTROY_ASYNC_RESOURCE_ARGC 1 -static napi_value DestroyAsyncResource(napi_env env, napi_callback_info info) { +static node_api_value +DestroyAsyncResource(node_api_env env, node_api_callback_info info) { size_t argc = DESTROY_ASYNC_RESOURCE_ARGC; - napi_value args[DESTROY_ASYNC_RESOURCE_ARGC]; + node_api_value args[DESTROY_ASYNC_RESOURCE_ARGC]; // NOLINTNEXTLINE (readability/null_usage) - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments"); - napi_value async_context_wrap = args[0]; + node_api_value async_context_wrap = args[0]; - napi_async_context async_context; - NAPI_CALL(env, - napi_remove_wrap(env, async_context_wrap, (void**)&async_context)); - NAPI_CALL(env, napi_async_destroy(env, async_context)); + node_api_async_context async_context; + NODE_API_CALL(env, + node_api_remove_wrap(env, async_context_wrap, (void**)&async_context)); + NODE_API_CALL(env, node_api_async_destroy(env, async_context)); return async_context_wrap; } static -napi_value Init(napi_env env, napi_value exports) { - napi_value fn; - NAPI_CALL(env, napi_create_function( +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_value fn; + NODE_API_CALL(env, node_api_create_function( // NOLINTNEXTLINE (readability/null_usage) - env, NULL, NAPI_AUTO_LENGTH, MakeCallback, NULL, &fn)); - NAPI_CALL(env, napi_set_named_property(env, exports, "makeCallback", fn)); - NAPI_CALL(env, napi_create_function( + env, NULL, NODE_API_AUTO_LENGTH, MakeCallback, NULL, &fn)); + NODE_API_CALL(env, + node_api_set_named_property(env, exports, "makeCallback", fn)); + NODE_API_CALL(env, node_api_create_function( // NOLINTNEXTLINE (readability/null_usage) - env, NULL, NAPI_AUTO_LENGTH, CreateAsyncResource, NULL, &fn)); - NAPI_CALL(env, napi_set_named_property( + env, NULL, NODE_API_AUTO_LENGTH, CreateAsyncResource, NULL, &fn)); + NODE_API_CALL(env, node_api_set_named_property( env, exports, "createAsyncResource", fn)); - NAPI_CALL(env, napi_create_function( + NODE_API_CALL(env, node_api_create_function( // NOLINTNEXTLINE (readability/null_usage) - env, NULL, NAPI_AUTO_LENGTH, DestroyAsyncResource, NULL, &fn)); - NAPI_CALL(env, napi_set_named_property( + env, NULL, NODE_API_AUTO_LENGTH, DestroyAsyncResource, NULL, &fn)); + NODE_API_CALL(env, node_api_set_named_property( env, exports, "destroyAsyncResource", fn)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_async_context/test-gcable-callback.js b/test/node-api/test_async_context/test-gcable-callback.js index e66080bb6a3a90..84e32dd470945a 100644 --- a/test/node-api/test_async_context/test-gcable-callback.js +++ b/test/node-api/test_async_context/test-gcable-callback.js @@ -11,7 +11,8 @@ const { } = require(`./build/${common.buildType}/binding`); // Test for https://github.com/nodejs/node/issues/27218: -// napi_async_destroy() can be called during a regular garbage collection run. +// node_api_async_destroy() can be called during a regular garbage collection +// run. const hook_result = { id: null, @@ -38,9 +39,10 @@ const asyncResource = createAsyncResource( ); // Trigger GC. This does *not* use global.gc(), because what we want to verify -// is that `napi_async_destroy()` can be called when there is no JS context +// is that `node_api_async_destroy()` can be called when there is no JS context // on the stack at the time of GC. -// Currently, using --gc-interval=100 + 1M elements seems to work fine for this. +// Currently, using --gc-interval=100 + 1M elements seems to work fine for +// this. const arr = new Array(1024 * 1024); for (let i = 0; i < arr.length; i++) arr[i] = {}; @@ -52,7 +54,7 @@ setImmediate(() => { const executionAsyncResource = async_hooks.executionAsyncResource(); // Assuming the executionAsyncResource was created for the absence of the // initial `{ foo: 'bar' }`. - // This is the worst path of `napi_async_context` related API of + // This is the worst path of `node_api_async_context` related API of // recovering from the condition and not break the executionAsyncResource // shape, although the executionAsyncResource might not be correct. assert.strictEqual(typeof executionAsyncResource, 'object'); diff --git a/test/node-api/test_async_context/test-gcable.js b/test/node-api/test_async_context/test-gcable.js index 288b7412267dcc..6bbb542b383cfb 100644 --- a/test/node-api/test_async_context/test-gcable.js +++ b/test/node-api/test_async_context/test-gcable.js @@ -7,7 +7,8 @@ const async_hooks = require('async_hooks'); const { createAsyncResource } = require(`./build/${common.buildType}/binding`); // Test for https://github.com/nodejs/node/issues/27218: -// napi_async_destroy() can be called during a regular garbage collection run. +// node_api_async_destroy() can be called during a regular garbage collection +// run. const hook_result = { id: null, @@ -31,7 +32,7 @@ test_hook.enable(); createAsyncResource({}); // Trigger GC. This does *not* use global.gc(), because what we want to verify -// is that `napi_async_destroy()` can be called when there is no JS context +// is that `node_api_async_destroy()` can be called when there is no JS context // on the stack at the time of GC. // Currently, using --gc-interval=100 + 1M elements seems to work fine for this. const arr = new Array(1024 * 1024); diff --git a/test/node-api/test_buffer/test_buffer.c b/test/node-api/test_buffer/test_buffer.c index 15d7c46e975d9a..1bdace4ebdc846 100644 --- a/test/node-api/test_buffer/test_buffer.c +++ b/test/node-api/test_buffer/test_buffer.c @@ -7,139 +7,150 @@ static const char theText[] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; static int deleterCallCount = 0; -static void deleteTheText(napi_env env, void* data, void* finalize_hint) { - NAPI_ASSERT_RETURN_VOID(env, data != NULL && strcmp(data, theText) == 0, "invalid data"); +static void deleteTheText(node_api_env env, void* data, void* finalize_hint) { + NODE_API_ASSERT_RETURN_VOID(env, data != NULL && strcmp(data, theText) == 0, + "invalid data"); (void)finalize_hint; free(data); deleterCallCount++; } -static void noopDeleter(napi_env env, void* data, void* finalize_hint) { - NAPI_ASSERT_RETURN_VOID(env, data != NULL && strcmp(data, theText) == 0, "invalid data"); +static void noopDeleter(node_api_env env, void* data, void* finalize_hint) { + NODE_API_ASSERT_RETURN_VOID(env, data != NULL && strcmp(data, theText) == 0, + "invalid data"); (void)finalize_hint; deleterCallCount++; } -static napi_value newBuffer(napi_env env, napi_callback_info info) { - napi_value theBuffer; +static node_api_value +newBuffer(node_api_env env, node_api_callback_info info) { + node_api_value theBuffer; char* theCopy; const unsigned int kBufferSize = sizeof(theText); - NAPI_CALL(env, - napi_create_buffer( + NODE_API_CALL(env, + node_api_create_buffer( env, sizeof(theText), (void**)(&theCopy), &theBuffer)); - NAPI_ASSERT(env, theCopy, "Failed to copy static text for newBuffer"); + NODE_API_ASSERT(env, theCopy, "Failed to copy static text for newBuffer"); memcpy(theCopy, theText, kBufferSize); return theBuffer; } -static napi_value newExternalBuffer(napi_env env, napi_callback_info info) { - napi_value theBuffer; +static node_api_value +newExternalBuffer(node_api_env env, node_api_callback_info info) { + node_api_value theBuffer; char* theCopy = strdup(theText); - NAPI_ASSERT(env, theCopy, "Failed to copy static text for newExternalBuffer"); - NAPI_CALL(env, - napi_create_external_buffer( - env, - sizeof(theText), - theCopy, - deleteTheText, - NULL, // finalize_hint - &theBuffer)); + NODE_API_ASSERT(env, theCopy, + "Failed to copy static text for newExternalBuffer"); + NODE_API_CALL(env, + node_api_create_external_buffer( + env, + sizeof(theText), + theCopy, + deleteTheText, + NULL, // finalize_hint + &theBuffer)); return theBuffer; } -static napi_value getDeleterCallCount(napi_env env, napi_callback_info info) { - napi_value callCount; - NAPI_CALL(env, napi_create_int32(env, deleterCallCount, &callCount)); +static node_api_value +getDeleterCallCount(node_api_env env, node_api_callback_info info) { + node_api_value callCount; + NODE_API_CALL(env, node_api_create_int32(env, deleterCallCount, &callCount)); return callCount; } -static napi_value copyBuffer(napi_env env, napi_callback_info info) { - napi_value theBuffer; - NAPI_CALL(env, napi_create_buffer_copy( +static node_api_value +copyBuffer(node_api_env env, node_api_callback_info info) { + node_api_value theBuffer; + NODE_API_CALL(env, node_api_create_buffer_copy( env, sizeof(theText), theText, NULL, &theBuffer)); return theBuffer; } -static napi_value bufferHasInstance(napi_env env, napi_callback_info info) { +static node_api_value +bufferHasInstance(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); - napi_value theBuffer = args[0]; + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments"); + node_api_value theBuffer = args[0]; bool hasInstance; - napi_valuetype theType; - NAPI_CALL(env, napi_typeof(env, theBuffer, &theType)); - NAPI_ASSERT(env, - theType == napi_object, - "bufferHasInstance: instance is not an object"); - NAPI_CALL(env, napi_is_buffer(env, theBuffer, &hasInstance)); - NAPI_ASSERT(env, hasInstance, "bufferHasInstance: instance is not a buffer"); - napi_value returnValue; - NAPI_CALL(env, napi_get_boolean(env, hasInstance, &returnValue)); + node_api_valuetype theType; + NODE_API_CALL(env, node_api_typeof(env, theBuffer, &theType)); + NODE_API_ASSERT(env, theType == node_api_object, + "bufferHasInstance: instance is not an object"); + NODE_API_CALL(env, node_api_is_buffer(env, theBuffer, &hasInstance)); + NODE_API_ASSERT(env, hasInstance, + "bufferHasInstance: instance is not a buffer"); + node_api_value returnValue; + NODE_API_CALL(env, node_api_get_boolean(env, hasInstance, &returnValue)); return returnValue; } -static napi_value bufferInfo(napi_env env, napi_callback_info info) { +static node_api_value +bufferInfo(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); - napi_value theBuffer = args[0]; + node_api_value args[1]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments"); + node_api_value theBuffer = args[0]; char *bufferData; - napi_value returnValue; + node_api_value returnValue; size_t bufferLength; - NAPI_CALL(env, - napi_get_buffer_info( - env, - theBuffer, - (void**)(&bufferData), - &bufferLength)); - NAPI_CALL(env, napi_get_boolean(env, + NODE_API_CALL(env, + node_api_get_buffer_info( + env, + theBuffer, + (void**)(&bufferData), + &bufferLength)); + NODE_API_CALL(env, node_api_get_boolean(env, !strcmp(bufferData, theText) && bufferLength == sizeof(theText), &returnValue)); return returnValue; } -static napi_value staticBuffer(napi_env env, napi_callback_info info) { - napi_value theBuffer; - NAPI_CALL( +static node_api_value +staticBuffer(node_api_env env, node_api_callback_info info) { + node_api_value theBuffer; + NODE_API_CALL( env, - napi_create_external_buffer(env, - sizeof(theText), - (void*)theText, - noopDeleter, - NULL, // finalize_hint - &theBuffer)); + node_api_create_external_buffer(env, + sizeof(theText), + (void*)theText, + noopDeleter, + NULL, // finalize_hint + &theBuffer)); return theBuffer; } -static napi_value Init(napi_env env, napi_value exports) { - napi_value theValue; - - NAPI_CALL(env, - napi_create_string_utf8(env, theText, sizeof(theText), &theValue)); - NAPI_CALL(env, napi_set_named_property(env, exports, "theText", theValue)); - - napi_property_descriptor methods[] = { - DECLARE_NAPI_PROPERTY("newBuffer", newBuffer), - DECLARE_NAPI_PROPERTY("newExternalBuffer", newExternalBuffer), - DECLARE_NAPI_PROPERTY("getDeleterCallCount", getDeleterCallCount), - DECLARE_NAPI_PROPERTY("copyBuffer", copyBuffer), - DECLARE_NAPI_PROPERTY("bufferHasInstance", bufferHasInstance), - DECLARE_NAPI_PROPERTY("bufferInfo", bufferInfo), - DECLARE_NAPI_PROPERTY("staticBuffer", staticBuffer), +static node_api_value Init(node_api_env env, node_api_value exports) { + node_api_value theValue; + + NODE_API_CALL(env, + node_api_create_string_utf8(env, theText, sizeof(theText), &theValue)); + NODE_API_CALL(env, + node_api_set_named_property(env, exports, "theText", theValue)); + + node_api_property_descriptor methods[] = { + DECLARE_NODE_API_PROPERTY("newBuffer", newBuffer), + DECLARE_NODE_API_PROPERTY("newExternalBuffer", newExternalBuffer), + DECLARE_NODE_API_PROPERTY("getDeleterCallCount", getDeleterCallCount), + DECLARE_NODE_API_PROPERTY("copyBuffer", copyBuffer), + DECLARE_NODE_API_PROPERTY("bufferHasInstance", bufferHasInstance), + DECLARE_NODE_API_PROPERTY("bufferInfo", bufferInfo), + DECLARE_NODE_API_PROPERTY("staticBuffer", staticBuffer), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(methods) / sizeof(methods[0]), methods)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_callback_scope/binding.c b/test/node-api/test_callback_scope/binding.c index d512219e7bfa58..bc525370575ffd 100644 --- a/test/node-api/test_callback_scope/binding.c +++ b/test/node-api/test_callback_scope/binding.c @@ -3,102 +3,107 @@ #include "uv.h" #include "../../js-native-api/common.h" -static napi_value RunInCallbackScope(napi_env env, napi_callback_info info) { +static node_api_value +RunInCallbackScope(node_api_env env, node_api_callback_info info) { size_t argc; - napi_value args[3]; + node_api_value args[3]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, NULL, NULL, NULL)); - NAPI_ASSERT(env, argc == 3 , "Wrong number of arguments"); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, NULL, NULL, NULL)); + NODE_API_ASSERT(env, argc == 3 , "Wrong number of arguments"); - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, + node_api_valuetype valuetype; + NODE_API_CALL(env, node_api_typeof(env, args[0], &valuetype)); + NODE_API_ASSERT(env, valuetype == node_api_object, "Wrong type of arguments. Expects an object as first argument."); - NAPI_CALL(env, napi_typeof(env, args[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, + NODE_API_CALL(env, node_api_typeof(env, args[1], &valuetype)); + NODE_API_ASSERT(env, valuetype == node_api_string, "Wrong type of arguments. Expects a string as second argument."); - NAPI_CALL(env, napi_typeof(env, args[2], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, + NODE_API_CALL(env, node_api_typeof(env, args[2], &valuetype)); + NODE_API_ASSERT(env, valuetype == node_api_function, "Wrong type of arguments. Expects a function as third argument."); - napi_async_context context; - NAPI_CALL(env, napi_async_init(env, args[0], args[1], &context)); + node_api_async_context context; + NODE_API_CALL(env, node_api_async_init(env, args[0], args[1], &context)); - napi_callback_scope scope = NULL; - NAPI_CALL( + node_api_callback_scope scope = NULL; + NODE_API_CALL( env, - napi_open_callback_scope(env, - args[0], - context, - &scope)); + node_api_open_callback_scope(env, + args[0], + context, + &scope)); // if the function has an exception pending after the call that is ok - // so we don't use NAPI_CALL as we must close the callback scope regardless - napi_value result = NULL; - napi_status function_call_result = - napi_call_function(env, args[0], args[2], 0, NULL, &result); - if (function_call_result != napi_ok) { + // so we don't use NODE_API_CALL as we must close the callback scope + // regardless + node_api_value result = NULL; + node_api_status function_call_result = + node_api_call_function(env, args[0], args[2], 0, NULL, &result); + if (function_call_result != node_api_ok) { GET_AND_THROW_LAST_ERROR((env)); } - NAPI_CALL(env, napi_close_callback_scope(env, scope)); - NAPI_CALL(env, napi_async_destroy(env, context)); + NODE_API_CALL(env, node_api_close_callback_scope(env, scope)); + NODE_API_CALL(env, node_api_async_destroy(env, context)); return result; } -static napi_env shared_env = NULL; -static napi_deferred deferred = NULL; +static node_api_env shared_env = NULL; +static node_api_deferred deferred = NULL; static void Callback(uv_work_t* req, int ignored) { - napi_env env = shared_env; + node_api_env env = shared_env; - napi_handle_scope handle_scope = NULL; - NAPI_CALL_RETURN_VOID(env, napi_open_handle_scope(env, &handle_scope)); + node_api_handle_scope handle_scope = NULL; + NODE_API_CALL_RETURN_VOID(env, + node_api_open_handle_scope(env, &handle_scope)); - napi_value resource_name; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8( - env, "test", NAPI_AUTO_LENGTH, &resource_name)); - napi_async_context context; - NAPI_CALL_RETURN_VOID(env, - napi_async_init(env, NULL, resource_name, &context)); + node_api_value resource_name; + NODE_API_CALL_RETURN_VOID(env, node_api_create_string_utf8( + env, "test", NODE_API_AUTO_LENGTH, &resource_name)); + node_api_async_context context; + NODE_API_CALL_RETURN_VOID(env, + node_api_async_init(env, NULL, resource_name, &context)); - napi_value resource_object; - NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &resource_object)); + node_api_value resource_object; + NODE_API_CALL_RETURN_VOID(env, + node_api_create_object(env, &resource_object)); - napi_value undefined_value; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined_value)); + node_api_value undefined_value; + NODE_API_CALL_RETURN_VOID(env, + node_api_get_undefined(env, &undefined_value)); - napi_callback_scope scope = NULL; - NAPI_CALL_RETURN_VOID(env, napi_open_callback_scope(env, - resource_object, - context, - &scope)); + node_api_callback_scope scope = NULL; + NODE_API_CALL_RETURN_VOID(env, + node_api_open_callback_scope(env, resource_object, context, &scope)); - NAPI_CALL_RETURN_VOID(env, - napi_resolve_deferred(env, deferred, undefined_value)); + NODE_API_CALL_RETURN_VOID(env, + node_api_resolve_deferred(env, deferred, undefined_value)); - NAPI_CALL_RETURN_VOID(env, napi_close_callback_scope(env, scope)); + NODE_API_CALL_RETURN_VOID(env, node_api_close_callback_scope(env, scope)); - NAPI_CALL_RETURN_VOID(env, napi_close_handle_scope(env, handle_scope)); - NAPI_CALL_RETURN_VOID(env, napi_async_destroy(env, context)); + NODE_API_CALL_RETURN_VOID(env, + node_api_close_handle_scope(env, handle_scope)); + NODE_API_CALL_RETURN_VOID(env, node_api_async_destroy(env, context)); free(req); } static void NoopWork(uv_work_t* work) { (void) work; } -static napi_value TestResolveAsync(napi_env env, napi_callback_info info) { - napi_value promise = NULL; +static node_api_value +TestResolveAsync(node_api_env env, node_api_callback_info info) { + node_api_value promise = NULL; if (deferred == NULL) { shared_env = env; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + NODE_API_CALL(env, node_api_create_promise(env, &deferred, &promise)); uv_loop_t* loop = NULL; - NAPI_CALL(env, napi_get_uv_event_loop(env, &loop)); + NODE_API_CALL(env, node_api_get_uv_event_loop(env, &loop)); uv_work_t* req = malloc(sizeof(*req)); uv_queue_work(loop, @@ -109,16 +114,16 @@ static napi_value TestResolveAsync(napi_env env, napi_callback_info info) { return promise; } -static napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("runInCallbackScope", RunInCallbackScope), - DECLARE_NAPI_PROPERTY("testResolveAsync", TestResolveAsync) +static node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("runInCallbackScope", RunInCallbackScope), + DECLARE_NODE_API_PROPERTY("testResolveAsync", TestResolveAsync) }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_cleanup_hook/binding.c b/test/node-api/test_cleanup_hook/binding.c index 3e0ddfe9e3c59b..6f1f752badd636 100644 --- a/test/node-api/test_cleanup_hook/binding.c +++ b/test/node-api/test_cleanup_hook/binding.c @@ -9,12 +9,12 @@ static void cleanup(void* arg) { static int secret = 42; static int wrong_secret = 17; -static napi_value Init(napi_env env, napi_value exports) { - napi_add_env_cleanup_hook(env, cleanup, &wrong_secret); - napi_add_env_cleanup_hook(env, cleanup, &secret); - napi_remove_env_cleanup_hook(env, cleanup, &wrong_secret); +static node_api_value Init(node_api_env env, node_api_value exports) { + node_api_add_env_cleanup_hook(env, cleanup, &wrong_secret); + node_api_add_env_cleanup_hook(env, cleanup, &secret); + node_api_remove_env_cleanup_hook(env, cleanup, &wrong_secret); return NULL; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_exception/test_exception.c b/test/node-api/test_exception/test_exception.c index 78744bee2cc60f..eb55c354429188 100644 --- a/test/node-api/test_exception/test_exception.c +++ b/test/node-api/test_exception/test_exception.c @@ -1,27 +1,28 @@ #include #include "../../js-native-api/common.h" -static void finalizer(napi_env env, void *data, void *hint) { - NAPI_CALL_RETURN_VOID(env, - napi_throw_error(env, NULL, "Error during Finalize")); +static void finalizer(node_api_env env, void *data, void *hint) { + NODE_API_CALL_RETURN_VOID(env, + node_api_throw_error(env, NULL, "Error during Finalize")); } static char buffer_data[12]; -static napi_value createExternalBuffer(napi_env env, napi_callback_info info) { - napi_value buffer; - NAPI_CALL(env, napi_create_external_buffer(env, sizeof(buffer_data), +static node_api_value +createExternalBuffer(node_api_env env, node_api_callback_info info) { + node_api_value buffer; + NODE_API_CALL(env, node_api_create_external_buffer(env, sizeof(buffer_data), buffer_data, finalizer, NULL, &buffer)); return buffer; } -static napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("createExternalBuffer", createExternalBuffer), +static node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("createExternalBuffer", createExternalBuffer), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_fatal/test_fatal.c b/test/node-api/test_fatal/test_fatal.c index 70bb458ef20e4e..cab0ad06aeac8e 100644 --- a/test/node-api/test_fatal/test_fatal.c +++ b/test/node-api/test_fatal/test_fatal.c @@ -1,27 +1,29 @@ #include #include "../../js-native-api/common.h" -static napi_value Test(napi_env env, napi_callback_info info) { - napi_fatal_error("test_fatal::Test", NAPI_AUTO_LENGTH, - "fatal message", NAPI_AUTO_LENGTH); +static node_api_value Test(node_api_env env, node_api_callback_info info) { + node_api_fatal_error("test_fatal::Test", NODE_API_AUTO_LENGTH, + "fatal message", NODE_API_AUTO_LENGTH); return NULL; } -static napi_value TestStringLength(napi_env env, napi_callback_info info) { - napi_fatal_error("test_fatal::TestStringLength", 16, "fatal message", 13); +static node_api_value +TestStringLength(node_api_env env, node_api_callback_info info) { + node_api_fatal_error( + "test_fatal::TestStringLength", 16, "fatal message", 13); return NULL; } -static napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("Test", Test), - DECLARE_NAPI_PROPERTY("TestStringLength", TestStringLength), +static node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor properties[] = { + DECLARE_NODE_API_PROPERTY("Test", Test), + DECLARE_NODE_API_PROPERTY("TestStringLength", TestStringLength), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_fatal_exception/test_fatal_exception.c b/test/node-api/test_fatal_exception/test_fatal_exception.c index 0e14b9b435871a..ca396b70deaa10 100644 --- a/test/node-api/test_fatal_exception/test_fatal_exception.c +++ b/test/node-api/test_fatal_exception/test_fatal_exception.c @@ -1,26 +1,26 @@ #include #include "../../js-native-api/common.h" -static napi_value Test(napi_env env, napi_callback_info info) { - napi_value err; +static node_api_value Test(node_api_env env, node_api_callback_info info) { + node_api_value err; size_t argc = 1; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &err, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, &err, NULL, NULL)); - NAPI_CALL(env, napi_fatal_exception(env, err)); + NODE_API_CALL(env, node_api_fatal_exception(env, err)); return NULL; } -static napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("Test", Test), +static node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor properties[] = { + DECLARE_NODE_API_PROPERTY("Test", Test), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_general/test_general.c b/test/node-api/test_general/test_general.c index be805f782be8d5..754458ed1499da 100644 --- a/test/node-api/test_general/test_general.c +++ b/test/node-api/test_general/test_general.c @@ -2,34 +2,35 @@ #include #include "../../js-native-api/common.h" -static napi_value testGetNodeVersion(napi_env env, napi_callback_info info) { - const napi_node_version* node_version; - napi_value result, major, minor, patch, release; - NAPI_CALL(env, napi_get_node_version(env, &node_version)); - NAPI_CALL(env, napi_create_uint32(env, node_version->major, &major)); - NAPI_CALL(env, napi_create_uint32(env, node_version->minor, &minor)); - NAPI_CALL(env, napi_create_uint32(env, node_version->patch, &patch)); - NAPI_CALL(env, napi_create_string_utf8(env, - node_version->release, - NAPI_AUTO_LENGTH, - &release)); - NAPI_CALL(env, napi_create_array_with_length(env, 4, &result)); - NAPI_CALL(env, napi_set_element(env, result, 0, major)); - NAPI_CALL(env, napi_set_element(env, result, 1, minor)); - NAPI_CALL(env, napi_set_element(env, result, 2, patch)); - NAPI_CALL(env, napi_set_element(env, result, 3, release)); +static node_api_value +testGetNodeVersion(node_api_env env, node_api_callback_info info) { + const node_api_node_version* node_version; + node_api_value result, major, minor, patch, release; + NODE_API_CALL(env, node_api_get_node_version(env, &node_version)); + NODE_API_CALL(env, node_api_create_uint32(env, node_version->major, &major)); + NODE_API_CALL(env, node_api_create_uint32(env, node_version->minor, &minor)); + NODE_API_CALL(env, node_api_create_uint32(env, node_version->patch, &patch)); + NODE_API_CALL(env, node_api_create_string_utf8(env, + node_version->release, + NODE_API_AUTO_LENGTH, + &release)); + NODE_API_CALL(env, node_api_create_array_with_length(env, 4, &result)); + NODE_API_CALL(env, node_api_set_element(env, result, 0, major)); + NODE_API_CALL(env, node_api_set_element(env, result, 1, minor)); + NODE_API_CALL(env, node_api_set_element(env, result, 2, patch)); + NODE_API_CALL(env, node_api_set_element(env, result, 3, release)); return result; } -static napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("testGetNodeVersion", testGetNodeVersion), +static node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor descriptors[] = { + DECLARE_NODE_API_PROPERTY("testGetNodeVersion", testGetNodeVersion), }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_instance_data/addon.c b/test/node-api/test_instance_data/addon.c index 7cf27bf28ab7eb..d65f0870771e24 100644 --- a/test/node-api/test_instance_data/addon.c +++ b/test/node-api/test_instance_data/addon.c @@ -2,21 +2,21 @@ #include #include -static void addon_free(napi_env env, void* data, void* hint) { - napi_ref* ref = data; - napi_delete_reference(env, *ref); +static void addon_free(node_api_env env, void* data, void* hint) { + node_api_ref* ref = data; + node_api_delete_reference(env, *ref); free(ref); fprintf(stderr, "addon_free"); } -napi_value addon_new(napi_env env, napi_value exports, bool ref_first) { - napi_ref* ref = malloc(sizeof(*ref)); +node_api_value addon_new(node_api_env env, node_api_value exports, bool ref_first) { + node_api_ref* ref = malloc(sizeof(*ref)); if (ref_first) { - napi_create_reference(env, exports, 1, ref); - napi_set_instance_data(env, ref, addon_free, NULL); + node_api_create_reference(env, exports, 1, ref); + node_api_set_instance_data(env, ref, addon_free, NULL); } else { - napi_set_instance_data(env, ref, addon_free, NULL); - napi_create_reference(env, exports, 1, ref); + node_api_set_instance_data(env, ref, addon_free, NULL); + node_api_create_reference(env, exports, 1, ref); } return exports; } diff --git a/test/node-api/test_instance_data/test_instance_data.c b/test/node-api/test_instance_data/test_instance_data.c index 24fd502e836176..404a5490f9f3e5 100644 --- a/test/node-api/test_instance_data/test_instance_data.c +++ b/test/node-api/test_instance_data/test_instance_data.c @@ -4,112 +4,115 @@ #include "../../js-native-api/common.h" typedef struct { - napi_ref js_cb_ref; - napi_ref js_tsfn_finalizer_ref; - napi_threadsafe_function tsfn; + node_api_ref js_cb_ref; + node_api_ref js_tsfn_finalizer_ref; + node_api_threadsafe_function tsfn; uv_thread_t thread; } AddonData; -static void AsyncWorkCbExecute(napi_env env, void* data) { +static void AsyncWorkCbExecute(node_api_env env, void* data) { (void) env; (void) data; } -static void call_cb_and_delete_ref(napi_env env, napi_ref* optional_ref) { - napi_value js_cb, undefined; +static void +call_cb_and_delete_ref(node_api_env env, node_api_ref* optional_ref) { + node_api_value js_cb, undefined; if (optional_ref == NULL) { AddonData* data; - NAPI_CALL_RETURN_VOID(env, napi_get_instance_data(env, (void**)&data)); + NODE_API_CALL_RETURN_VOID(env, + node_api_get_instance_data(env, (void**)&data)); optional_ref = &data->js_cb_ref; } - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, - *optional_ref, - &js_cb)); - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, - undefined, - js_cb, - 0, - NULL, - NULL)); - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, *optional_ref)); + NODE_API_CALL_RETURN_VOID(env, + node_api_get_reference_value(env, *optional_ref, &js_cb)); + NODE_API_CALL_RETURN_VOID(env, node_api_get_undefined(env, &undefined)); + NODE_API_CALL_RETURN_VOID(env, + node_api_call_function(env, undefined, js_cb, 0, NULL, NULL)); + NODE_API_CALL_RETURN_VOID(env, + node_api_delete_reference(env, *optional_ref)); *optional_ref = NULL; } -static void AsyncWorkCbComplete(napi_env env, - napi_status status, - void* data) { +static void +AsyncWorkCbComplete(node_api_env env, node_api_status status, void* data) { (void) status; (void) data; call_cb_and_delete_ref(env, NULL); } -static bool establish_callback_ref(napi_env env, napi_callback_info info) { +static bool +establish_callback_ref(node_api_env env, node_api_callback_info info) { AddonData* data; size_t argc = 1; - napi_value js_cb; - - NAPI_CALL_BASE(env, napi_get_instance_data(env, (void**)&data), false); - NAPI_ASSERT_BASE(env, - data->js_cb_ref == NULL, - "reference must be NULL", - false); - NAPI_CALL_BASE(env, - napi_get_cb_info(env, info, &argc, &js_cb, NULL, NULL), - false); - NAPI_CALL_BASE(env, - napi_create_reference(env, js_cb, 1, &data->js_cb_ref), - false); + node_api_value js_cb; + + NODE_API_CALL_BASE(env, + node_api_get_instance_data(env, (void**)&data), false); + NODE_API_ASSERT_BASE(env, + data->js_cb_ref == NULL, + "reference must be NULL", + false); + NODE_API_CALL_BASE(env, + node_api_get_cb_info(env, info, &argc, &js_cb, NULL, NULL), + false); + NODE_API_CALL_BASE(env, + node_api_create_reference(env, js_cb, 1, &data->js_cb_ref), + false); return true; } -static napi_value AsyncWorkCallback(napi_env env, napi_callback_info info) { +static node_api_value +AsyncWorkCallback(node_api_env env, node_api_callback_info info) { if (establish_callback_ref(env, info)) { - napi_value resource_name; - napi_async_work work; - - NAPI_CALL(env, napi_create_string_utf8(env, - "AsyncIncrement", - NAPI_AUTO_LENGTH, - &resource_name)); - NAPI_CALL(env, napi_create_async_work(env, - NULL, - resource_name, - AsyncWorkCbExecute, - AsyncWorkCbComplete, - NULL, - &work)); - NAPI_CALL(env, napi_queue_async_work(env, work)); + node_api_value resource_name; + node_api_async_work work; + + NODE_API_CALL(env, node_api_create_string_utf8(env, + "AsyncIncrement", + NODE_API_AUTO_LENGTH, + &resource_name)); + NODE_API_CALL(env, node_api_create_async_work(env, + NULL, + resource_name, + AsyncWorkCbExecute, + AsyncWorkCbComplete, + NULL, + &work)); + NODE_API_CALL(env, node_api_queue_async_work(env, work)); } return NULL; } -static void TestBufferFinalizerCallback(napi_env env, void* data, void* hint) { +static void +TestBufferFinalizerCallback(node_api_env env, void* data, void* hint) { (void) data; (void) hint; call_cb_and_delete_ref(env, NULL); } -static napi_value TestBufferFinalizer(napi_env env, napi_callback_info info) { - napi_value buffer = NULL; +static node_api_value +TestBufferFinalizer(node_api_env env, node_api_callback_info info) { + node_api_value buffer = NULL; if (establish_callback_ref(env, info)) { - NAPI_CALL(env, napi_create_external_buffer(env, - sizeof(napi_callback), - TestBufferFinalizer, - TestBufferFinalizerCallback, - NULL, - &buffer)); + NODE_API_CALL(env, + node_api_create_external_buffer(env, + sizeof(node_api_callback), + TestBufferFinalizer, + TestBufferFinalizerCallback, + NULL, + &buffer)); } return buffer; } -static void ThreadsafeFunctionCallJS(napi_env env, - napi_value tsfn_cb, +static void ThreadsafeFunctionCallJS(node_api_env env, + node_api_value tsfn_cb, void* context, void* data) { (void) tsfn_cb; @@ -120,76 +123,78 @@ static void ThreadsafeFunctionCallJS(napi_env env, static void ThreadsafeFunctionTestThread(void* raw_data) { AddonData* data = raw_data; - napi_status status; + node_api_status status; - // No need to call `napi_acquire_threadsafe_function()` because the main + // No need to call `node_api_acquire_threadsafe_function()` because the main // thread has set the refcount to 1 and there is only this one secondary // thread. - status = napi_call_threadsafe_function(data->tsfn, - ThreadsafeFunctionCallJS, - napi_tsfn_nonblocking); - if (status != napi_ok) { - napi_fatal_error("ThreadSafeFunctionTestThread", - NAPI_AUTO_LENGTH, - "Failed to call TSFN", - NAPI_AUTO_LENGTH); + status = node_api_call_threadsafe_function(data->tsfn, + ThreadsafeFunctionCallJS, + node_api_tsfn_nonblocking); + if (status != node_api_ok) { + node_api_fatal_error("ThreadSafeFunctionTestThread", + NODE_API_AUTO_LENGTH, + "Failed to call TSFN", + NODE_API_AUTO_LENGTH); } - status = napi_release_threadsafe_function(data->tsfn, napi_tsfn_release); - if (status != napi_ok) { - napi_fatal_error("ThreadSafeFunctionTestThread", - NAPI_AUTO_LENGTH, - "Failed to release TSFN", - NAPI_AUTO_LENGTH); + status = node_api_release_threadsafe_function(data->tsfn, node_api_tsfn_release); + if (status != node_api_ok) { + node_api_fatal_error("ThreadSafeFunctionTestThread", + NODE_API_AUTO_LENGTH, + "Failed to release TSFN", + NODE_API_AUTO_LENGTH); } } -static void FinalizeThreadsafeFunction(napi_env env, void* raw, void* hint) { +static void FinalizeThreadsafeFunction(node_api_env env, void* raw, void* hint) { AddonData* data; - NAPI_CALL_RETURN_VOID(env, napi_get_instance_data(env, (void**)&data)); - NAPI_ASSERT_RETURN_VOID(env, - uv_thread_join(&data->thread) == 0, - "Failed to join the thread"); + NODE_API_CALL_RETURN_VOID(env, node_api_get_instance_data(env, (void**)&data)); + NODE_API_ASSERT_RETURN_VOID(env, + uv_thread_join(&data->thread) == 0, + "Failed to join the thread"); call_cb_and_delete_ref(env, &data->js_tsfn_finalizer_ref); data->tsfn = NULL; } // Ths function accepts two arguments: the JS callback, and the finalize // callback. The latter moves the test forward. -static napi_value -TestThreadsafeFunction(napi_env env, napi_callback_info info) { +static node_api_value +TestThreadsafeFunction(node_api_env env, node_api_callback_info info) { AddonData* data; size_t argc = 2; - napi_value argv[2], resource_name; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_CALL(env, napi_get_instance_data(env, (void**)&data)); - NAPI_ASSERT(env, data->js_cb_ref == NULL, "reference must be NULL"); - NAPI_ASSERT(env, - data->js_tsfn_finalizer_ref == NULL, - "tsfn finalizer reference must be NULL"); - NAPI_CALL(env, napi_create_reference(env, argv[0], 1, &data->js_cb_ref)); - NAPI_CALL(env, napi_create_reference(env, - argv[1], - 1, - &data->js_tsfn_finalizer_ref)); - NAPI_CALL(env, napi_create_string_utf8(env, - "TSFN instance data test", - NAPI_AUTO_LENGTH, - &resource_name)); - NAPI_CALL(env, napi_create_threadsafe_function(env, - NULL, - NULL, - resource_name, - 0, - 1, - NULL, - FinalizeThreadsafeFunction, - NULL, - ThreadsafeFunctionCallJS, - &data->tsfn)); - NAPI_ASSERT(env, + node_api_value argv[2], resource_name; + + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NODE_API_CALL(env, node_api_get_instance_data(env, (void**)&data)); + NODE_API_ASSERT(env, data->js_cb_ref == NULL, "reference must be NULL"); + NODE_API_ASSERT(env, + data->js_tsfn_finalizer_ref == NULL, + "tsfn finalizer reference must be NULL"); + NODE_API_CALL(env, + node_api_create_reference(env, argv[0], 1, &data->js_cb_ref)); + NODE_API_CALL(env, node_api_create_reference(env, + argv[1], + 1, + &data->js_tsfn_finalizer_ref)); + NODE_API_CALL(env, node_api_create_string_utf8(env, + "TSFN instance data test", + NODE_API_AUTO_LENGTH, + &resource_name)); + NODE_API_CALL(env, + node_api_create_threadsafe_function(env, + NULL, + NULL, + resource_name, + 0, + 1, + NULL, + FinalizeThreadsafeFunction, + NULL, + ThreadsafeFunctionCallJS, + &data->tsfn)); + NODE_API_ASSERT(env, uv_thread_create(&data->thread, ThreadsafeFunctionTestThread, data) == 0, @@ -198,38 +203,41 @@ TestThreadsafeFunction(napi_env env, napi_callback_info info) { return NULL; } -static void DeleteAddonData(napi_env env, void* raw_data, void* hint) { +static void DeleteAddonData(node_api_env env, void* raw_data, void* hint) { AddonData* data = raw_data; if (data->js_cb_ref) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, data->js_cb_ref)); + NODE_API_CALL_RETURN_VOID(env, + node_api_delete_reference(env, data->js_cb_ref)); } if (data->js_tsfn_finalizer_ref) { - NAPI_CALL_RETURN_VOID(env, - napi_delete_reference(env, - data->js_tsfn_finalizer_ref)); + NODE_API_CALL_RETURN_VOID(env, + node_api_delete_reference(env, + data->js_tsfn_finalizer_ref)); } free(data); } -static napi_value Init(napi_env env, napi_value exports) { +static node_api_value Init(node_api_env env, node_api_value exports) { AddonData* data = malloc(sizeof(*data)); data->js_cb_ref = NULL; data->js_tsfn_finalizer_ref = NULL; - NAPI_CALL(env, napi_set_instance_data(env, data, DeleteAddonData, NULL)); + NODE_API_CALL(env, + node_api_set_instance_data(env, data, DeleteAddonData, NULL)); - napi_property_descriptor props[] = { - DECLARE_NAPI_PROPERTY("asyncWorkCallback", AsyncWorkCallback), - DECLARE_NAPI_PROPERTY("testBufferFinalizer", TestBufferFinalizer), - DECLARE_NAPI_PROPERTY("testThreadsafeFunction", TestThreadsafeFunction), + node_api_property_descriptor props[] = { + DECLARE_NODE_API_PROPERTY("asyncWorkCallback", AsyncWorkCallback), + DECLARE_NODE_API_PROPERTY("testBufferFinalizer", TestBufferFinalizer), + DECLARE_NODE_API_PROPERTY("testThreadsafeFunction", + TestThreadsafeFunction), }; - NAPI_CALL(env, napi_define_properties(env, - exports, - sizeof(props) / sizeof(*props), - props)); + NODE_API_CALL(env, node_api_define_properties(env, + exports, + sizeof(props) / sizeof(*props), + props)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_instance_data/test_ref_then_set.c b/test/node-api/test_instance_data/test_ref_then_set.c index 10c779d3241e0e..76f04d4c1ccd66 100644 --- a/test/node-api/test_instance_data/test_ref_then_set.c +++ b/test/node-api/test_instance_data/test_ref_then_set.c @@ -2,9 +2,10 @@ #include #include -napi_value addon_new(napi_env env, napi_value exports, bool ref_first); +node_api_value +addon_new(node_api_env env, node_api_value exports, bool ref_first); -// static napi_value -NAPI_MODULE_INIT(/*napi_env env, napi_value exports */) { +// static node_api_value +NODE_API_MODULE_INIT(/*node_api_env env, node_api_value exports */) { return addon_new(env, exports, true); } diff --git a/test/node-api/test_instance_data/test_set_then_ref.c b/test/node-api/test_instance_data/test_set_then_ref.c index 9a1b31aeed390b..4e9b149cae3eb9 100644 --- a/test/node-api/test_instance_data/test_set_then_ref.c +++ b/test/node-api/test_instance_data/test_set_then_ref.c @@ -2,9 +2,10 @@ #include #include -napi_value addon_new(napi_env env, napi_value exports, bool ref_first); +node_api_value +addon_new(node_api_env env, node_api_value exports, bool ref_first); -// static napi_value -NAPI_MODULE_INIT(/*napi_env env, napi_value exports */) { +// static node_api_value +NODE_API_MODULE_INIT(/*node_api_env env, node_api_value exports */) { return addon_new(env, exports, false); } diff --git a/test/node-api/test_make_callback/binding.c b/test/node-api/test_make_callback/binding.c index 214e0a4e182385..535e943fd7dcdd 100644 --- a/test/node-api/test_make_callback/binding.c +++ b/test/node-api/test_make_callback/binding.c @@ -5,56 +5,59 @@ #define MAX_ARGUMENTS 10 #define RESERVED_ARGS 3 -static napi_value MakeCallback(napi_env env, napi_callback_info info) { +static node_api_value +MakeCallback(node_api_env env, node_api_callback_info info) { size_t argc = MAX_ARGUMENTS; size_t n; - napi_value args[MAX_ARGUMENTS]; + node_api_value args[MAX_ARGUMENTS]; // NOLINTNEXTLINE (readability/null_usage) - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); + NODE_API_ASSERT(env, argc > 0, "Wrong number of arguments"); - napi_value resource = args[0]; - napi_value recv = args[1]; - napi_value func = args[2]; + node_api_value resource = args[0]; + node_api_value recv = args[1]; + node_api_value func = args[2]; - napi_value argv[MAX_ARGUMENTS - RESERVED_ARGS]; + node_api_value argv[MAX_ARGUMENTS - RESERVED_ARGS]; for (n = RESERVED_ARGS; n < argc; n += 1) { argv[n - RESERVED_ARGS] = args[n]; } - napi_valuetype func_type; + node_api_valuetype func_type; - NAPI_CALL(env, napi_typeof(env, func, &func_type)); + NODE_API_CALL(env, node_api_typeof(env, func, &func_type)); - napi_value resource_name; - NAPI_CALL(env, napi_create_string_utf8( - env, "test", NAPI_AUTO_LENGTH, &resource_name)); + node_api_value resource_name; + NODE_API_CALL(env, node_api_create_string_utf8( + env, "test", NODE_API_AUTO_LENGTH, &resource_name)); - napi_async_context context; - NAPI_CALL(env, napi_async_init(env, resource, resource_name, &context)); + node_api_async_context context; + NODE_API_CALL(env, + node_api_async_init(env, resource, resource_name, &context)); - napi_value result; - if (func_type == napi_function) { - NAPI_CALL(env, napi_make_callback( + node_api_value result; + if (func_type == node_api_function) { + NODE_API_CALL(env, node_api_make_callback( env, context, recv, func, argc - RESERVED_ARGS, argv, &result)); } else { - NAPI_ASSERT(env, false, "Unexpected argument type"); + NODE_API_ASSERT(env, false, "Unexpected argument type"); } - NAPI_CALL(env, napi_async_destroy(env, context)); + NODE_API_CALL(env, node_api_async_destroy(env, context)); return result; } static -napi_value Init(napi_env env, napi_value exports) { - napi_value fn; - NAPI_CALL(env, napi_create_function( +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_value fn; + NODE_API_CALL(env, node_api_create_function( // NOLINTNEXTLINE (readability/null_usage) - env, NULL, NAPI_AUTO_LENGTH, MakeCallback, NULL, &fn)); - NAPI_CALL(env, napi_set_named_property(env, exports, "makeCallback", fn)); + env, NULL, NODE_API_AUTO_LENGTH, MakeCallback, NULL, &fn)); + NODE_API_CALL(env, + node_api_set_named_property(env, exports, "makeCallback", fn)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_make_callback/test.js b/test/node-api/test_make_callback/test.js index d0b4b22500c9f6..de431216b009d9 100644 --- a/test/node-api/test_make_callback/test.js +++ b/test/node-api/test_make_callback/test.js @@ -34,7 +34,7 @@ assert.strictEqual(makeCallback(resource, process, common.mustCall(function(x) { assert.strictEqual(makeCallback(resource, this, common.mustCall(myMultiArgFunc), 1, 2, 3), 42); -// TODO(node-api): napi_make_callback needs to support +// TODO(node-api): node_api_make_callback needs to support // strings passed for the func argument // // const recv = { diff --git a/test/node-api/test_make_callback_recurse/binding.c b/test/node-api/test_make_callback_recurse/binding.c index 78f27e370babde..f0ec3fd61e32b5 100644 --- a/test/node-api/test_make_callback_recurse/binding.c +++ b/test/node-api/test_make_callback_recurse/binding.c @@ -1,27 +1,29 @@ #include #include "../../js-native-api/common.h" -static napi_value MakeCallback(napi_env env, napi_callback_info info) { +static node_api_value +MakeCallback(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value args[2]; + node_api_value args[2]; // NOLINTNEXTLINE (readability/null_usage) - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, args, NULL, NULL)); - napi_value recv = args[0]; - napi_value func = args[1]; + node_api_value recv = args[0]; + node_api_value func = args[1]; - napi_status status = napi_make_callback(env, NULL /* async_context */, - recv, func, 0 /* argc */, NULL /* argv */, NULL /* result */); + node_api_status status = + node_api_make_callback(env, NULL /* async_context */, recv, func, + 0 /* argc */, NULL /* argv */, NULL /* result */); bool isExceptionPending; - NAPI_CALL(env, napi_is_exception_pending(env, &isExceptionPending)); - if (isExceptionPending && !(status == napi_pending_exception)) { + NODE_API_CALL(env, node_api_is_exception_pending(env, &isExceptionPending)); + if (isExceptionPending && !(status == node_api_pending_exception)) { // if there is an exception pending we don't expect any // other error - napi_value pending_error; - status = napi_get_and_clear_last_exception(env, &pending_error); - NAPI_CALL(env, - napi_throw_error((env), + node_api_value pending_error; + status = node_api_get_and_clear_last_exception(env, &pending_error); + NODE_API_CALL(env, + node_api_throw_error((env), NULL, "error when only pending exception expected")); } @@ -29,13 +31,14 @@ static napi_value MakeCallback(napi_env env, napi_callback_info info) { return recv; } -static napi_value Init(napi_env env, napi_value exports) { - napi_value fn; - NAPI_CALL(env, napi_create_function( +static node_api_value Init(node_api_env env, node_api_value exports) { + node_api_value fn; + NODE_API_CALL(env, node_api_create_function( // NOLINTNEXTLINE (readability/null_usage) - env, NULL, NAPI_AUTO_LENGTH, MakeCallback, NULL, &fn)); - NAPI_CALL(env, napi_set_named_property(env, exports, "makeCallback", fn)); + env, NULL, NODE_API_AUTO_LENGTH, MakeCallback, NULL, &fn)); + NODE_API_CALL(env, + node_api_set_named_property(env, exports, "makeCallback", fn)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_null_init/test_null_init.c b/test/node-api/test_null_init/test_null_init.c index d9d2200488ce41..014f910f35a7d5 100644 --- a/test/node-api/test_null_init/test_null_init.c +++ b/test/node-api/test_null_init/test_null_init.c @@ -1,3 +1,3 @@ #include -NAPI_MODULE(NODE_GYP_MODULE_NAME, NULL) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, NULL) diff --git a/test/node-api/test_policy/binding.c b/test/node-api/test_policy/binding.c index b896da2cba4d84..4953009f86863c 100644 --- a/test/node-api/test_policy/binding.c +++ b/test/node-api/test_policy/binding.c @@ -2,16 +2,17 @@ #include "../../js-native-api/common.h" #include -static napi_value Method(napi_env env, napi_callback_info info) { - napi_value world; +static node_api_value Method(node_api_env env, node_api_callback_info info) { + node_api_value world; const char* str = "world"; size_t str_len = strlen(str); - NAPI_CALL(env, napi_create_string_utf8(env, str, str_len, &world)); + NODE_API_CALL(env, node_api_create_string_utf8(env, str, str_len, &world)); return world; } -NAPI_MODULE_INIT() { - napi_property_descriptor desc = DECLARE_NAPI_PROPERTY("hello", Method); - NAPI_CALL(env, napi_define_properties(env, exports, 1, &desc)); +NODE_API_MODULE_INIT() { + node_api_property_descriptor desc = + DECLARE_NODE_API_PROPERTY("hello", Method); + NODE_API_CALL(env, node_api_define_properties(env, exports, 1, &desc)); return exports; } diff --git a/test/node-api/test_threadsafe_function/binding.c b/test/node-api/test_threadsafe_function/binding.c index c9c526153804c6..a9c3ad4a6c889f 100644 --- a/test/node-api/test_threadsafe_function/binding.c +++ b/test/node-api/test_threadsafe_function/binding.c @@ -11,13 +11,13 @@ #define MAX_QUEUE_SIZE 2 static uv_thread_t uv_threads[2]; -static napi_threadsafe_function ts_fn; +static node_api_threadsafe_function ts_fn; typedef struct { - napi_threadsafe_function_call_mode block_on_full; - napi_threadsafe_function_release_mode abort; + node_api_threadsafe_function_call_mode block_on_full; + node_api_threadsafe_function_release_mode abort; bool start_secondary; - napi_ref js_finalize_cb; + node_api_ref js_finalize_cb; uint32_t max_queue_size; } ts_fn_hint; @@ -27,257 +27,274 @@ static ts_fn_hint ts_info; static int ints[ARRAY_LENGTH]; static void secondary_thread(void* data) { - napi_threadsafe_function ts_fn = data; + node_api_threadsafe_function ts_fn = data; + node_api_status status = + node_api_release_threadsafe_function(ts_fn, node_api_tsfn_release); - if (napi_release_threadsafe_function(ts_fn, napi_tsfn_release) != napi_ok) { - napi_fatal_error("secondary_thread", NAPI_AUTO_LENGTH, - "napi_release_threadsafe_function failed", NAPI_AUTO_LENGTH); + if (status != node_api_ok) { + node_api_fatal_error("secondary_thread", NODE_API_AUTO_LENGTH, + "node_api_release_threadsafe_function failed", NODE_API_AUTO_LENGTH); } } // Source thread producing the data static void data_source_thread(void* data) { - napi_threadsafe_function ts_fn = data; + node_api_threadsafe_function ts_fn = data; int index; void* hint; ts_fn_hint *ts_fn_info; - napi_status status; + node_api_status status; bool queue_was_full = false; bool queue_was_closing = false; - if (napi_get_threadsafe_function_context(ts_fn, &hint) != napi_ok) { - napi_fatal_error("data_source_thread", NAPI_AUTO_LENGTH, - "napi_get_threadsafe_function_context failed", NAPI_AUTO_LENGTH); + if (node_api_get_threadsafe_function_context(ts_fn, &hint) != node_api_ok) { + node_api_fatal_error("data_source_thread", NODE_API_AUTO_LENGTH, + "node_api_get_threadsafe_function_context failed", + NODE_API_AUTO_LENGTH); } ts_fn_info = (ts_fn_hint *)hint; if (ts_fn_info != &ts_info) { - napi_fatal_error("data_source_thread", NAPI_AUTO_LENGTH, - "thread-safe function hint is not as expected", NAPI_AUTO_LENGTH); + node_api_fatal_error("data_source_thread", NODE_API_AUTO_LENGTH, + "thread-safe function hint is not as expected", NODE_API_AUTO_LENGTH); } if (ts_fn_info->start_secondary) { - if (napi_acquire_threadsafe_function(ts_fn) != napi_ok) { - napi_fatal_error("data_source_thread", NAPI_AUTO_LENGTH, - "napi_acquire_threadsafe_function failed", NAPI_AUTO_LENGTH); + if (node_api_acquire_threadsafe_function(ts_fn) != node_api_ok) { + node_api_fatal_error("data_source_thread", NODE_API_AUTO_LENGTH, + "node_api_acquire_threadsafe_function failed", NODE_API_AUTO_LENGTH); } if (uv_thread_create(&uv_threads[1], secondary_thread, ts_fn) != 0) { - napi_fatal_error("data_source_thread", NAPI_AUTO_LENGTH, - "failed to start secondary thread", NAPI_AUTO_LENGTH); + node_api_fatal_error("data_source_thread", NODE_API_AUTO_LENGTH, + "failed to start secondary thread", NODE_API_AUTO_LENGTH); } } for (index = ARRAY_LENGTH - 1; index > -1 && !queue_was_closing; index--) { - status = napi_call_threadsafe_function(ts_fn, &ints[index], + status = node_api_call_threadsafe_function(ts_fn, &ints[index], ts_fn_info->block_on_full); if (ts_fn_info->max_queue_size == 0) { - // Let's make this thread really busy for 200 ms to give the main thread a - // chance to abort. + // Let's make this thread really busy for 200 ms to give the main thread + // a chance to abort. uint64_t start = uv_hrtime(); for (; uv_hrtime() - start < 200000000;); } switch (status) { - case napi_queue_full: + case node_api_queue_full: queue_was_full = true; index++; // fall through - case napi_ok: + case node_api_ok: continue; - case napi_closing: + case node_api_closing: queue_was_closing = true; break; default: - napi_fatal_error("data_source_thread", NAPI_AUTO_LENGTH, - "napi_call_threadsafe_function failed", NAPI_AUTO_LENGTH); + node_api_fatal_error("data_source_thread", NODE_API_AUTO_LENGTH, + "node_api_call_threadsafe_function failed", NODE_API_AUTO_LENGTH); } } // Assert that the enqueuing of a value was refused at least once, if this is // a non-blocking test run. if (!ts_fn_info->block_on_full && !queue_was_full) { - napi_fatal_error("data_source_thread", NAPI_AUTO_LENGTH, - "queue was never full", NAPI_AUTO_LENGTH); + node_api_fatal_error("data_source_thread", NODE_API_AUTO_LENGTH, + "queue was never full", NODE_API_AUTO_LENGTH); } // Assert that the queue was marked as closing at least once, if this is an // aborting test run. - if (ts_fn_info->abort == napi_tsfn_abort && !queue_was_closing) { - napi_fatal_error("data_source_thread", NAPI_AUTO_LENGTH, - "queue was never closing", NAPI_AUTO_LENGTH); + if (ts_fn_info->abort == node_api_tsfn_abort && !queue_was_closing) { + node_api_fatal_error("data_source_thread", NODE_API_AUTO_LENGTH, + "queue was never closing", NODE_API_AUTO_LENGTH); } if (!queue_was_closing && - napi_release_threadsafe_function(ts_fn, napi_tsfn_release) != napi_ok) { - napi_fatal_error("data_source_thread", NAPI_AUTO_LENGTH, - "napi_release_threadsafe_function failed", NAPI_AUTO_LENGTH); + node_api_release_threadsafe_function(ts_fn, node_api_tsfn_release) + != node_api_ok) { + node_api_fatal_error("data_source_thread", NODE_API_AUTO_LENGTH, + "node_api_release_threadsafe_function failed", NODE_API_AUTO_LENGTH); } } // Getting the data into JS -static void call_js(napi_env env, napi_value cb, void* hint, void* data) { +static void +call_js(node_api_env env, node_api_value cb, void* hint, void* data) { if (!(env == NULL || cb == NULL)) { - napi_value argv, undefined; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, *(int*)data, &argv)); - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, cb, 1, &argv, - NULL)); + node_api_value argv, undefined; + NODE_API_CALL_RETURN_VOID(env, + node_api_create_int32(env, *(int*)data, &argv)); + NODE_API_CALL_RETURN_VOID(env, node_api_get_undefined(env, &undefined)); + NODE_API_CALL_RETURN_VOID(env, + node_api_call_function(env, undefined, cb, 1, &argv, NULL)); } } -static napi_ref alt_ref; +static node_api_ref alt_ref; // Getting the data into JS with the alternative referece -static void call_ref(napi_env env, napi_value _, void* hint, void* data) { +static void +call_ref(node_api_env env, node_api_value _, void* hint, void* data) { if (!(env == NULL || alt_ref == NULL)) { - napi_value fn, argv, undefined; - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, alt_ref, &fn)); - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, *(int*)data, &argv)); - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, fn, 1, &argv, - NULL)); + node_api_value fn, argv, undefined; + NODE_API_CALL_RETURN_VOID(env, + node_api_get_reference_value(env, alt_ref, &fn)); + NODE_API_CALL_RETURN_VOID(env, + node_api_create_int32(env, *(int*)data, &argv)); + NODE_API_CALL_RETURN_VOID(env, node_api_get_undefined(env, &undefined)); + NODE_API_CALL_RETURN_VOID(env, + node_api_call_function(env, undefined, fn, 1, &argv, NULL)); } } // Cleanup -static napi_value StopThread(napi_env env, napi_callback_info info) { +static node_api_value +StopThread(node_api_env env, node_api_callback_info info) { size_t argc = 2; - napi_value argv[2]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - napi_valuetype value_type; - NAPI_CALL(env, napi_typeof(env, argv[0], &value_type)); - NAPI_ASSERT(env, value_type == napi_function, + node_api_value argv[2]; + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, argv, NULL, NULL)); + node_api_valuetype value_type; + NODE_API_CALL(env, node_api_typeof(env, argv[0], &value_type)); + NODE_API_ASSERT(env, value_type == node_api_function, "StopThread argument is a function"); - NAPI_ASSERT(env, (ts_fn != NULL), "Existing threadsafe function"); - NAPI_CALL(env, - napi_create_reference(env, argv[0], 1, &(ts_info.js_finalize_cb))); + NODE_API_ASSERT(env, (ts_fn != NULL), "Existing threadsafe function"); + NODE_API_CALL(env, + node_api_create_reference(env, argv[0], 1, &(ts_info.js_finalize_cb))); bool abort; - NAPI_CALL(env, napi_get_value_bool(env, argv[1], &abort)); - NAPI_CALL(env, - napi_release_threadsafe_function(ts_fn, - abort ? napi_tsfn_abort : napi_tsfn_release)); + NODE_API_CALL(env, node_api_get_value_bool(env, argv[1], &abort)); + NODE_API_CALL(env, + node_api_release_threadsafe_function(ts_fn, + abort ? node_api_tsfn_abort : node_api_tsfn_release)); ts_fn = NULL; return NULL; } // Join the thread and inform JS that we're done. -static void join_the_threads(napi_env env, void *data, void *hint) { +static void join_the_threads(node_api_env env, void *data, void *hint) { uv_thread_t *the_threads = data; ts_fn_hint *the_hint = hint; - napi_value js_cb, undefined; + node_api_value js_cb, undefined; uv_thread_join(&the_threads[0]); if (the_hint->start_secondary) { uv_thread_join(&the_threads[1]); } - NAPI_CALL_RETURN_VOID(env, - napi_get_reference_value(env, the_hint->js_finalize_cb, &js_cb)); - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, - napi_call_function(env, undefined, js_cb, 0, NULL, NULL)); - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, + NODE_API_CALL_RETURN_VOID(env, + node_api_get_reference_value(env, the_hint->js_finalize_cb, &js_cb)); + NODE_API_CALL_RETURN_VOID(env, node_api_get_undefined(env, &undefined)); + NODE_API_CALL_RETURN_VOID(env, + node_api_call_function(env, undefined, js_cb, 0, NULL, NULL)); + NODE_API_CALL_RETURN_VOID(env, node_api_delete_reference(env, the_hint->js_finalize_cb)); if (alt_ref != NULL) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, alt_ref)); + NODE_API_CALL_RETURN_VOID(env, node_api_delete_reference(env, alt_ref)); alt_ref = NULL; } } -static napi_value StartThreadInternal(napi_env env, - napi_callback_info info, - napi_threadsafe_function_call_js cb, +static node_api_value StartThreadInternal(node_api_env env, + node_api_callback_info info, + node_api_threadsafe_function_call_js cb, bool block_on_full, bool alt_ref_js_cb) { size_t argc = 4; - napi_value argv[4]; + node_api_value argv[4]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, argv, NULL, NULL)); if (alt_ref_js_cb) { - NAPI_CALL(env, napi_create_reference(env, argv[0], 1, &alt_ref)); + NODE_API_CALL(env, node_api_create_reference(env, argv[0], 1, &alt_ref)); argv[0] = NULL; } ts_info.block_on_full = - (block_on_full ? napi_tsfn_blocking : napi_tsfn_nonblocking); - - NAPI_ASSERT(env, (ts_fn == NULL), "Existing thread-safe function"); - napi_value async_name; - NAPI_CALL(env, napi_create_string_utf8(env, "N-API Thread-safe Function Test", - NAPI_AUTO_LENGTH, &async_name)); - NAPI_CALL(env, napi_get_value_uint32(env, argv[3], &ts_info.max_queue_size)); - NAPI_CALL(env, napi_create_threadsafe_function(env, - argv[0], - NULL, - async_name, - ts_info.max_queue_size, - 2, - uv_threads, - join_the_threads, - &ts_info, - cb, - &ts_fn)); + (block_on_full ? node_api_tsfn_blocking : node_api_tsfn_nonblocking); + + NODE_API_ASSERT(env, (ts_fn == NULL), "Existing thread-safe function"); + node_api_value async_name; + NODE_API_CALL(env, + node_api_create_string_utf8(env, "N-API Thread-safe Function Test", + NODE_API_AUTO_LENGTH, &async_name)); + NODE_API_CALL(env, + node_api_get_value_uint32(env, argv[3], &ts_info.max_queue_size)); + NODE_API_CALL(env, node_api_create_threadsafe_function(env, + argv[0], + NULL, + async_name, + ts_info.max_queue_size, + 2, + uv_threads, + join_the_threads, + &ts_info, + cb, + &ts_fn)); bool abort; - NAPI_CALL(env, napi_get_value_bool(env, argv[1], &abort)); - ts_info.abort = abort ? napi_tsfn_abort : napi_tsfn_release; - NAPI_CALL(env, napi_get_value_bool(env, argv[2], &(ts_info.start_secondary))); + NODE_API_CALL(env, node_api_get_value_bool(env, argv[1], &abort)); + ts_info.abort = abort ? node_api_tsfn_abort : node_api_tsfn_release; + NODE_API_CALL(env, + node_api_get_value_bool(env, argv[2], &(ts_info.start_secondary))); - NAPI_ASSERT(env, + NODE_API_ASSERT(env, (uv_thread_create(&uv_threads[0], data_source_thread, ts_fn) == 0), "Thread creation"); return NULL; } -static napi_value Unref(napi_env env, napi_callback_info info) { - NAPI_ASSERT(env, ts_fn != NULL, "No existing thread-safe function"); - NAPI_CALL(env, napi_unref_threadsafe_function(env, ts_fn)); +static node_api_value Unref(node_api_env env, node_api_callback_info info) { + NODE_API_ASSERT(env, ts_fn != NULL, "No existing thread-safe function"); + NODE_API_CALL(env, node_api_unref_threadsafe_function(env, ts_fn)); return NULL; } -static napi_value Release(napi_env env, napi_callback_info info) { - NAPI_ASSERT(env, ts_fn != NULL, "No existing thread-safe function"); - NAPI_CALL(env, napi_release_threadsafe_function(ts_fn, napi_tsfn_release)); +static node_api_value Release(node_api_env env, node_api_callback_info info) { + NODE_API_ASSERT(env, ts_fn != NULL, "No existing thread-safe function"); + NODE_API_CALL(env, + node_api_release_threadsafe_function(ts_fn, node_api_tsfn_release)); return NULL; } // Startup -static napi_value StartThread(napi_env env, napi_callback_info info) { +static node_api_value +StartThread(node_api_env env, node_api_callback_info info) { return StartThreadInternal(env, info, call_js, /** block_on_full */true, /** alt_ref_js_cb */false); } -static napi_value StartThreadNonblocking(napi_env env, - napi_callback_info info) { +static node_api_value +StartThreadNonblocking(node_api_env env, node_api_callback_info info) { return StartThreadInternal(env, info, call_js, /** block_on_full */false, /** alt_ref_js_cb */false); } -static napi_value StartThreadNoNative(napi_env env, napi_callback_info info) { +static node_api_value +StartThreadNoNative(node_api_env env, node_api_callback_info info) { return StartThreadInternal(env, info, NULL, /** block_on_full */true, /** alt_ref_js_cb */false); } -static napi_value StartThreadNoJsFunc(napi_env env, napi_callback_info info) { +static node_api_value +StartThreadNoJsFunc(node_api_env env, node_api_callback_info info) { return StartThreadInternal(env, info, call_ref, /** block_on_full */true, /** alt_ref_js_cb */true); } // Module init -static napi_value Init(napi_env env, napi_value exports) { +static node_api_value Init(node_api_env env, node_api_value exports) { size_t index; for (index = 0; index < ARRAY_LENGTH; index++) { ints[index] = index; } - napi_value js_array_length, js_max_queue_size; - napi_create_uint32(env, ARRAY_LENGTH, &js_array_length); - napi_create_uint32(env, MAX_QUEUE_SIZE, &js_max_queue_size); + node_api_value js_array_length, js_max_queue_size; + node_api_create_uint32(env, ARRAY_LENGTH, &js_array_length); + node_api_create_uint32(env, MAX_QUEUE_SIZE, &js_max_queue_size); - napi_property_descriptor properties[] = { + node_api_property_descriptor properties[] = { { "ARRAY_LENGTH", NULL, @@ -285,7 +302,7 @@ static napi_value Init(napi_env env, napi_value exports) { NULL, NULL, js_array_length, - napi_enumerable, + node_api_enumerable, NULL }, { @@ -295,21 +312,22 @@ static napi_value Init(napi_env env, napi_value exports) { NULL, NULL, js_max_queue_size, - napi_enumerable, + node_api_enumerable, NULL }, - DECLARE_NAPI_PROPERTY("StartThread", StartThread), - DECLARE_NAPI_PROPERTY("StartThreadNoNative", StartThreadNoNative), - DECLARE_NAPI_PROPERTY("StartThreadNonblocking", StartThreadNonblocking), - DECLARE_NAPI_PROPERTY("StartThreadNoJsFunc", StartThreadNoJsFunc), - DECLARE_NAPI_PROPERTY("StopThread", StopThread), - DECLARE_NAPI_PROPERTY("Unref", Unref), - DECLARE_NAPI_PROPERTY("Release", Release), + DECLARE_NODE_API_PROPERTY("StartThread", StartThread), + DECLARE_NODE_API_PROPERTY("StartThreadNoNative", StartThreadNoNative), + DECLARE_NODE_API_PROPERTY("StartThreadNonblocking", + StartThreadNonblocking), + DECLARE_NODE_API_PROPERTY("StartThreadNoJsFunc", StartThreadNoJsFunc), + DECLARE_NODE_API_PROPERTY("StopThread", StopThread), + DECLARE_NODE_API_PROPERTY("Unref", Unref), + DECLARE_NODE_API_PROPERTY("Release", Release), }; - NAPI_CALL(env, napi_define_properties(env, exports, + NODE_API_CALL(env, node_api_define_properties(env, exports, sizeof(properties)/sizeof(properties[0]), properties)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_threadsafe_function/test.js b/test/node-api/test_threadsafe_function/test.js index 3603d79ee6b5d3..fb2645e10234f4 100644 --- a/test/node-api/test_threadsafe_function/test.js +++ b/test/node-api/test_threadsafe_function/test.js @@ -51,7 +51,7 @@ function testWithJSMarshaller({ }, !!abort, !!launchSecondary, maxQueueSize); if (threadStarter === 'StartThreadNonblocking') { // Let's make this thread really busy for a short while to ensure that - // the queue fills and the thread receives a napi_queue_full. + // the queue fills and the thread receives a node_api_queue_full. const start = Date.now(); while (Date.now() - start < 200); } @@ -104,7 +104,8 @@ new Promise(function testWithoutJSMarshaller(resolve) { // Start the thread in blocking mode, and assert that all values are passed. // Quit after it's done. -// Doesn't pass the callback js function to napi_create_threadsafe_function. +// Doesn't pass the callback js function to +// node_api_create_threadsafe_function. // Instead, use an alternative reference to get js function called. .then(() => testWithJSMarshaller({ threadStarter: 'StartThreadNoJsFunc', diff --git a/test/node-api/test_uv_loop/test_uv_loop.cc b/test/node-api/test_uv_loop/test_uv_loop.cc index 51b10f32bb7900..d31e6d60a17ddc 100644 --- a/test/node-api/test_uv_loop/test_uv_loop.cc +++ b/test/node-api/test_uv_loop/test_uv_loop.cc @@ -8,14 +8,14 @@ #include template -void* SetImmediate(napi_env env, T&& cb) { +void* SetImmediate(node_api_env env, T&& cb) { T* ptr = new T(std::move(cb)); uv_loop_t* loop = nullptr; uv_check_t* check = new uv_check_t; check->data = ptr; - NAPI_ASSERT(env, - napi_get_uv_event_loop(env, &loop) == napi_ok, - "can get event loop"); + NODE_API_ASSERT(env, + node_api_get_uv_event_loop(env, &loop) == node_api_ok, + "can get event loop"); uv_check_init(loop, check); uv_check_start(check, [](uv_check_t* check) { std::unique_ptr ptr {static_cast(check->data)}; @@ -40,50 +40,51 @@ void* SetImmediate(napi_env env, T&& cb) { static char dummy; -napi_value SetImmediateBinding(napi_env env, napi_callback_info info) { +node_api_value +SetImmediateBinding(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value argv[1]; - napi_value _this; + node_api_value argv[1]; + node_api_value _this; void* data; - NAPI_CALL(env, - napi_get_cb_info(env, info, &argc, argv, &_this, &data)); - NAPI_ASSERT(env, argc >= 1, "Not enough arguments, expected 1."); + NODE_API_CALL(env, + node_api_get_cb_info(env, info, &argc, argv, &_this, &data)); + NODE_API_ASSERT(env, argc >= 1, "Not enough arguments, expected 1."); - napi_valuetype t; - NAPI_CALL(env, napi_typeof(env, argv[0], &t)); - NAPI_ASSERT(env, t == napi_function, + node_api_valuetype t; + NODE_API_CALL(env, node_api_typeof(env, argv[0], &t)); + NODE_API_ASSERT(env, t == node_api_function, "Wrong first argument, function expected."); - napi_ref cbref; - NAPI_CALL(env, - napi_create_reference(env, argv[0], 1, &cbref)); + node_api_ref cbref; + NODE_API_CALL(env, + node_api_create_reference(env, argv[0], 1, &cbref)); SetImmediate(env, [=]() -> char* { - napi_value undefined; - napi_value callback; - napi_handle_scope scope; - NAPI_CALL(env, napi_open_handle_scope(env, &scope)); - NAPI_CALL(env, napi_get_undefined(env, &undefined)); - NAPI_CALL(env, napi_get_reference_value(env, cbref, &callback)); - NAPI_CALL(env, napi_delete_reference(env, cbref)); - NAPI_CALL(env, - napi_call_function(env, undefined, callback, 0, nullptr, nullptr)); - NAPI_CALL(env, napi_close_handle_scope(env, scope)); + node_api_value undefined; + node_api_value callback; + node_api_handle_scope scope; + NODE_API_CALL(env, node_api_open_handle_scope(env, &scope)); + NODE_API_CALL(env, node_api_get_undefined(env, &undefined)); + NODE_API_CALL(env, node_api_get_reference_value(env, cbref, &callback)); + NODE_API_CALL(env, node_api_delete_reference(env, cbref)); + NODE_API_CALL(env, + node_api_call_function(env, undefined, callback, 0, nullptr, nullptr)); + NODE_API_CALL(env, node_api_close_handle_scope(env, scope)); return &dummy; }); return nullptr; } -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("SetImmediate", SetImmediateBinding) +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor properties[] = { + DECLARE_NODE_API_PROPERTY("SetImmediate", SetImmediateBinding) }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_worker_buffer_callback/test_worker_buffer_callback.c b/test/node-api/test_worker_buffer_callback/test_worker_buffer_callback.c index b4f2e288ece31b..e931eaab579a3f 100644 --- a/test/node-api/test_worker_buffer_callback/test_worker_buffer_callback.c +++ b/test/node-api/test_worker_buffer_callback/test_worker_buffer_callback.c @@ -6,33 +6,34 @@ uint32_t free_call_count = 0; -napi_value GetFreeCallCount(napi_env env, napi_callback_info info) { - napi_value value; - NAPI_CALL(env, napi_create_uint32(env, free_call_count, &value)); +node_api_value +GetFreeCallCount(node_api_env env, node_api_callback_info info) { + node_api_value value; + NODE_API_CALL(env, node_api_create_uint32(env, free_call_count, &value)); return value; } -static void finalize_cb(napi_env env, void* finalize_data, void* hint) { +static void finalize_cb(node_api_env env, void* finalize_data, void* hint) { free(finalize_data); free_call_count++; } -NAPI_MODULE_INIT() { - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("getFreeCallCount", GetFreeCallCount) +NODE_API_MODULE_INIT() { + node_api_property_descriptor properties[] = { + DECLARE_NODE_API_PROPERTY("getFreeCallCount", GetFreeCallCount) }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(properties) / sizeof(*properties), properties)); // This is a slight variation on the non-N-API test: We create an ArrayBuffer // rather than a Node.js Buffer, since testing the latter would only test // the same code paths and not the ones specific to N-API. - napi_value buffer; + node_api_value buffer; char* data = malloc(sizeof(char)); - NAPI_CALL(env, napi_create_external_arraybuffer( + NODE_API_CALL(env, node_api_create_external_arraybuffer( env, data, sizeof(char), @@ -40,7 +41,8 @@ NAPI_MODULE_INIT() { NULL, &buffer)); - NAPI_CALL(env, napi_set_named_property(env, exports, "buffer", buffer)); + NODE_API_CALL(env, + node_api_set_named_property(env, exports, "buffer", buffer)); return exports; } diff --git a/test/node-api/test_worker_terminate/test.js b/test/node-api/test_worker_terminate/test.js index 7c7224c073dda3..6b13f36760fbae 100644 --- a/test/node-api/test_worker_terminate/test.js +++ b/test/node-api/test_worker_terminate/test.js @@ -6,7 +6,7 @@ const { Worker, isMainThread, workerData } = require('worker_threads'); if (isMainThread) { // Load the addon in the main thread first. // This checks that N-API addons can be loaded from multiple contexts - // when they are not loaded through NAPI_MODULE(). + // when they are not loaded through NODE_API_MODULE(). require(`./build/${common.buildType}/test_worker_terminate`); const counter = new Int32Array(new SharedArrayBuffer(4)); diff --git a/test/node-api/test_worker_terminate/test_worker_terminate.c b/test/node-api/test_worker_terminate/test_worker_terminate.c index 517cae42037323..9bde7fd3cfccd0 100644 --- a/test/node-api/test_worker_terminate/test_worker_terminate.c +++ b/test/node-api/test_worker_terminate/test_worker_terminate.c @@ -3,39 +3,39 @@ #include #include "../../js-native-api/common.h" -napi_value Test(napi_env env, napi_callback_info info) { +node_api_value Test(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value recv; - napi_value argv[1]; - napi_status status; + node_api_value recv; + node_api_value argv[1]; + node_api_status status; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &recv, NULL)); - NAPI_ASSERT(env, argc >= 1, "Not enough arguments, expected 1."); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, argv, &recv, NULL)); + NODE_API_ASSERT(env, argc >= 1, "Not enough arguments, expected 1."); - napi_valuetype t; - NAPI_CALL(env, napi_typeof(env, argv[0], &t)); - NAPI_ASSERT(env, t == napi_function, + node_api_valuetype t; + NODE_API_CALL(env, node_api_typeof(env, argv[0], &t)); + NODE_API_ASSERT(env, t == node_api_function, "Wrong first argument, function expected."); - status = napi_call_function(env, recv, argv[0], 0, NULL, NULL); - assert(status == napi_ok); - status = napi_call_function(env, recv, argv[0], 0, NULL, NULL); - assert(status == napi_pending_exception); + status = node_api_call_function(env, recv, argv[0], 0, NULL, NULL); + assert(status == node_api_ok); + status = node_api_call_function(env, recv, argv[0], 0, NULL, NULL); + assert(status == node_api_pending_exception); return NULL; } -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("Test", Test) +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor properties[] = { + DECLARE_NODE_API_PROPERTY("Test", Test) }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } -// Do not start using NAPI_MODULE_INIT() here, so that we can test -// compatibility of Workers with NAPI_MODULE(). -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +// Do not start using NODE_API_MODULE_INIT() here, so that we can test +// compatibility of Workers with NODE_API_MODULE(). +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/node-api/test_worker_terminate_finalization/test_worker_terminate_finalization.c b/test/node-api/test_worker_terminate_finalization/test_worker_terminate_finalization.c index bb23830ecd2731..ee79de487e9634 100644 --- a/test/node-api/test_worker_terminate_finalization/test_worker_terminate_finalization.c +++ b/test/node-api/test_worker_terminate_finalization/test_worker_terminate_finalization.c @@ -7,41 +7,45 @@ #define BUFFER_SIZE 4 int wrappedNativeData; -napi_ref ref; -void WrapFinalizer(napi_env env, void* data, void* hint) { +node_api_ref ref; +void WrapFinalizer(node_api_env env, void* data, void* hint) { uint32_t count; - NAPI_CALL_RETURN_VOID(env, napi_reference_unref(env, ref, &count)); - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, ref)); + NODE_API_CALL_RETURN_VOID(env, node_api_reference_unref(env, ref, &count)); + NODE_API_CALL_RETURN_VOID(env, node_api_delete_reference(env, ref)); } -void BufferFinalizer(napi_env env, void* data, void* hint) { +void BufferFinalizer(node_api_env env, void* data, void* hint) { free(hint); } -napi_value Test(napi_env env, napi_callback_info info) { +node_api_value Test(node_api_env env, node_api_callback_info info) { size_t argc = 1; - napi_value argv[1]; - napi_value result; + node_api_value argv[1]; + node_api_value result; void* bufferData = malloc(BUFFER_SIZE); - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_CALL(env, napi_create_external_buffer(env, BUFFER_SIZE, bufferData, BufferFinalizer, bufferData, &result)); - NAPI_CALL(env, napi_create_reference(env, result, 1, &ref)); - NAPI_CALL(env, napi_wrap(env, argv[0], (void*) &wrappedNativeData, WrapFinalizer, NULL, NULL)); + NODE_API_CALL(env, node_api_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NODE_API_CALL(env, + node_api_create_external_buffer(env, BUFFER_SIZE, bufferData, + BufferFinalizer, bufferData, &result)); + NODE_API_CALL(env, node_api_create_reference(env, result, 1, &ref)); + NODE_API_CALL(env, + node_api_wrap(env, argv[0], (void*) &wrappedNativeData, WrapFinalizer, + NULL, NULL)); return NULL; } -napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("Test", Test) +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_property_descriptor properties[] = { + DECLARE_NODE_API_PROPERTY("Test", Test) }; - NAPI_CALL(env, napi_define_properties( + NODE_API_CALL(env, node_api_define_properties( env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } -// Do not start using NAPI_MODULE_INIT() here, so that we can test -// compatibility of Workers with NAPI_MODULE(). -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) +// Do not start using NODE_API_MODULE_INIT() here, so that we can test +// compatibility of Workers with NODE_API_MODULE(). +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) From 272dcfe91c6872ad3e7d453b2f618f7ec1eb098c Mon Sep 17 00:00:00 2001 From: Gabriel Schulhof Date: Mon, 25 Jan 2021 17:41:40 -0800 Subject: [PATCH 3/8] rename benchmarks --- Makefile | 26 +- benchmark/napi/function_args/napi_binding.c | 231 ----------------- benchmark/napi/function_call/napi_binding.c | 26 -- benchmark/napi/ref/addon.c | 82 ------ benchmark/napi/type-tag/binding.c | 84 ------- .../function_args/.gitignore | 0 .../function_args/binding.cc | 0 .../function_args/binding.gyp | 4 +- .../{napi => node-api}/function_args/index.js | 8 +- .../node-api/function_args/node_api_binding.c | 237 ++++++++++++++++++ .../function_call/.gitignore | 0 .../function_call/binding.cc | 0 .../function_call/binding.gyp | 4 +- .../{napi => node-api}/function_call/index.js | 10 +- .../node-api/function_call/node_api_binding.c | 26 ++ benchmark/{napi => node-api}/ref/.gitignore | 0 benchmark/node-api/ref/addon.c | 83 ++++++ benchmark/{napi => node-api}/ref/binding.gyp | 0 benchmark/{napi => node-api}/ref/index.js | 0 .../type-tag-check/.gitignore | 0 .../type-tag-check/binding.gyp | 0 .../type-tag-check/index.js | 0 .../{napi => node-api}/type-tag/.gitignore | 0 benchmark/node-api/type-tag/binding.c | 89 +++++++ .../{napi => node-api}/type-tag/binding.gyp | 0 .../type-tag/check-object-tag.js | 0 .../{napi => node-api}/type-tag/index.js | 0 27 files changed, 461 insertions(+), 449 deletions(-) delete mode 100644 benchmark/napi/function_args/napi_binding.c delete mode 100644 benchmark/napi/function_call/napi_binding.c delete mode 100644 benchmark/napi/ref/addon.c delete mode 100644 benchmark/napi/type-tag/binding.c rename benchmark/{napi => node-api}/function_args/.gitignore (100%) rename benchmark/{napi => node-api}/function_args/binding.cc (100%) rename benchmark/{napi => node-api}/function_args/binding.gyp (57%) rename benchmark/{napi => node-api}/function_args/index.js (93%) create mode 100644 benchmark/node-api/function_args/node_api_binding.c rename benchmark/{napi => node-api}/function_call/.gitignore (100%) rename benchmark/{napi => node-api}/function_call/binding.cc (100%) rename benchmark/{napi => node-api}/function_call/binding.gyp (57%) rename benchmark/{napi => node-api}/function_call/index.js (80%) create mode 100644 benchmark/node-api/function_call/node_api_binding.c rename benchmark/{napi => node-api}/ref/.gitignore (100%) create mode 100644 benchmark/node-api/ref/addon.c rename benchmark/{napi => node-api}/ref/binding.gyp (100%) rename benchmark/{napi => node-api}/ref/index.js (100%) rename benchmark/{napi => node-api}/type-tag-check/.gitignore (100%) rename benchmark/{napi => node-api}/type-tag-check/binding.gyp (100%) rename benchmark/{napi => node-api}/type-tag-check/index.js (100%) rename benchmark/{napi => node-api}/type-tag/.gitignore (100%) create mode 100644 benchmark/node-api/type-tag/binding.c rename benchmark/{napi => node-api}/type-tag/binding.gyp (100%) rename benchmark/{napi => node-api}/type-tag/check-object-tag.js (100%) rename benchmark/{napi => node-api}/type-tag/index.js (100%) diff --git a/Makefile b/Makefile index aa3eb1567d447e..e9a2a8a7164fa4 100644 --- a/Makefile +++ b/Makefile @@ -436,16 +436,16 @@ test/node-api/.buildstamp: $(ADDONS_PREREQS) \ # TODO(bnoordhuis) Force rebuild after gyp or node-gyp update. build-node-api-tests: | $(NODE_EXE) test/node-api/.buildstamp -BENCHMARK_NAPI_BINDING_GYPS := $(wildcard benchmark/napi/*/binding.gyp) +BENCHMARK_NODE_API_BINDING_GYPS := $(wildcard benchmark/node-api/*/binding.gyp) -BENCHMARK_NAPI_BINDING_SOURCES := \ - $(wildcard benchmark/napi/*/*.c) \ - $(wildcard benchmark/napi/*/*.cc) \ - $(wildcard benchmark/napi/*/*.h) +BENCHMARK_NODE_API_BINDING_SOURCES := \ + $(wildcard benchmark/node-api/*/*.c) \ + $(wildcard benchmark/node-api/*/*.cc) \ + $(wildcard benchmark/node-api/*/*.h) -benchmark/napi/.buildstamp: $(ADDONS_PREREQS) \ - $(BENCHMARK_NAPI_BINDING_GYPS) $(BENCHMARK_NAPI_BINDING_SOURCES) - @$(call run_build_addons,"$$PWD/benchmark/napi",$@) +benchmark/node-api/.buildstamp: $(ADDONS_PREREQS) \ + $(BENCHMARK_NODE_API_BINDING_GYPS) $(BENCHMARK_NODE_API_BINDING_SOURCES) + @$(call run_build_addons,"$$PWD/benchmark/node-api",$@) .PHONY: clear-stalled clear-stalled: @@ -488,7 +488,7 @@ endif # Build and test addons without building anything else # Related CI job: node-test-commit-arm-fanned test-ci-native: LOGLEVEL := info -test-ci-native: | benchmark/napi/.buildstamp test/addons/.buildstamp test/js-native-api/.buildstamp test/node-api/.buildstamp +test-ci-native: | benchmark/node-api/.buildstamp test/addons/.buildstamp test/js-native-api/.buildstamp test/node-api/.buildstamp $(PYTHON) tools/test.py $(PARALLEL_ARGS) -p tap --logfile test.tap \ --mode=$(BUILDTYPE_LOWER) --flaky-tests=$(FLAKY_TESTS) \ $(TEST_CI_ARGS) $(CI_NATIVE_SUITES) @@ -1157,12 +1157,12 @@ bench bench-all: bench-addons-build # Build required addons for benchmark before running it. .PHONY: bench-addons-build -bench-addons-build: | $(NODE_EXE) benchmark/napi/.buildstamp +bench-addons-build: | $(NODE_EXE) benchmark/node-api/.buildstamp .PHONY: bench-addons-clean bench-addons-clean: - $(RM) -r benchmark/napi/*/build - $(RM) benchmark/napi/.buildstamp + $(RM) -r benchmark/node-api/*/build + $(RM) benchmark/node-api/.buildstamp .PHONY: lint-md-rollup lint-md-rollup: @@ -1251,7 +1251,7 @@ LINT_CPP_EXCLUDE += $(wildcard test/js-native-api/??_*/*.cc test/js-native-api/? LINT_CPP_EXCLUDE += src/tracing/trace_event.h src/tracing/trace_event_common.h LINT_CPP_FILES = $(filter-out $(LINT_CPP_EXCLUDE), $(wildcard \ - benchmark/napi/*/*.cc \ + benchmark/node-api/*/*.cc \ src/*.c \ src/*.cc \ src/*.h \ diff --git a/benchmark/napi/function_args/napi_binding.c b/benchmark/napi/function_args/napi_binding.c deleted file mode 100644 index 1a3a0f1cd2b96e..00000000000000 --- a/benchmark/napi/function_args/napi_binding.c +++ /dev/null @@ -1,231 +0,0 @@ -#include -#include -#include -#include -#include - -static napi_value CallWithString(napi_env env, napi_callback_info info) { - napi_status status; - - size_t argc = 1; - napi_value args[1]; - status = napi_get_cb_info(env, info, &argc, args, NULL, NULL); - assert(status == napi_ok); - - napi_valuetype types[1]; - status = napi_typeof(env, args[0], types); - assert(status == napi_ok); - - assert(types[0] == napi_string); - if (types[0] == napi_string) { - size_t len = 0; - // Get the length - status = napi_get_value_string_utf8(env, args[0], NULL, 0, &len); - assert(status == napi_ok); - char* buf = (char*)malloc(len + 1); - status = napi_get_value_string_utf8(env, args[0], buf, len + 1, &len); - assert(status == napi_ok); - free(buf); - } - - return NULL; -} - -static napi_value CallWithArray(napi_env env, napi_callback_info info) { - napi_status status; - - size_t argc = 1; - napi_value args[1]; - status = napi_get_cb_info(env, info, &argc, args, NULL, NULL); - assert(status == napi_ok); - - napi_value array = args[0]; - bool is_array = false; - status = napi_is_array(env, array, &is_array); - assert(status == napi_ok); - - assert(is_array); - if (is_array) { - uint32_t length; - status = napi_get_array_length(env, array, &length); - assert(status == napi_ok); - - uint32_t i; - for (i = 0; i < length; ++i) { - napi_value v; - status = napi_get_element(env, array, i, &v); - assert(status == napi_ok); - } - } - - return NULL; -} - -static napi_value CallWithNumber(napi_env env, napi_callback_info info) { - napi_status status; - - size_t argc = 1; - napi_value args[1]; - status = napi_get_cb_info(env, info, &argc, args, NULL, NULL); - assert(status == napi_ok); - - napi_valuetype types[1]; - status = napi_typeof(env, args[0], types); - assert(status == napi_ok); - - assert(types[0] == napi_number); - if (types[0] == napi_number) { - double value = 0.0; - status = napi_get_value_double(env, args[0], &value); - assert(status == napi_ok); - } - - return NULL; -} - -static napi_value CallWithObject(napi_env env, napi_callback_info info) { - napi_status status; - - size_t argc = 1; - napi_value args[1]; - status = napi_get_cb_info(env, info, &argc, args, NULL, NULL); - assert(status == napi_ok); - - napi_valuetype types[1]; - status = napi_typeof(env, args[0], types); - assert(status == napi_ok); - - assert(argc == 1 && types[0] == napi_object); - if (argc == 1 && types[0] == napi_object) { - napi_value value; - - status = napi_get_named_property(env, args[0], "map", &value); - assert(status == napi_ok); - - status = napi_get_named_property(env, args[0], "operand", &value); - assert(status == napi_ok); - - status = napi_get_named_property(env, args[0], "data", &value); - assert(status == napi_ok); - - status = napi_get_named_property(env, args[0], "reduce", &value); - assert(status == napi_ok); - } - - return NULL; -} - -static napi_value CallWithTypedarray(napi_env env, napi_callback_info info) { - napi_status status; - - size_t argc = 1; - napi_value args[1]; - status = napi_get_cb_info(env, info, &argc, args, NULL, NULL); - assert(status == napi_ok); - - bool is_typedarray = false; - status = napi_is_typedarray(env, args[0], &is_typedarray); - assert(status == napi_ok); - - assert(is_typedarray); - if (is_typedarray) { - napi_typedarray_type type; - napi_value input_buffer; - size_t byte_offset = 0; - size_t length = 0; - status = napi_get_typedarray_info(env, args[0], &type, &length, - NULL, &input_buffer, &byte_offset); - assert(status == napi_ok); - assert(length > 0); - - void* data = NULL; - size_t byte_length = 0; - status = napi_get_arraybuffer_info(env, - input_buffer, &data, &byte_length); - assert(status == napi_ok); - - uint32_t* input_integers = (uint32_t*)((uint8_t*)(data) + byte_offset); - assert(input_integers); - } - - return NULL; -} - -static napi_value CallWithArguments(napi_env env, napi_callback_info info) { - napi_status status; - - size_t argc = 1; - napi_value args[1000]; - // Get the length - status = napi_get_cb_info(env, info, &argc, NULL, NULL, NULL); - assert(status == napi_ok); - - status = napi_get_cb_info(env, info, &argc, args, NULL, NULL); - assert(status == napi_ok); - assert(argc <= 1000); - - napi_valuetype types[1]; - status = napi_typeof(env, args[0], types); - assert(status == napi_ok); - - assert(argc > 1 && types[0] == napi_number); - if (argc > 1 && types[0] == napi_number) { - uint32_t loop = 0; - status = napi_get_value_uint32(env, args[0], &loop); - assert(status == napi_ok); - - uint32_t i; - for (i = 1; i < loop; ++i) { - assert(i < argc); - status = napi_typeof(env, args[i], types); - assert(status == napi_ok); - assert(types[0] == napi_number); - - uint32_t value = 0; - status = napi_get_value_uint32(env, args[i], &value); - assert(status == napi_ok); - } - } - - return NULL; -} - - -#define EXPORT_FUNC(env, exports, name, func) \ - do { \ - napi_status status; \ - napi_value js_func; \ - status = napi_create_function((env), \ - (name), \ - NAPI_AUTO_LENGTH, \ - (func), \ - NULL, \ - &js_func); \ - assert(status == napi_ok); \ - status = napi_set_named_property((env), \ - (exports), \ - (name), \ - js_func); \ - assert(status == napi_ok); \ - } while (0); - - -NAPI_MODULE_INIT() { - EXPORT_FUNC(env, exports, "callWithString", CallWithString); - EXPORT_FUNC(env, exports, "callWithLongString", CallWithString); - - EXPORT_FUNC(env, exports, "callWithArray", CallWithArray); - EXPORT_FUNC(env, exports, "callWithLargeArray", CallWithArray); - EXPORT_FUNC(env, exports, "callWithHugeArray", CallWithArray); - - EXPORT_FUNC(env, exports, "callWithNumber", CallWithNumber); - - EXPORT_FUNC(env, exports, "callWithObject", CallWithObject); - EXPORT_FUNC(env, exports, "callWithTypedarray", CallWithTypedarray); - - EXPORT_FUNC(env, exports, "callWith10Numbers", CallWithArguments); - EXPORT_FUNC(env, exports, "callWith100Numbers", CallWithArguments); - EXPORT_FUNC(env, exports, "callWith1000Numbers", CallWithArguments); - - return exports; -} diff --git a/benchmark/napi/function_call/napi_binding.c b/benchmark/napi/function_call/napi_binding.c deleted file mode 100644 index d97170e0fcd9c5..00000000000000 --- a/benchmark/napi/function_call/napi_binding.c +++ /dev/null @@ -1,26 +0,0 @@ -#include -#include - -static int32_t increment = 0; - -static napi_value Hello(napi_env env, napi_callback_info info) { - napi_value result; - napi_status status = napi_create_int32(env, increment++, &result); - assert(status == napi_ok); - return result; -} - -NAPI_MODULE_INIT() { - napi_value hello; - napi_status status = - napi_create_function(env, - "hello", - NAPI_AUTO_LENGTH, - Hello, - NULL, - &hello); - assert(status == napi_ok); - status = napi_set_named_property(env, exports, "hello", hello); - assert(status == napi_ok); - return exports; -} diff --git a/benchmark/napi/ref/addon.c b/benchmark/napi/ref/addon.c deleted file mode 100644 index 3fb8de603d3ced..00000000000000 --- a/benchmark/napi/ref/addon.c +++ /dev/null @@ -1,82 +0,0 @@ -#include -#define NAPI_EXPERIMENTAL -#include - -#define NAPI_CALL(env, call) \ - do { \ - napi_status status = (call); \ - if (status != napi_ok) { \ - napi_throw_error((env), NULL, #call " failed"); \ - return NULL; \ - } \ - } while (0) - -static napi_value -GetCount(napi_env env, napi_callback_info info) { - napi_value result; - size_t* count; - - NAPI_CALL(env, napi_get_instance_data(env, (void**)&count)); - NAPI_CALL(env, napi_create_uint32(env, *count, &result)); - - return result; -} - -static napi_value -SetCount(napi_env env, napi_callback_info info) { - size_t* count; - - NAPI_CALL(env, napi_get_instance_data(env, (void**)&count)); - - // Set the count to zero irrespective of what is passed into the setter. - *count = 0; - - return NULL; -} - -static void -IncrementCounter(napi_env env, void* data, void* hint) { - size_t* count = data; - (*count) = (*count) + 1; -} - -static napi_value -NewWeak(napi_env env, napi_callback_info info) { - napi_value result; - void* instance_data; - - NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL(env, napi_get_instance_data(env, &instance_data)); - NAPI_CALL(env, napi_add_finalizer(env, - result, - instance_data, - IncrementCounter, - NULL, - NULL)); - - return result; -} - -static void -FreeCount(napi_env env, void* data, void* hint) { - free(data); -} - -/* napi_value */ -NAPI_MODULE_INIT(/* napi_env env, napi_value exports */) { - napi_property_descriptor props[] = { - { "count", NULL, NULL, GetCount, SetCount, NULL, napi_enumerable, NULL }, - { "newWeak", NULL, NewWeak, NULL, NULL, NULL, napi_enumerable, NULL } - }; - - size_t* count = malloc(sizeof(*count)); - *count = 0; - - NAPI_CALL(env, napi_define_properties(env, - exports, - sizeof(props) / sizeof(*props), - props)); - NAPI_CALL(env, napi_set_instance_data(env, count, FreeCount, NULL)); - - return exports; -} diff --git a/benchmark/napi/type-tag/binding.c b/benchmark/napi/type-tag/binding.c deleted file mode 100644 index 7bc8b5d7502e8b..00000000000000 --- a/benchmark/napi/type-tag/binding.c +++ /dev/null @@ -1,84 +0,0 @@ -#include -#define NAPI_EXPERIMENTAL -#include - -#define NAPI_CALL(call) \ - do { \ - napi_status status = call; \ - assert(status == napi_ok && #call " failed"); \ - } while (0); - -#define EXPORT_FUNC(env, exports, name, func) \ - do { \ - napi_value js_func; \ - NAPI_CALL(napi_create_function((env), \ - (name), \ - NAPI_AUTO_LENGTH, \ - (func), \ - NULL, \ - &js_func)); \ - NAPI_CALL(napi_set_named_property((env), \ - (exports), \ - (name), \ - js_func)); \ - } while (0); - -static const napi_type_tag tag = { - 0xe7ecbcd5954842f6, 0x9e75161c9bf27282 -}; - -static napi_value TagObject(napi_env env, napi_callback_info info) { - size_t argc = 4; - napi_value argv[4]; - uint32_t n; - uint32_t index; - napi_handle_scope scope; - - NAPI_CALL(napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_CALL(napi_get_value_uint32(env, argv[0], &n)); - NAPI_CALL(napi_open_handle_scope(env, &scope)); - napi_value objects[n]; - for (index = 0; index < n; index++) { - NAPI_CALL(napi_create_object(env, &objects[index])); - } - - // Time the object tag creation. - NAPI_CALL(napi_call_function(env, argv[1], argv[2], 0, NULL, NULL)); - for (index = 0; index < n; index++) { - NAPI_CALL(napi_type_tag_object(env, objects[index], &tag)); - } - NAPI_CALL(napi_call_function(env, argv[1], argv[3], 1, &argv[0], NULL)); - - NAPI_CALL(napi_close_handle_scope(env, scope)); - return NULL; -} - -static napi_value CheckObjectTag(napi_env env, napi_callback_info info) { - size_t argc = 4; - napi_value argv[4]; - uint32_t n; - uint32_t index; - bool is_of_type; - - NAPI_CALL(napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_CALL(napi_get_value_uint32(env, argv[0], &n)); - napi_value object; - NAPI_CALL(napi_create_object(env, &object)); - NAPI_CALL(napi_type_tag_object(env, object, &tag)); - - // Time the object tag checking. - NAPI_CALL(napi_call_function(env, argv[1], argv[2], 0, NULL, NULL)); - for (index = 0; index < n; index++) { - NAPI_CALL(napi_check_object_type_tag(env, object, &tag, &is_of_type)); - assert(is_of_type && " type mismatch"); - } - NAPI_CALL(napi_call_function(env, argv[1], argv[3], 1, &argv[0], NULL)); - - return NULL; -} - -NAPI_MODULE_INIT() { - EXPORT_FUNC(env, exports, "tagObject", TagObject); - EXPORT_FUNC(env, exports, "checkObjectTag", CheckObjectTag); - return exports; -} diff --git a/benchmark/napi/function_args/.gitignore b/benchmark/node-api/function_args/.gitignore similarity index 100% rename from benchmark/napi/function_args/.gitignore rename to benchmark/node-api/function_args/.gitignore diff --git a/benchmark/napi/function_args/binding.cc b/benchmark/node-api/function_args/binding.cc similarity index 100% rename from benchmark/napi/function_args/binding.cc rename to benchmark/node-api/function_args/binding.cc diff --git a/benchmark/napi/function_args/binding.gyp b/benchmark/node-api/function_args/binding.gyp similarity index 57% rename from benchmark/napi/function_args/binding.gyp rename to benchmark/node-api/function_args/binding.gyp index ac122ed1a07962..06abb671a1ddd7 100644 --- a/benchmark/napi/function_args/binding.gyp +++ b/benchmark/node-api/function_args/binding.gyp @@ -1,8 +1,8 @@ { 'targets': [ { - 'target_name': 'napi_binding', - 'sources': [ 'napi_binding.c' ] + 'target_name': 'node_api_binding', + 'sources': [ 'node_api_binding.c' ] }, { 'target_name': 'binding', diff --git a/benchmark/napi/function_args/index.js b/benchmark/node-api/function_args/index.js similarity index 93% rename from benchmark/napi/function_args/index.js rename to benchmark/node-api/function_args/index.js index 8ce9fa9d528f5c..33742c1a40ade0 100644 --- a/benchmark/napi/function_args/index.js +++ b/benchmark/node-api/function_args/index.js @@ -7,7 +7,7 @@ const common = require('../../common.js'); let v8; -let napi; +let node_api; try { v8 = require(`./build/${common.buildType}/binding`); @@ -17,7 +17,7 @@ try { } try { - napi = require(`./build/${common.buildType}/napi_binding`); + node_api = require(`./build/${common.buildType}/node_api_binding`); } catch { console.error(`${__filename}: NAPI-Binding failed to load`); process.exit(0); @@ -76,12 +76,12 @@ const generateArgs = (argType) => { const bench = common.createBenchmark(main, { type: argsTypes, - engine: ['v8', 'napi'], + engine: ['v8', 'node_api'], n: [1, 1e1, 1e2, 1e3, 1e4, 1e5], }); function main({ n, engine, type }) { - const bindings = engine === 'v8' ? v8 : napi; + const bindings = engine === 'v8' ? v8 : node_api; const methodName = 'callWith' + type; const fn = bindings[methodName]; diff --git a/benchmark/node-api/function_args/node_api_binding.c b/benchmark/node-api/function_args/node_api_binding.c new file mode 100644 index 00000000000000..070e009225fe20 --- /dev/null +++ b/benchmark/node-api/function_args/node_api_binding.c @@ -0,0 +1,237 @@ +#include +#include +#include +#include +#include + +static node_api_value +CallWithString(node_api_env env, node_api_callback_info info) { + node_api_status status; + + size_t argc = 1; + node_api_value args[1]; + status = node_api_get_cb_info(env, info, &argc, args, NULL, NULL); + assert(status == node_api_ok); + + node_api_valuetype types[1]; + status = node_api_typeof(env, args[0], types); + assert(status == node_api_ok); + + assert(types[0] == node_api_string); + if (types[0] == node_api_string) { + size_t len = 0; + // Get the length + status = node_api_get_value_string_utf8(env, args[0], NULL, 0, &len); + assert(status == node_api_ok); + char* buf = (char*)malloc(len + 1); + status = node_api_get_value_string_utf8(env, args[0], buf, len + 1, &len); + assert(status == node_api_ok); + free(buf); + } + + return NULL; +} + +static node_api_value +CallWithArray(node_api_env env, node_api_callback_info info) { + node_api_status status; + + size_t argc = 1; + node_api_value args[1]; + status = node_api_get_cb_info(env, info, &argc, args, NULL, NULL); + assert(status == node_api_ok); + + node_api_value array = args[0]; + bool is_array = false; + status = node_api_is_array(env, array, &is_array); + assert(status == node_api_ok); + + assert(is_array); + if (is_array) { + uint32_t length; + status = node_api_get_array_length(env, array, &length); + assert(status == node_api_ok); + + uint32_t i; + for (i = 0; i < length; ++i) { + node_api_value v; + status = node_api_get_element(env, array, i, &v); + assert(status == node_api_ok); + } + } + + return NULL; +} + +static node_api_value +CallWithNumber(node_api_env env, node_api_callback_info info) { + node_api_status status; + + size_t argc = 1; + node_api_value args[1]; + status = node_api_get_cb_info(env, info, &argc, args, NULL, NULL); + assert(status == node_api_ok); + + node_api_valuetype types[1]; + status = node_api_typeof(env, args[0], types); + assert(status == node_api_ok); + + assert(types[0] == node_api_number); + if (types[0] == node_api_number) { + double value = 0.0; + status = node_api_get_value_double(env, args[0], &value); + assert(status == node_api_ok); + } + + return NULL; +} + +static node_api_value +CallWithObject(node_api_env env, node_api_callback_info info) { + node_api_status status; + + size_t argc = 1; + node_api_value args[1]; + status = node_api_get_cb_info(env, info, &argc, args, NULL, NULL); + assert(status == node_api_ok); + + node_api_valuetype types[1]; + status = node_api_typeof(env, args[0], types); + assert(status == node_api_ok); + + assert(argc == 1 && types[0] == node_api_object); + if (argc == 1 && types[0] == node_api_object) { + node_api_value value; + + status = node_api_get_named_property(env, args[0], "map", &value); + assert(status == node_api_ok); + + status = node_api_get_named_property(env, args[0], "operand", &value); + assert(status == node_api_ok); + + status = node_api_get_named_property(env, args[0], "data", &value); + assert(status == node_api_ok); + + status = node_api_get_named_property(env, args[0], "reduce", &value); + assert(status == node_api_ok); + } + + return NULL; +} + +static node_api_value +CallWithTypedarray(node_api_env env, node_api_callback_info info) { + node_api_status status; + + size_t argc = 1; + node_api_value args[1]; + status = node_api_get_cb_info(env, info, &argc, args, NULL, NULL); + assert(status == node_api_ok); + + bool is_typedarray = false; + status = node_api_is_typedarray(env, args[0], &is_typedarray); + assert(status == node_api_ok); + + assert(is_typedarray); + if (is_typedarray) { + node_api_typedarray_type type; + node_api_value input_buffer; + size_t byte_offset = 0; + size_t length = 0; + status = node_api_get_typedarray_info(env, args[0], &type, &length, + NULL, &input_buffer, &byte_offset); + assert(status == node_api_ok); + assert(length > 0); + + void* data = NULL; + size_t byte_length = 0; + status = node_api_get_arraybuffer_info(env, + input_buffer, &data, &byte_length); + assert(status == node_api_ok); + + uint32_t* input_integers = (uint32_t*)((uint8_t*)(data) + byte_offset); + assert(input_integers); + } + + return NULL; +} + +static node_api_value +CallWithArguments(node_api_env env, node_api_callback_info info) { + node_api_status status; + + size_t argc = 1; + node_api_value args[1000]; + // Get the length + status = node_api_get_cb_info(env, info, &argc, NULL, NULL, NULL); + assert(status == node_api_ok); + + status = node_api_get_cb_info(env, info, &argc, args, NULL, NULL); + assert(status == node_api_ok); + assert(argc <= 1000); + + node_api_valuetype types[1]; + status = node_api_typeof(env, args[0], types); + assert(status == node_api_ok); + + assert(argc > 1 && types[0] == node_api_number); + if (argc > 1 && types[0] == node_api_number) { + uint32_t loop = 0; + status = node_api_get_value_uint32(env, args[0], &loop); + assert(status == node_api_ok); + + uint32_t i; + for (i = 1; i < loop; ++i) { + assert(i < argc); + status = node_api_typeof(env, args[i], types); + assert(status == node_api_ok); + assert(types[0] == node_api_number); + + uint32_t value = 0; + status = node_api_get_value_uint32(env, args[i], &value); + assert(status == node_api_ok); + } + } + + return NULL; +} + + +#define EXPORT_FUNC(env, exports, name, func) \ + do { \ + node_api_status status; \ + node_api_value js_func; \ + status = node_api_create_function((env), \ + (name), \ + NODE_API_AUTO_LENGTH, \ + (func), \ + NULL, \ + &js_func); \ + assert(status == node_api_ok); \ + status = node_api_set_named_property((env), \ + (exports), \ + (name), \ + js_func); \ + assert(status == node_api_ok); \ + } while (0); + + +NODE_API_MODULE_INIT() { + EXPORT_FUNC(env, exports, "callWithString", CallWithString); + EXPORT_FUNC(env, exports, "callWithLongString", CallWithString); + + EXPORT_FUNC(env, exports, "callWithArray", CallWithArray); + EXPORT_FUNC(env, exports, "callWithLargeArray", CallWithArray); + EXPORT_FUNC(env, exports, "callWithHugeArray", CallWithArray); + + EXPORT_FUNC(env, exports, "callWithNumber", CallWithNumber); + + EXPORT_FUNC(env, exports, "callWithObject", CallWithObject); + EXPORT_FUNC(env, exports, "callWithTypedarray", CallWithTypedarray); + + EXPORT_FUNC(env, exports, "callWith10Numbers", CallWithArguments); + EXPORT_FUNC(env, exports, "callWith100Numbers", CallWithArguments); + EXPORT_FUNC(env, exports, "callWith1000Numbers", CallWithArguments); + + return exports; +} diff --git a/benchmark/napi/function_call/.gitignore b/benchmark/node-api/function_call/.gitignore similarity index 100% rename from benchmark/napi/function_call/.gitignore rename to benchmark/node-api/function_call/.gitignore diff --git a/benchmark/napi/function_call/binding.cc b/benchmark/node-api/function_call/binding.cc similarity index 100% rename from benchmark/napi/function_call/binding.cc rename to benchmark/node-api/function_call/binding.cc diff --git a/benchmark/napi/function_call/binding.gyp b/benchmark/node-api/function_call/binding.gyp similarity index 57% rename from benchmark/napi/function_call/binding.gyp rename to benchmark/node-api/function_call/binding.gyp index ac122ed1a07962..06abb671a1ddd7 100644 --- a/benchmark/napi/function_call/binding.gyp +++ b/benchmark/node-api/function_call/binding.gyp @@ -1,8 +1,8 @@ { 'targets': [ { - 'target_name': 'napi_binding', - 'sources': [ 'napi_binding.c' ] + 'target_name': 'node_api_binding', + 'sources': [ 'node_api_binding.c' ] }, { 'target_name': 'binding', diff --git a/benchmark/napi/function_call/index.js b/benchmark/node-api/function_call/index.js similarity index 80% rename from benchmark/napi/function_call/index.js rename to benchmark/node-api/function_call/index.js index 1e1d159c8ad83a..1416ce54799988 100644 --- a/benchmark/napi/function_call/index.js +++ b/benchmark/node-api/function_call/index.js @@ -20,14 +20,14 @@ try { } const cxx = binding.hello; -let napi_binding; +let node_api_binding; try { - napi_binding = require(`./build/${common.buildType}/napi_binding`); + node_api_binding = require(`./build/${common.buildType}/node_api_binding`); } catch { console.error('misc/function_call/index.js NAPI-Binding failed to load'); process.exit(0); } -const napi = napi_binding.hello; +const node_api = node_api_binding.hello; let c = 0; function js() { @@ -37,12 +37,12 @@ function js() { assert(js() === cxx()); const bench = common.createBenchmark(main, { - type: ['js', 'cxx', 'napi'], + type: ['js', 'cxx', 'node_api'], n: [1e6, 1e7, 5e7] }); function main({ n, type }) { - const fn = type === 'cxx' ? cxx : type === 'napi' ? napi : js; + const fn = type === 'cxx' ? cxx : type === 'node_api' ? node_api : js; bench.start(); for (let i = 0; i < n; i++) { fn(); diff --git a/benchmark/node-api/function_call/node_api_binding.c b/benchmark/node-api/function_call/node_api_binding.c new file mode 100644 index 00000000000000..459967f975e04e --- /dev/null +++ b/benchmark/node-api/function_call/node_api_binding.c @@ -0,0 +1,26 @@ +#include +#include + +static int32_t increment = 0; + +static node_api_value Hello(node_api_env env, node_api_callback_info info) { + node_api_value result; + node_api_status status = node_api_create_int32(env, increment++, &result); + assert(status == node_api_ok); + return result; +} + +NODE_API_MODULE_INIT() { + node_api_value hello; + node_api_status status = + node_api_create_function(env, + "hello", + NODE_API_AUTO_LENGTH, + Hello, + NULL, + &hello); + assert(status == node_api_ok); + status = node_api_set_named_property(env, exports, "hello", hello); + assert(status == node_api_ok); + return exports; +} diff --git a/benchmark/napi/ref/.gitignore b/benchmark/node-api/ref/.gitignore similarity index 100% rename from benchmark/napi/ref/.gitignore rename to benchmark/node-api/ref/.gitignore diff --git a/benchmark/node-api/ref/addon.c b/benchmark/node-api/ref/addon.c new file mode 100644 index 00000000000000..d9ea8e0718e8a6 --- /dev/null +++ b/benchmark/node-api/ref/addon.c @@ -0,0 +1,83 @@ +#include +#define NODE_API_EXPERIMENTAL +#include + +#define NODE_API_CALL(env, call) \ + do { \ + node_api_status status = (call); \ + if (status != node_api_ok) { \ + node_api_throw_error((env), NULL, #call " failed"); \ + return NULL; \ + } \ + } while (0) + +static node_api_value +GetCount(node_api_env env, node_api_callback_info info) { + node_api_value result; + size_t* count; + + NODE_API_CALL(env, node_api_get_instance_data(env, (void**)&count)); + NODE_API_CALL(env, node_api_create_uint32(env, *count, &result)); + + return result; +} + +static node_api_value +SetCount(node_api_env env, node_api_callback_info info) { + size_t* count; + + NODE_API_CALL(env, node_api_get_instance_data(env, (void**)&count)); + + // Set the count to zero irrespective of what is passed into the setter. + *count = 0; + + return NULL; +} + +static void +IncrementCounter(node_api_env env, void* data, void* hint) { + size_t* count = data; + (*count) = (*count) + 1; +} + +static node_api_value +NewWeak(node_api_env env, node_api_callback_info info) { + node_api_value result; + void* instance_data; + + NODE_API_CALL(env, node_api_create_object(env, &result)); + NODE_API_CALL(env, node_api_get_instance_data(env, &instance_data)); + NODE_API_CALL(env, node_api_add_finalizer(env, + result, + instance_data, + IncrementCounter, + NULL, + NULL)); + + return result; +} + +static void +FreeCount(node_api_env env, void* data, void* hint) { + free(data); +} + +/* node_api_value */ +NODE_API_MODULE_INIT(/* node_api_env env, node_api_value exports */) { + node_api_property_descriptor props[] = { + { "count", NULL, NULL, GetCount, SetCount, NULL, node_api_enumerable, + NULL }, + { "newWeak", NULL, NewWeak, NULL, NULL, NULL, node_api_enumerable, NULL } + }; + + size_t* count = malloc(sizeof(*count)); + *count = 0; + + NODE_API_CALL(env, node_api_define_properties(env, + exports, + sizeof(props) / sizeof(*props), + props)); + NODE_API_CALL(env, node_api_set_instance_data(env, count, FreeCount, NULL)); + + return exports; +} diff --git a/benchmark/napi/ref/binding.gyp b/benchmark/node-api/ref/binding.gyp similarity index 100% rename from benchmark/napi/ref/binding.gyp rename to benchmark/node-api/ref/binding.gyp diff --git a/benchmark/napi/ref/index.js b/benchmark/node-api/ref/index.js similarity index 100% rename from benchmark/napi/ref/index.js rename to benchmark/node-api/ref/index.js diff --git a/benchmark/napi/type-tag-check/.gitignore b/benchmark/node-api/type-tag-check/.gitignore similarity index 100% rename from benchmark/napi/type-tag-check/.gitignore rename to benchmark/node-api/type-tag-check/.gitignore diff --git a/benchmark/napi/type-tag-check/binding.gyp b/benchmark/node-api/type-tag-check/binding.gyp similarity index 100% rename from benchmark/napi/type-tag-check/binding.gyp rename to benchmark/node-api/type-tag-check/binding.gyp diff --git a/benchmark/napi/type-tag-check/index.js b/benchmark/node-api/type-tag-check/index.js similarity index 100% rename from benchmark/napi/type-tag-check/index.js rename to benchmark/node-api/type-tag-check/index.js diff --git a/benchmark/napi/type-tag/.gitignore b/benchmark/node-api/type-tag/.gitignore similarity index 100% rename from benchmark/napi/type-tag/.gitignore rename to benchmark/node-api/type-tag/.gitignore diff --git a/benchmark/node-api/type-tag/binding.c b/benchmark/node-api/type-tag/binding.c new file mode 100644 index 00000000000000..bdab16b2249d5f --- /dev/null +++ b/benchmark/node-api/type-tag/binding.c @@ -0,0 +1,89 @@ +#include +#define NODE_API_EXPERIMENTAL +#include + +#define NODE_API_CALL(call) \ + do { \ + node_api_status status = call; \ + assert(status == node_api_ok && #call " failed"); \ + } while (0); + +#define EXPORT_FUNC(env, exports, name, func) \ + do { \ + node_api_value js_func; \ + NODE_API_CALL(node_api_create_function((env), \ + (name), \ + NODE_API_AUTO_LENGTH, \ + (func), \ + NULL, \ + &js_func)); \ + NODE_API_CALL(node_api_set_named_property((env), \ + (exports), \ + (name), \ + js_func)); \ + } while (0); + +static const node_api_type_tag tag = { + 0xe7ecbcd5954842f6, 0x9e75161c9bf27282 +}; + +static node_api_value +TagObject(node_api_env env, node_api_callback_info info) { + size_t argc = 4; + node_api_value argv[4]; + uint32_t n; + uint32_t index; + node_api_handle_scope scope; + + NODE_API_CALL(node_api_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NODE_API_CALL(node_api_get_value_uint32(env, argv[0], &n)); + NODE_API_CALL(node_api_open_handle_scope(env, &scope)); + node_api_value objects[n]; + for (index = 0; index < n; index++) { + NODE_API_CALL(node_api_create_object(env, &objects[index])); + } + + // Time the object tag creation. + NODE_API_CALL(node_api_call_function(env, argv[1], argv[2], 0, NULL, NULL)); + for (index = 0; index < n; index++) { + NODE_API_CALL(node_api_type_tag_object(env, objects[index], &tag)); + } + NODE_API_CALL(node_api_call_function( + env, argv[1], argv[3], 1, &argv[0], NULL)); + + NODE_API_CALL(node_api_close_handle_scope(env, scope)); + return NULL; +} + +static node_api_value +CheckObjectTag(node_api_env env, node_api_callback_info info) { + size_t argc = 4; + node_api_value argv[4]; + uint32_t n; + uint32_t index; + bool is_of_type; + + NODE_API_CALL(node_api_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NODE_API_CALL(node_api_get_value_uint32(env, argv[0], &n)); + node_api_value object; + NODE_API_CALL(node_api_create_object(env, &object)); + NODE_API_CALL(node_api_type_tag_object(env, object, &tag)); + + // Time the object tag checking. + NODE_API_CALL(node_api_call_function(env, argv[1], argv[2], 0, NULL, NULL)); + for (index = 0; index < n; index++) { + NODE_API_CALL(node_api_check_object_type_tag( + env, object, &tag, &is_of_type)); + assert(is_of_type && " type mismatch"); + } + NODE_API_CALL(node_api_call_function( + env, argv[1], argv[3], 1, &argv[0], NULL)); + + return NULL; +} + +NODE_API_MODULE_INIT() { + EXPORT_FUNC(env, exports, "tagObject", TagObject); + EXPORT_FUNC(env, exports, "checkObjectTag", CheckObjectTag); + return exports; +} diff --git a/benchmark/napi/type-tag/binding.gyp b/benchmark/node-api/type-tag/binding.gyp similarity index 100% rename from benchmark/napi/type-tag/binding.gyp rename to benchmark/node-api/type-tag/binding.gyp diff --git a/benchmark/napi/type-tag/check-object-tag.js b/benchmark/node-api/type-tag/check-object-tag.js similarity index 100% rename from benchmark/napi/type-tag/check-object-tag.js rename to benchmark/node-api/type-tag/check-object-tag.js diff --git a/benchmark/napi/type-tag/index.js b/benchmark/node-api/type-tag/index.js similarity index 100% rename from benchmark/napi/type-tag/index.js rename to benchmark/node-api/type-tag/index.js From 8e0addf07f2dd54b2d77f2cb790c41b55fc2cf5d Mon Sep 17 00:00:00 2001 From: Gabriel Schulhof Date: Tue, 26 Jan 2021 09:38:59 -0800 Subject: [PATCH 4/8] update docs tools and src some more --- .github/CODEOWNERS | 6 +- Makefile | 2 +- benchmark/node-api/function_args/index.js | 2 +- configure.py | 6 +- doc/api/addons.md | 63 +- doc/api/errors.md | 13 +- doc/api/index.md | 2 +- doc/api/n-api.md | 6080 ---------------- doc/api/node-api.md | 6172 +++++++++++++++++ doc/api/process.md | 2 +- doc/api/util.md | 20 +- ...new-napi-api.md => adding-new-node-api.md} | 14 +- doc/guides/collaborator-guide.md | 29 +- .../investigating_native_memory_leak.md | 20 +- src/README.md | 4 +- src/js_native_api.h | 8 +- src/js_native_api_v8.cc | 29 +- src/js_native_api_v8_internals.h | 18 +- src/node_api.cc | 8 +- src/node_binding.cc | 2 +- test/js-native-api/test_object/test_null.js | 2 +- .../test_callback_scope/test-async-hooks.js | 2 +- .../test_threadsafe_function/binding.c | 2 +- .../test_worker_buffer_callback.c | 4 +- test/node-api/test_worker_terminate/test.js | 2 +- tools/doc/common.js | 4 +- tools/doc/html.js | 5 +- ...ldversion.py => getnodeapibuildversion.py} | 12 +- tools/lint-md.js | 2 +- 29 files changed, 6318 insertions(+), 6217 deletions(-) delete mode 100644 doc/api/n-api.md create mode 100644 doc/api/node-api.md rename doc/guides/{adding-new-napi-api.md => adding-new-node-api.md} (86%) rename tools/{getnapibuildversion.py => getnodeapibuildversion.py} (61%) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 47f7380d36ff9c..d3e87251ee469c 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -100,12 +100,12 @@ /lib/internal/bootstrap/loaders.js @nodejs/modules /src/module_wrap* @nodejs/modules @nodejs/vm -# N-API +# Node.js API /src/node_api* @nodejs/n-api /src/js_native_api* @nodejs/n-api -/doc/guides/adding-new-napi-api.md @nodejs/n-api -/doc/api/n-api.md @nodejs/n-api +/doc/guides/adding-new-node-api.md @nodejs/n-api +/doc/api/node-api.md @nodejs/n-api # WASI /deps/uvwasi/ @nodejs/wasi diff --git a/Makefile b/Makefile index e9a2a8a7164fa4..ed60971b6236a4 100644 --- a/Makefile +++ b/Makefile @@ -143,7 +143,7 @@ out/Makefile: config.gypi common.gypi node.gyp \ tools/v8_gypfiles/inspector.gypi tools/v8_gypfiles/v8.gyp $(PYTHON) tools/gyp_node.py -f make -# node_version.h is listed because the N-API version is taken from there +# node_version.h is listed because the Node.js API version is taken from there # and included in config.gypi config.gypi: configure configure.py src/node_version.h @if [ -x config.status ]; then \ diff --git a/benchmark/node-api/function_args/index.js b/benchmark/node-api/function_args/index.js index 33742c1a40ade0..fe89814dd41d72 100644 --- a/benchmark/node-api/function_args/index.js +++ b/benchmark/node-api/function_args/index.js @@ -1,5 +1,5 @@ // Show the difference between calling a V8 binding C++ function -// relative to a comparable N-API C++ function, +// relative to a comparable Node.js API C++ function, // in various types/numbers of arguments. // Reports n of calls per second. 'use strict'; diff --git a/configure.py b/configure.py index 8ed8524b26667e..bc08a62883b13b 100755 --- a/configure.py +++ b/configure.py @@ -37,7 +37,7 @@ # imports in tools/ sys.path.insert(0, 'tools') import getmoduleversion -import getnapibuildversion +import getnodeapibuildversion from gyp_node import run_gyp # parse our options @@ -1339,8 +1339,8 @@ def configure_node(o): o['variables']['node_builtin_modules_path'] = options.node_builtin_modules_path def configure_napi(output): - version = getnapibuildversion.get_napi_version() - output['variables']['napi_build_version'] = version + version = getnodeapibuildversion.get_node_api_version() + output['variables']['node_api_build_version'] = version def configure_library(lib, output, pkgname=None): shared_lib = 'shared_' + lib diff --git a/doc/api/addons.md b/doc/api/addons.md index 19799233cf7584..d1f975d5d52815 100644 --- a/doc/api/addons.md +++ b/doc/api/addons.md @@ -7,12 +7,14 @@ _Addons_ are dynamically-linked shared objects written in C++. The [`require()`][require] function can load addons as ordinary Node.js modules. Addons provide an interface between JavaScript and C/C++ libraries. -There are three options for implementing addons: N-API, nan, or direct -use of internal V8, libuv and Node.js libraries. Unless there is a need for -direct access to functionality which is not exposed by N-API, use N-API. -Refer to [C/C++ addons with N-API](n-api.md) for more information on N-API. - -When not using N-API, implementing addons is complicated, +There are three options for implementing addons: the Node.js API, nan, or +direct use of internal V8, libuv and Node.js libraries. Unless there is a need +for direct access to functionality which is not exposed by the Node.js API, use +the Node.js API. +Refer to [C/C++ addons with the Node.js API](node--api.md) for more information +on the Node.js API. + +When not using the Node.js API, implementing addons is complicated, involving knowledge of several components and APIs: * V8: the C++ library Node.js uses to provide the @@ -245,7 +247,7 @@ changes: In order to be loaded from multiple Node.js environments, such as a main thread and a Worker thread, an add-on needs to either: -* Be an N-API addon, or +* Be a Node.js API addon, or * Be declared as context-aware using `NODE_MODULE_INIT()` as described above In order to support [`Worker`][] threads, addons need to clean up any resources @@ -437,11 +439,11 @@ addon developers are recommended to use to keep compatibility between past and future releases of V8 and Node.js. See the `nan` [examples][] for an illustration of how it can be used. -## N-API +## The Node.js API > Stability: 2 - Stable -N-API is an API for building native addons. It is independent from +The Node.js API is an API for building native addons. It is independent from the underlying JavaScript runtime (e.g. V8) and is maintained as part of Node.js itself. This API will be Application Binary Interface (ABI) stable across versions of Node.js. It is intended to insulate addons from @@ -451,49 +453,52 @@ recompilation. Addons are built/packaged with the same approach/tools outlined in this document (node-gyp, etc.). The only difference is the set of APIs that are used by the native code. Instead of using the V8 or [Native Abstractions for Node.js][] APIs, the functions available -in the N-API are used. +in the Node.js API are used. Creating and maintaining an addon that benefits from the ABI stability -provided by N-API carries with it certain -[implementation considerations](n-api.md#n_api_implications_of_abi_stability). +provided by the Node.js API carries with it certain +[implementation considerations](node-api.md#n_api_implications_of_abi_stability). -To use N-API in the above "Hello world" example, replace the content of -`hello.cc` with the following. All other instructions remain the same. +To use the Node.js API in the above "Hello world" example, replace the content +of `hello.cc` with the following. All other instructions remain the same. ```cpp -// hello.cc using N-API +// hello.cc using Node.js API #include namespace demo { -napi_value Method(napi_env env, napi_callback_info args) { - napi_value greeting; - napi_status status; +node_api_value Method(node_api_env env, node_api_callback_info args) { + node_api_value greeting; + node_api_status status; - status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting); - if (status != napi_ok) return nullptr; + status = node_api_create_string_utf8(env, + "world", + NODE_API_AUTO_LENGTH, + &greeting); + if (status != node_api_ok) return nullptr; return greeting; } -napi_value init(napi_env env, napi_value exports) { - napi_status status; - napi_value fn; +node_api_value init(node_api_env env, node_api_value exports) { + node_api_status status; + node_api_value fn; - status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn); - if (status != napi_ok) return nullptr; + status = node_api_create_function(env, nullptr, 0, Method, nullptr, &fn); + if (status != node_api_ok) return nullptr; - status = napi_set_named_property(env, exports, "hello", fn); - if (status != napi_ok) return nullptr; + status = node_api_set_named_property(env, exports, "hello", fn); + if (status != node_api_ok) return nullptr; return exports; } -NAPI_MODULE(NODE_GYP_MODULE_NAME, init) +NODE_API_MODULE(NODE_GYP_MODULE_NAME, init) } // namespace demo ``` The functions available and how to use them are documented in -[C/C++ addons with N-API](n-api.md). +[C/C++ addons with the Node.js API](node-api.md). ## Addon examples diff --git a/doc/api/errors.md b/doc/api/errors.md index d0e0b8794f09ce..82053d859f4038 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -1811,24 +1811,25 @@ would be possible by calling a callback more than once. ### `ERR_NAPI_CONS_FUNCTION` -While using `N-API`, a constructor passed was not a function. +While using the Node.js API, a constructor passed was not a function. ### `ERR_NAPI_INVALID_DATAVIEW_ARGS` -While calling `napi_create_dataview()`, a given `offset` was outside the bounds -of the dataview or `offset + length` was larger than a length of given `buffer`. +While calling `node_api_create_dataview()`, a given `offset` was outside the +bounds of the dataview or `offset + length` was larger than a length of given +`buffer`. ### `ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT` -While calling `napi_create_typedarray()`, the provided `offset` was not a +While calling `node_api_create_typedarray()`, the provided `offset` was not a multiple of the element size. ### `ERR_NAPI_INVALID_TYPEDARRAY_LENGTH` -While calling `napi_create_typedarray()`, `(length * size_of_element) + +While calling `node_api_create_typedarray()`, `(length * size_of_element) + byte_offset` was larger than the length of given `buffer`. @@ -2578,7 +2579,7 @@ added: v9.0.0 removed: v10.0.0 --> -Used by the `N-API` when `Constructor.prototype` is not an object. +Used by the Node.js API when `Constructor.prototype` is not an object. ### `ERR_NO_LONGER_SUPPORTED` diff --git a/doc/api/index.md b/doc/api/index.md index 391873c16122c6..3d9a0a8267aa61 100644 --- a/doc/api/index.md +++ b/doc/api/index.md @@ -14,7 +14,7 @@ * [Async hooks](async_hooks.md) * [Buffer](buffer.md) * [C++ addons](addons.md) -* [C/C++ addons with N-API](n-api.md) +* [C/C++ addons with the Node.js API](node-api.md) * [C++ embedder API](embedding.md) * [Child processes](child_process.md) * [Cluster](cluster.md) diff --git a/doc/api/n-api.md b/doc/api/n-api.md deleted file mode 100644 index 1e2240d26ca409..00000000000000 --- a/doc/api/n-api.md +++ /dev/null @@ -1,6080 +0,0 @@ -# N-API - - - - -> Stability: 2 - Stable - -N-API (pronounced N as in the letter, followed by API) -is an API for building native Addons. It is independent from -the underlying JavaScript runtime (for example, V8) and is maintained as part of -Node.js itself. This API will be Application Binary Interface (ABI) stable -across versions of Node.js. It is intended to insulate Addons from -changes in the underlying JavaScript engine and allow modules -compiled for one major version to run on later major versions of Node.js without -recompilation. The [ABI Stability][] guide provides a more in-depth explanation. - -Addons are built/packaged with the same approach/tools outlined in the section -titled [C++ Addons][]. The only difference is the set of APIs that are used by -the native code. Instead of using the V8 or [Native Abstractions for Node.js][] -APIs, the functions available in the N-API are used. - -APIs exposed by N-API are generally used to create and manipulate -JavaScript values. Concepts and operations generally map to ideas specified -in the ECMA-262 Language Specification. The APIs have the following -properties: - -* All N-API calls return a status code of type `napi_status`. This - status indicates whether the API call succeeded or failed. -* The API's return value is passed via an out parameter. -* All JavaScript values are abstracted behind an opaque type named - `napi_value`. -* In case of an error status code, additional information can be obtained - using `napi_get_last_error_info`. More information can be found in the error - handling section [Error handling][]. - -The N-API is a C API that ensures ABI stability across Node.js versions -and different compiler levels. A C++ API can be easier to use. -To support using C++, the project maintains a -C++ wrapper module called [`node-addon-api`][]. -This wrapper provides an inlineable C++ API. Binaries built -with `node-addon-api` will depend on the symbols for the N-API C-based -functions exported by Node.js. `node-addon-api` is a more -efficient way to write code that calls N-API. Take, for example, the -following `node-addon-api` code. The first section shows the -`node-addon-api` code and the second section shows what actually gets -used in the addon. - -```cpp -Object obj = Object::New(env); -obj["foo"] = String::New(env, "bar"); -``` - -```cpp -napi_status status; -napi_value object, string; -status = napi_create_object(env, &object); -if (status != napi_ok) { - napi_throw_error(env, ...); - return; -} - -status = napi_create_string_utf8(env, "bar", NAPI_AUTO_LENGTH, &string); -if (status != napi_ok) { - napi_throw_error(env, ...); - return; -} - -status = napi_set_named_property(env, object, "foo", string); -if (status != napi_ok) { - napi_throw_error(env, ...); - return; -} -``` - -The end result is that the addon only uses the exported C APIs. As a result, -it still gets the benefits of the ABI stability provided by the C API. - -When using `node-addon-api` instead of the C APIs, start with the API [docs][] -for `node-addon-api`. - -The [N-API Resource](https://nodejs.github.io/node-addon-examples/) offers an -excellent orientation and tips for developers just getting started with N-API -and `node-addon-api`. - -## Implications of ABI stability - -Although N-API provides an ABI stability guarantee, other parts of Node.js do -not, and any external libraries used from the addon may not. In particular, -none of the following APIs provide an ABI stability guarantee across major -versions: - -* the Node.js C++ APIs available via any of - - ```cpp - #include - #include - #include - #include - ``` - -* the libuv APIs which are also included with Node.js and available via - - ```cpp - #include - ``` - -* the V8 API available via - - ```cpp - #include - ``` - -Thus, for an addon to remain ABI-compatible across Node.js major versions, it -must use N-API exclusively by restricting itself to using - -```c -#include -``` - -and by checking, for all external libraries that it uses, that the external -library makes ABI stability guarantees similar to N-API. - -## Building - -Unlike modules written in JavaScript, developing and deploying Node.js -native addons using N-API requires an additional set of tools. Besides the -basic tools required to develop for Node.js, the native addon developer -requires a toolchain that can compile C and C++ code into a binary. In -addition, depending upon how the native addon is deployed, the *user* of -the native addon will also need to have a C/C++ toolchain installed. - -For Linux developers, the necessary C/C++ toolchain packages are readily -available. [GCC][] is widely used in the Node.js community to build and -test across a variety of platforms. For many developers, the [LLVM][] -compiler infrastructure is also a good choice. - -For Mac developers, [Xcode][] offers all the required compiler tools. -However, it is not necessary to install the entire Xcode IDE. The following -command installs the necessary toolchain: - -```bash -xcode-select --install -``` - -For Windows developers, [Visual Studio][] offers all the required compiler -tools. However, it is not necessary to install the entire Visual Studio -IDE. The following command installs the necessary toolchain: - -```bash -npm install --global windows-build-tools -``` - -The sections below describe the additional tools available for developing -and deploying Node.js native addons. - -### Build tools - -Both the tools listed here require that *users* of the native -addon have a C/C++ toolchain installed in order to successfully install -the native addon. - -#### node-gyp - -[node-gyp][] is a build system based on Google's [GYP][] tool and comes -bundled with npm. GYP, and therefore node-gyp, requires that Python be -installed. - -Historically, node-gyp has been the tool of choice for building native -addons. It has widespread adoption and documentation. However, some -developers have run into limitations in node-gyp. - -#### CMake.js - -[CMake.js][] is an alternative build system based on [CMake][]. - -CMake.js is a good choice for projects that already use CMake or for -developers affected by limitations in node-gyp. - -### Uploading precompiled binaries - -The three tools listed here permit native addon developers and maintainers -to create and upload binaries to public or private servers. These tools are -typically integrated with CI/CD build systems like [Travis CI][] and -[AppVeyor][] to build and upload binaries for a variety of platforms and -architectures. These binaries are then available for download by users who -do not need to have a C/C++ toolchain installed. - -#### node-pre-gyp - -[node-pre-gyp][] is a tool based on node-gyp that adds the ability to -upload binaries to a server of the developer's choice. node-pre-gyp has -particularly good support for uploading binaries to Amazon S3. - -#### prebuild - -[prebuild][] is a tool that supports builds using either node-gyp or -CMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild -uploads binaries only to [GitHub releases][]. prebuild is a good choice for -GitHub projects using CMake.js. - -#### prebuildify - -[prebuildify][] is a tool based on node-gyp. The advantage of prebuildify is -that the built binaries are bundled with the native module when it's -uploaded to npm. The binaries are downloaded from npm and are immediately -available to the module user when the native module is installed. - -## Usage - -In order to use the N-API functions, include the file [`node_api.h`][] which is -located in the src directory in the node development tree: - -```c -#include -``` - -This will opt into the default `NAPI_VERSION` for the given release of Node.js. -In order to ensure compatibility with specific versions of N-API, the version -can be specified explicitly when including the header: - -```c -#define NAPI_VERSION 3 -#include -``` - -This restricts the N-API surface to just the functionality that was available in -the specified (and earlier) versions. - -Some of the N-API surface is experimental and requires explicit opt-in: - -```c -#define NAPI_EXPERIMENTAL -#include -``` - -In this case the entire API surface, including any experimental APIs, will be -available to the module code. - -## N-API version matrix - -N-API versions are additive and versioned independently from Node.js. -Version 4 is an extension to version 3 in that it has all of the APIs -from version 3 with some additions. This means that it is not necessary -to recompile for new versions of Node.js which are -listed as supporting a later version. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
123
v6.xv6.14.2*
v8.xv8.6.0**v8.10.0*v8.11.2
v9.xv9.0.0*v9.3.0*v9.11.0*
≥ v10.xall releasesall releasesall releases
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4567
v10.xv10.16.0v10.17.0v10.20.0
v11.xv11.8.0
v12.xv12.0.0v12.11.0v12.17.0v12.19.0
v13.xv13.0.0v13.0.0
v14.xv14.0.0v14.0.0v14.0.0v14.12.0
- -\* N-API was experimental. - -\*\* Node.js 8.0.0 included N-API as experimental. It was released as N-API -version 1 but continued to evolve until Node.js 8.6.0. The API is different in -versions prior to Node.js 8.6.0. We recommend N-API version 3 or later. - -Each API documented for N-API will have a header named `added in:`, and APIs -which are stable will have the additional header `N-API version:`. -APIs are directly usable when using a Node.js version which supports -the N-API version shown in `N-API version:` or higher. -When using a Node.js version that does not support the -`N-API version:` listed or if there is no `N-API version:` listed, -then the API will only be available if -`#define NAPI_EXPERIMENTAL` precedes the inclusion of `node_api.h` -or `js_native_api.h`. If an API appears not to be available on -a version of Node.js which is later than the one shown in `added in:` then -this is most likely the reason for the apparent absence. - -The N-APIs associated strictly with accessing ECMAScript features from native -code can be found separately in `js_native_api.h` and `js_native_api_types.h`. -The APIs defined in these headers are included in `node_api.h` and -`node_api_types.h`. The headers are structured in this way in order to allow -implementations of N-API outside of Node.js. For those implementations the -Node.js specific APIs may not be applicable. - -The Node.js-specific parts of an addon can be separated from the code that -exposes the actual functionality to the JavaScript environment so that the -latter may be used with multiple implementations of N-API. In the example below, -`addon.c` and `addon.h` refer only to `js_native_api.h`. This ensures that -`addon.c` can be reused to compile against either the Node.js implementation of -N-API or any implementation of N-API outside of Node.js. - -`addon_node.c` is a separate file that contains the Node.js specific entry point -to the addon and which instantiates the addon by calling into `addon.c` when the -addon is loaded into a Node.js environment. - -```c -// addon.h -#ifndef _ADDON_H_ -#define _ADDON_H_ -#include -napi_value create_addon(napi_env env); -#endif // _ADDON_H_ -``` - -```c -// addon.c -#include "addon.h" - -#define NAPI_CALL(env, call) \ - do { \ - napi_status status = (call); \ - if (status != napi_ok) { \ - const napi_extended_error_info* error_info = NULL; \ - napi_get_last_error_info((env), &error_info); \ - bool is_pending; \ - napi_is_exception_pending((env), &is_pending); \ - if (!is_pending) { \ - const char* message = (error_info->error_message == NULL) \ - ? "empty error message" \ - : error_info->error_message; \ - napi_throw_error((env), NULL, message); \ - return NULL; \ - } \ - } \ - } while(0) - -static napi_value -DoSomethingUseful(napi_env env, napi_callback_info info) { - // Do something useful. - return NULL; -} - -napi_value create_addon(napi_env env) { - napi_value result; - NAPI_CALL(env, napi_create_object(env, &result)); - - napi_value exported_function; - NAPI_CALL(env, napi_create_function(env, - "doSomethingUseful", - NAPI_AUTO_LENGTH, - DoSomethingUseful, - NULL, - &exported_function)); - - NAPI_CALL(env, napi_set_named_property(env, - result, - "doSomethingUseful", - exported_function)); - - return result; -} -``` - -```c -// addon_node.c -#include -#include "addon.h" - -NAPI_MODULE_INIT() { - // This function body is expected to return a `napi_value`. - // The variables `napi_env env` and `napi_value exports` may be used within - // the body, as they are provided by the definition of `NAPI_MODULE_INIT()`. - return create_addon(env); -} -``` - -## Environment life cycle APIs - -[Section 8.7][] of the [ECMAScript Language Specification][] defines the concept -of an "Agent" as a self-contained environment in which JavaScript code runs. -Multiple such Agents may be started and terminated either concurrently or in -sequence by the process. - -A Node.js environment corresponds to an ECMAScript Agent. In the main process, -an environment is created at startup, and additional environments can be created -on separate threads to serve as [worker threads][]. When Node.js is embedded in -another application, the main thread of the application may also construct and -destroy a Node.js environment multiple times during the life cycle of the -application process such that each Node.js environment created by the -application may, in turn, during its life cycle create and destroy additional -environments as worker threads. - -From the perspective of a native addon this means that the bindings it provides -may be called multiple times, from multiple contexts, and even concurrently from -multiple threads. - -Native addons may need to allocate global state which they use during -their entire life cycle such that the state must be unique to each instance of -the addon. - -To this end, N-API provides a way to allocate data such that its life cycle is -tied to the life cycle of the Agent. - -### napi_set_instance_data - - -```c -napi_status napi_set_instance_data(napi_env env, - void* data, - napi_finalize finalize_cb, - void* finalize_hint); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] data`: The data item to make available to bindings of this instance. -* `[in] finalize_cb`: The function to call when the environment is being torn - down. The function receives `data` so that it might free it. - [`napi_finalize`][] provides more details. -* `[in] finalize_hint`: Optional hint to pass to the finalize callback during - collection. - -Returns `napi_ok` if the API succeeded. - -This API associates `data` with the currently running Agent. `data` can later -be retrieved using `napi_get_instance_data()`. Any existing data associated with -the currently running Agent which was set by means of a previous call to -`napi_set_instance_data()` will be overwritten. If a `finalize_cb` was provided -by the previous call, it will not be called. - -### napi_get_instance_data - - -```c -napi_status napi_get_instance_data(napi_env env, - void** data); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[out] data`: The data item that was previously associated with the currently - running Agent by a call to `napi_set_instance_data()`. - -Returns `napi_ok` if the API succeeded. - -This API retrieves data that was previously associated with the currently -running Agent via `napi_set_instance_data()`. If no data is set, the call will -succeed and `data` will be set to `NULL`. - -## Basic N-API data types - -N-API exposes the following fundamental datatypes as abstractions that are -consumed by the various APIs. These APIs should be treated as opaque, -introspectable only with other N-API calls. - -### napi_status - -Integral status code indicating the success or failure of a N-API call. -Currently, the following status codes are supported. - -```c -typedef enum { - napi_ok, - napi_invalid_arg, - napi_object_expected, - napi_string_expected, - napi_name_expected, - napi_function_expected, - napi_number_expected, - napi_boolean_expected, - napi_array_expected, - napi_generic_failure, - napi_pending_exception, - napi_cancelled, - napi_escape_called_twice, - napi_handle_scope_mismatch, - napi_callback_scope_mismatch, - napi_queue_full, - napi_closing, - napi_bigint_expected, - napi_date_expected, - napi_arraybuffer_expected, - napi_detachable_arraybuffer_expected, - napi_would_deadlock, /* unused */ -} napi_status; -``` - -If additional information is required upon an API returning a failed status, -it can be obtained by calling `napi_get_last_error_info`. - -### napi_extended_error_info - - -```c -typedef struct { - const char* error_message; - void* engine_reserved; - uint32_t engine_error_code; - napi_status error_code; -} napi_extended_error_info; -``` - -* `error_message`: UTF8-encoded string containing a VM-neutral description of - the error. -* `engine_reserved`: Reserved for VM-specific error details. This is currently - not implemented for any VM. -* `engine_error_code`: VM-specific error code. This is currently - not implemented for any VM. -* `error_code`: The N-API status code that originated with the last error. - -See the [Error handling][] section for additional information. - -### napi_env - -`napi_env` is used to represent a context that the underlying N-API -implementation can use to persist VM-specific state. This structure is passed -to native functions when they're invoked, and it must be passed back when -making N-API calls. Specifically, the same `napi_env` that was passed in when -the initial native function was called must be passed to any subsequent -nested N-API calls. Caching the `napi_env` for the purpose of general reuse, -and passing the `napi_env` between instances of the same addon running on -different [`Worker`][] threads is not allowed. The `napi_env` becomes invalid -when an instance of a native addon is unloaded. Notification of this event is -delivered through the callbacks given to [`napi_add_env_cleanup_hook`][] and -[`napi_set_instance_data`][]. - -### napi_value - -This is an opaque pointer that is used to represent a JavaScript value. - -### napi_threadsafe_function - - -This is an opaque pointer that represents a JavaScript function which can be -called asynchronously from multiple threads via -`napi_call_threadsafe_function()`. - -### napi_threadsafe_function_release_mode - - -A value to be given to `napi_release_threadsafe_function()` to indicate whether -the thread-safe function is to be closed immediately (`napi_tsfn_abort`) or -merely released (`napi_tsfn_release`) and thus available for subsequent use via -`napi_acquire_threadsafe_function()` and `napi_call_threadsafe_function()`. - -```c -typedef enum { - napi_tsfn_release, - napi_tsfn_abort -} napi_threadsafe_function_release_mode; -``` - -### napi_threadsafe_function_call_mode - - -A value to be given to `napi_call_threadsafe_function()` to indicate whether -the call should block whenever the queue associated with the thread-safe -function is full. - -```c -typedef enum { - napi_tsfn_nonblocking, - napi_tsfn_blocking -} napi_threadsafe_function_call_mode; -``` - -### N-API memory management types -#### napi_handle_scope - -This is an abstraction used to control and modify the lifetime of objects -created within a particular scope. In general, N-API values are created within -the context of a handle scope. When a native method is called from -JavaScript, a default handle scope will exist. If the user does not explicitly -create a new handle scope, N-API values will be created in the default handle -scope. For any invocations of code outside the execution of a native method -(for instance, during a libuv callback invocation), the module is required to -create a scope before invoking any functions that can result in the creation -of JavaScript values. - -Handle scopes are created using [`napi_open_handle_scope`][] and are destroyed -using [`napi_close_handle_scope`][]. Closing the scope can indicate to the GC -that all `napi_value`s created during the lifetime of the handle scope are no -longer referenced from the current stack frame. - -For more details, review the [Object lifetime management][]. - -#### napi_escapable_handle_scope - -Escapable handle scopes are a special type of handle scope to return values -created within a particular handle scope to a parent scope. - -#### napi_ref - -This is the abstraction to use to reference a `napi_value`. This allows for -users to manage the lifetimes of JavaScript values, including defining their -minimum lifetimes explicitly. - -For more details, review the [Object lifetime management][]. - -#### napi_type_tag - - -A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID -with which JavaScript objects can be "tagged" in order to ensure that they are -of a certain type. This is a stronger check than [`napi_instanceof`][], because -the latter can report a false positive if the object's prototype has been -manipulated. Type-tagging is most useful in conjunction with [`napi_wrap`][] -because it ensures that the pointer retrieved from a wrapped object can be -safely cast to the native type corresponding to the type tag that had been -previously applied to the JavaScript object. - -```c -typedef struct { - uint64_t lower; - uint64_t upper; -} napi_type_tag; -``` - -#### napi_async_cleanup_hook_handle - - -An opaque value returned by [`napi_add_async_cleanup_hook`][]. It must be passed -to [`napi_remove_async_cleanup_hook`][] when the chain of asynchronous cleanup -events completes. - -### N-API callback types - -#### napi_callback_info - -Opaque datatype that is passed to a callback function. It can be used for -getting additional information about the context in which the callback was -invoked. - -#### napi_callback - -Function pointer type for user-provided native functions which are to be -exposed to JavaScript via N-API. Callback functions should satisfy the -following signature: - -```c -typedef napi_value (*napi_callback)(napi_env, napi_callback_info); -``` - -Unless for reasons discussed in [Object Lifetime Management][], creating a -handle and/or callback scope inside a `napi_callback` is not necessary. - -#### napi_finalize - -Function pointer type for add-on provided functions that allow the user to be -notified when externally-owned data is ready to be cleaned up because the -object with which it was associated with, has been garbage-collected. The user -must provide a function satisfying the following signature which would get -called upon the object's collection. Currently, `napi_finalize` can be used for -finding out when objects that have external data are collected. - -```c -typedef void (*napi_finalize)(napi_env env, - void* finalize_data, - void* finalize_hint); -``` - -Unless for reasons discussed in [Object Lifetime Management][], creating a -handle and/or callback scope inside the function body is not necessary. - -#### napi_async_execute_callback - -Function pointer used with functions that support asynchronous -operations. Callback functions must satisfy the following signature: - -```c -typedef void (*napi_async_execute_callback)(napi_env env, void* data); -``` - -Implementations of this function must avoid making N-API calls that execute -JavaScript or interact with JavaScript objects. N-API calls should be in the -`napi_async_complete_callback` instead. Do not use the `napi_env` parameter as -it will likely result in execution of JavaScript. - -#### napi_async_complete_callback - -Function pointer used with functions that support asynchronous -operations. Callback functions must satisfy the following signature: - -```c -typedef void (*napi_async_complete_callback)(napi_env env, - napi_status status, - void* data); -``` - -Unless for reasons discussed in [Object Lifetime Management][], creating a -handle and/or callback scope inside the function body is not necessary. - -#### napi_threadsafe_function_call_js - - -Function pointer used with asynchronous thread-safe function calls. The callback -will be called on the main thread. Its purpose is to use a data item arriving -via the queue from one of the secondary threads to construct the parameters -necessary for a call into JavaScript, usually via `napi_call_function`, and then -make the call into JavaScript. - -The data arriving from the secondary thread via the queue is given in the `data` -parameter and the JavaScript function to call is given in the `js_callback` -parameter. - -N-API sets up the environment prior to calling this callback, so it is -sufficient to call the JavaScript function via `napi_call_function` rather than -via `napi_make_callback`. - -Callback functions must satisfy the following signature: - -```c -typedef void (*napi_threadsafe_function_call_js)(napi_env env, - napi_value js_callback, - void* context, - void* data); -``` - -* `[in] env`: The environment to use for API calls, or `NULL` if the thread-safe - function is being torn down and `data` may need to be freed. -* `[in] js_callback`: The JavaScript function to call, or `NULL` if the - thread-safe function is being torn down and `data` may need to be freed. It - may also be `NULL` if the thread-safe function was created without - `js_callback`. -* `[in] context`: The optional data with which the thread-safe function was - created. -* `[in] data`: Data created by the secondary thread. It is the responsibility of - the callback to convert this native data to JavaScript values (with N-API - functions) that can be passed as parameters when `js_callback` is invoked. - This pointer is managed entirely by the threads and this callback. Thus this - callback should free the data. - -Unless for reasons discussed in [Object Lifetime Management][], creating a -handle and/or callback scope inside the function body is not necessary. - -#### napi_async_cleanup_hook - - -Function pointer used with [`napi_add_async_cleanup_hook`][]. It will be called -when the environment is being torn down. - -Callback functions must satisfy the following signature: - -```c -typedef void (*napi_async_cleanup_hook)(napi_async_cleanup_hook_handle handle, - void* data); -``` - -* `[in] handle`: The handle that must be passed to - [`napi_remove_async_cleanup_hook`][] after completion of the asynchronous - cleanup. -* `[in] data`: The data that was passed to [`napi_add_async_cleanup_hook`][]. - -The body of the function should initiate the asynchronous cleanup actions at the -end of which `handle` must be passed in a call to -[`napi_remove_async_cleanup_hook`][]. - -## Error handling - -N-API uses both return values and JavaScript exceptions for error handling. -The following sections explain the approach for each case. - -### Return values - -All of the N-API functions share the same error handling pattern. The -return type of all API functions is `napi_status`. - -The return value will be `napi_ok` if the request was successful and -no uncaught JavaScript exception was thrown. If an error occurred AND -an exception was thrown, the `napi_status` value for the error -will be returned. If an exception was thrown, and no error occurred, -`napi_pending_exception` will be returned. - -In cases where a return value other than `napi_ok` or -`napi_pending_exception` is returned, [`napi_is_exception_pending`][] -must be called to check if an exception is pending. -See the section on exceptions for more details. - -The full set of possible `napi_status` values is defined -in `napi_api_types.h`. - -The `napi_status` return value provides a VM-independent representation of -the error which occurred. In some cases it is useful to be able to get -more detailed information, including a string representing the error as well as -VM (engine)-specific information. - -In order to retrieve this information [`napi_get_last_error_info`][] -is provided which returns a `napi_extended_error_info` structure. -The format of the `napi_extended_error_info` structure is as follows: - - - -```c -typedef struct napi_extended_error_info { - const char* error_message; - void* engine_reserved; - uint32_t engine_error_code; - napi_status error_code; -}; -``` - -* `error_message`: Textual representation of the error that occurred. -* `engine_reserved`: Opaque handle reserved for engine use only. -* `engine_error_code`: VM specific error code. -* `error_code`: n-api status code for the last error. - -[`napi_get_last_error_info`][] returns the information for the last -N-API call that was made. - -Do not rely on the content or format of any of the extended information as it -is not subject to SemVer and may change at any time. It is intended only for -logging purposes. - -#### napi_get_last_error_info - - -```c -napi_status -napi_get_last_error_info(napi_env env, - const napi_extended_error_info** result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] result`: The `napi_extended_error_info` structure with more - information about the error. - -Returns `napi_ok` if the API succeeded. - -This API retrieves a `napi_extended_error_info` structure with information -about the last error that occurred. - -The content of the `napi_extended_error_info` returned is only valid up until -an n-api function is called on the same `env`. - -Do not rely on the content or format of any of the extended information as it -is not subject to SemVer and may change at any time. It is intended only for -logging purposes. - -This API can be called even if there is a pending JavaScript exception. - -### Exceptions - -Any N-API function call may result in a pending JavaScript exception. This is -the case for any of the API functions, even those that may not cause the -execution of JavaScript. - -If the `napi_status` returned by a function is `napi_ok` then no -exception is pending and no additional action is required. If the -`napi_status` returned is anything other than `napi_ok` or -`napi_pending_exception`, in order to try to recover and continue -instead of simply returning immediately, [`napi_is_exception_pending`][] -must be called in order to determine if an exception is pending or not. - -In many cases when an N-API function is called and an exception is -already pending, the function will return immediately with a -`napi_status` of `napi_pending_exception`. However, this is not the case -for all functions. N-API allows a subset of the functions to be -called to allow for some minimal cleanup before returning to JavaScript. -In that case, `napi_status` will reflect the status for the function. It -will not reflect previous pending exceptions. To avoid confusion, check -the error status after every function call. - -When an exception is pending one of two approaches can be employed. - -The first approach is to do any appropriate cleanup and then return so that -execution will return to JavaScript. As part of the transition back to -JavaScript, the exception will be thrown at the point in the JavaScript -code where the native method was invoked. The behavior of most N-API calls -is unspecified while an exception is pending, and many will simply return -`napi_pending_exception`, so do as little as possible and then return to -JavaScript where the exception can be handled. - -The second approach is to try to handle the exception. There will be cases -where the native code can catch the exception, take the appropriate action, -and then continue. This is only recommended in specific cases -where it is known that the exception can be safely handled. In these -cases [`napi_get_and_clear_last_exception`][] can be used to get and -clear the exception. On success, result will contain the handle to -the last JavaScript `Object` thrown. If it is determined, after -retrieving the exception, the exception cannot be handled after all -it can be re-thrown it with [`napi_throw`][] where error is the -JavaScript `Error` object to be thrown. - -The following utility functions are also available in case native code -needs to throw an exception or determine if a `napi_value` is an instance -of a JavaScript `Error` object: [`napi_throw_error`][], -[`napi_throw_type_error`][], [`napi_throw_range_error`][] and -[`napi_is_error`][]. - -The following utility functions are also available in case native -code needs to create an `Error` object: [`napi_create_error`][], -[`napi_create_type_error`][], and [`napi_create_range_error`][], -where result is the `napi_value` that refers to the newly created -JavaScript `Error` object. - -The Node.js project is adding error codes to all of the errors -generated internally. The goal is for applications to use these -error codes for all error checking. The associated error messages -will remain, but will only be meant to be used for logging and -display with the expectation that the message can change without -SemVer applying. In order to support this model with N-API, both -in internal functionality and for module specific functionality -(as its good practice), the `throw_` and `create_` functions -take an optional code parameter which is the string for the code -to be added to the error object. If the optional parameter is `NULL` -then no code will be associated with the error. If a code is provided, -the name associated with the error is also updated to be: - -```text -originalName [code] -``` - -where `originalName` is the original name associated with the error -and `code` is the code that was provided. For example, if the code -is `'ERR_ERROR_1'` and a `TypeError` is being created the name will be: - -```text -TypeError [ERR_ERROR_1] -``` - -#### napi_throw - - -```c -NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] error`: The JavaScript value to be thrown. - -Returns `napi_ok` if the API succeeded. - -This API throws the JavaScript value provided. - -#### napi_throw_error - - -```c -NAPI_EXTERN napi_status napi_throw_error(napi_env env, - const char* code, - const char* msg); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] code`: Optional error code to be set on the error. -* `[in] msg`: C string representing the text to be associated with the error. - -Returns `napi_ok` if the API succeeded. - -This API throws a JavaScript `Error` with the text provided. - -#### napi_throw_type_error - - -```c -NAPI_EXTERN napi_status napi_throw_type_error(napi_env env, - const char* code, - const char* msg); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] code`: Optional error code to be set on the error. -* `[in] msg`: C string representing the text to be associated with the error. - -Returns `napi_ok` if the API succeeded. - -This API throws a JavaScript `TypeError` with the text provided. - -#### napi_throw_range_error - - -```c -NAPI_EXTERN napi_status napi_throw_range_error(napi_env env, - const char* code, - const char* msg); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] code`: Optional error code to be set on the error. -* `[in] msg`: C string representing the text to be associated with the error. - -Returns `napi_ok` if the API succeeded. - -This API throws a JavaScript `RangeError` with the text provided. - -#### napi_is_error - - -```c -NAPI_EXTERN napi_status napi_is_error(napi_env env, - napi_value value, - bool* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The `napi_value` to be checked. -* `[out] result`: Boolean value that is set to true if `napi_value` represents - an error, false otherwise. - -Returns `napi_ok` if the API succeeded. - -This API queries a `napi_value` to check if it represents an error object. - -#### napi_create_error - - -```c -NAPI_EXTERN napi_status napi_create_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] code`: Optional `napi_value` with the string for the error code to be - associated with the error. -* `[in] msg`: `napi_value` that references a JavaScript `String` to be used as - the message for the `Error`. -* `[out] result`: `napi_value` representing the error created. - -Returns `napi_ok` if the API succeeded. - -This API returns a JavaScript `Error` with the text provided. - -#### napi_create_type_error - - -```c -NAPI_EXTERN napi_status napi_create_type_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] code`: Optional `napi_value` with the string for the error code to be - associated with the error. -* `[in] msg`: `napi_value` that references a JavaScript `String` to be used as - the message for the `Error`. -* `[out] result`: `napi_value` representing the error created. - -Returns `napi_ok` if the API succeeded. - -This API returns a JavaScript `TypeError` with the text provided. - -#### napi_create_range_error - - -```c -NAPI_EXTERN napi_status napi_create_range_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] code`: Optional `napi_value` with the string for the error code to be - associated with the error. -* `[in] msg`: `napi_value` that references a JavaScript `String` to be used as - the message for the `Error`. -* `[out] result`: `napi_value` representing the error created. - -Returns `napi_ok` if the API succeeded. - -This API returns a JavaScript `RangeError` with the text provided. - -#### napi_get_and_clear_last_exception - - -```c -napi_status napi_get_and_clear_last_exception(napi_env env, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] result`: The exception if one is pending, `NULL` otherwise. - -Returns `napi_ok` if the API succeeded. - -This API can be called even if there is a pending JavaScript exception. - -#### napi_is_exception_pending - - -```c -napi_status napi_is_exception_pending(napi_env env, bool* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] result`: Boolean value that is set to true if an exception is pending. - -Returns `napi_ok` if the API succeeded. - -This API can be called even if there is a pending JavaScript exception. - -#### napi_fatal_exception - - -```c -napi_status napi_fatal_exception(napi_env env, napi_value err); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] err`: The error that is passed to `'uncaughtException'`. - -Trigger an `'uncaughtException'` in JavaScript. Useful if an async -callback throws an exception with no way to recover. - -### Fatal errors - -In the event of an unrecoverable error in a native module, a fatal error can be -thrown to immediately terminate the process. - -#### napi_fatal_error - - -```c -NAPI_NO_RETURN void napi_fatal_error(const char* location, - size_t location_len, - const char* message, - size_t message_len); -``` - -* `[in] location`: Optional location at which the error occurred. -* `[in] location_len`: The length of the location in bytes, or - `NAPI_AUTO_LENGTH` if it is null-terminated. -* `[in] message`: The message associated with the error. -* `[in] message_len`: The length of the message in bytes, or `NAPI_AUTO_LENGTH` - if it is null-terminated. - -The function call does not return, the process will be terminated. - -This API can be called even if there is a pending JavaScript exception. - -## Object lifetime management - -As N-API calls are made, handles to objects in the heap for the underlying -VM may be returned as `napi_values`. These handles must hold the -objects 'live' until they are no longer required by the native code, -otherwise the objects could be collected before the native code was -finished using them. - -As object handles are returned they are associated with a -'scope'. The lifespan for the default scope is tied to the lifespan -of the native method call. The result is that, by default, handles -remain valid and the objects associated with these handles will be -held live for the lifespan of the native method call. - -In many cases, however, it is necessary that the handles remain valid for -either a shorter or longer lifespan than that of the native method. -The sections which follow describe the N-API functions that can be used -to change the handle lifespan from the default. - -### Making handle lifespan shorter than that of the native method -It is often necessary to make the lifespan of handles shorter than -the lifespan of a native method. For example, consider a native method -that has a loop which iterates through the elements in a large array: - -```c -for (int i = 0; i < 1000000; i++) { - napi_value result; - napi_status status = napi_get_element(env, object, i, &result); - if (status != napi_ok) { - break; - } - // do something with element -} -``` - -This would result in a large number of handles being created, consuming -substantial resources. In addition, even though the native code could only -use the most recent handle, all of the associated objects would also be -kept alive since they all share the same scope. - -To handle this case, N-API provides the ability to establish a new 'scope' to -which newly created handles will be associated. Once those handles -are no longer required, the scope can be 'closed' and any handles associated -with the scope are invalidated. The methods available to open/close scopes are -[`napi_open_handle_scope`][] and [`napi_close_handle_scope`][]. - -N-API only supports a single nested hierarchy of scopes. There is only one -active scope at any time, and all new handles will be associated with that -scope while it is active. Scopes must be closed in the reverse order from -which they are opened. In addition, all scopes created within a native method -must be closed before returning from that method. - -Taking the earlier example, adding calls to [`napi_open_handle_scope`][] and -[`napi_close_handle_scope`][] would ensure that at most a single handle -is valid throughout the execution of the loop: - -```c -for (int i = 0; i < 1000000; i++) { - napi_handle_scope scope; - napi_status status = napi_open_handle_scope(env, &scope); - if (status != napi_ok) { - break; - } - napi_value result; - status = napi_get_element(env, object, i, &result); - if (status != napi_ok) { - break; - } - // do something with element - status = napi_close_handle_scope(env, scope); - if (status != napi_ok) { - break; - } -} -``` - -When nesting scopes, there are cases where a handle from an -inner scope needs to live beyond the lifespan of that scope. N-API supports an -'escapable scope' in order to support this case. An escapable scope -allows one handle to be 'promoted' so that it 'escapes' the -current scope and the lifespan of the handle changes from the current -scope to that of the outer scope. - -The methods available to open/close escapable scopes are -[`napi_open_escapable_handle_scope`][] and -[`napi_close_escapable_handle_scope`][]. - -The request to promote a handle is made through [`napi_escape_handle`][] which -can only be called once. - -#### napi_open_handle_scope - - -```c -NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env, - napi_handle_scope* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] result`: `napi_value` representing the new scope. - -Returns `napi_ok` if the API succeeded. - -This API opens a new scope. - -#### napi_close_handle_scope - - -```c -NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env, - napi_handle_scope scope); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] scope`: `napi_value` representing the scope to be closed. - -Returns `napi_ok` if the API succeeded. - -This API closes the scope passed in. Scopes must be closed in the -reverse order from which they were created. - -This API can be called even if there is a pending JavaScript exception. - -#### napi_open_escapable_handle_scope - - -```c -NAPI_EXTERN napi_status - napi_open_escapable_handle_scope(napi_env env, - napi_handle_scope* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] result`: `napi_value` representing the new scope. - -Returns `napi_ok` if the API succeeded. - -This API opens a new scope from which one object can be promoted -to the outer scope. - -#### napi_close_escapable_handle_scope - - -```c -NAPI_EXTERN napi_status - napi_close_escapable_handle_scope(napi_env env, - napi_handle_scope scope); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] scope`: `napi_value` representing the scope to be closed. - -Returns `napi_ok` if the API succeeded. - -This API closes the scope passed in. Scopes must be closed in the -reverse order from which they were created. - -This API can be called even if there is a pending JavaScript exception. - -#### napi_escape_handle - - -```c -napi_status napi_escape_handle(napi_env env, - napi_escapable_handle_scope scope, - napi_value escapee, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] scope`: `napi_value` representing the current scope. -* `[in] escapee`: `napi_value` representing the JavaScript `Object` to be - escaped. -* `[out] result`: `napi_value` representing the handle to the escaped `Object` - in the outer scope. - -Returns `napi_ok` if the API succeeded. - -This API promotes the handle to the JavaScript object so that it is valid -for the lifetime of the outer scope. It can only be called once per scope. -If it is called more than once an error will be returned. - -This API can be called even if there is a pending JavaScript exception. - -### References to objects with a lifespan longer than that of the native method - -In some cases an addon will need to be able to create and reference objects -with a lifespan longer than that of a single native method invocation. For -example, to create a constructor and later use that constructor -in a request to creates instances, it must be possible to reference -the constructor object across many different instance creation requests. This -would not be possible with a normal handle returned as a `napi_value` as -described in the earlier section. The lifespan of a normal handle is -managed by scopes and all scopes must be closed before the end of a native -method. - -N-API provides methods to create persistent references to an object. -Each persistent reference has an associated count with a value of 0 -or higher. The count determines if the reference will keep -the corresponding object live. References with a count of 0 do not -prevent the object from being collected and are often called 'weak' -references. Any count greater than 0 will prevent the object -from being collected. - -References can be created with an initial reference count. The count can -then be modified through [`napi_reference_ref`][] and -[`napi_reference_unref`][]. If an object is collected while the count -for a reference is 0, all subsequent calls to -get the object associated with the reference [`napi_get_reference_value`][] -will return `NULL` for the returned `napi_value`. An attempt to call -[`napi_reference_ref`][] for a reference whose object has been collected -results in an error. - -References must be deleted once they are no longer required by the addon. When -a reference is deleted, it will no longer prevent the corresponding object from -being collected. Failure to delete a persistent reference results in -a 'memory leak' with both the native memory for the persistent reference and -the corresponding object on the heap being retained forever. - -There can be multiple persistent references created which refer to the same -object, each of which will either keep the object live or not based on its -individual count. - -#### napi_create_reference - - -```c -NAPI_EXTERN napi_status napi_create_reference(napi_env env, - napi_value value, - uint32_t initial_refcount, - napi_ref* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing the `Object` to which we want a - reference. -* `[in] initial_refcount`: Initial reference count for the new reference. -* `[out] result`: `napi_ref` pointing to the new reference. - -Returns `napi_ok` if the API succeeded. - -This API create a new reference with the specified reference count -to the `Object` passed in. - -#### napi_delete_reference - - -```c -NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] ref`: `napi_ref` to be deleted. - -Returns `napi_ok` if the API succeeded. - -This API deletes the reference passed in. - -This API can be called even if there is a pending JavaScript exception. - -#### napi_reference_ref - - -```c -NAPI_EXTERN napi_status napi_reference_ref(napi_env env, - napi_ref ref, - uint32_t* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] ref`: `napi_ref` for which the reference count will be incremented. -* `[out] result`: The new reference count. - -Returns `napi_ok` if the API succeeded. - -This API increments the reference count for the reference -passed in and returns the resulting reference count. - -#### napi_reference_unref - - -```c -NAPI_EXTERN napi_status napi_reference_unref(napi_env env, - napi_ref ref, - uint32_t* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] ref`: `napi_ref` for which the reference count will be decremented. -* `[out] result`: The new reference count. - -Returns `napi_ok` if the API succeeded. - -This API decrements the reference count for the reference -passed in and returns the resulting reference count. - -#### napi_get_reference_value - - -```c -NAPI_EXTERN napi_status napi_get_reference_value(napi_env env, - napi_ref ref, - napi_value* result); -``` - -the `napi_value passed` in or out of these methods is a handle to the -object to which the reference is related. - -* `[in] env`: The environment that the API is invoked under. -* `[in] ref`: `napi_ref` for which we requesting the corresponding `Object`. -* `[out] result`: The `napi_value` for the `Object` referenced by the - `napi_ref`. - -Returns `napi_ok` if the API succeeded. - -If still valid, this API returns the `napi_value` representing the -JavaScript `Object` associated with the `napi_ref`. Otherwise, result -will be `NULL`. - -### Cleanup on exit of the current Node.js instance - -While a Node.js process typically releases all its resources when exiting, -embedders of Node.js, or future Worker support, may require addons to register -clean-up hooks that will be run once the current Node.js instance exits. - -N-API provides functions for registering and un-registering such callbacks. -When those callbacks are run, all resources that are being held by the addon -should be freed up. - -#### napi_add_env_cleanup_hook - - -```c -NODE_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env, - void (*fun)(void* arg), - void* arg); -``` - -Registers `fun` as a function to be run with the `arg` parameter once the -current Node.js environment exits. - -A function can safely be specified multiple times with different -`arg` values. In that case, it will be called multiple times as well. -Providing the same `fun` and `arg` values multiple times is not allowed -and will lead the process to abort. - -The hooks will be called in reverse order, i.e. the most recently added one -will be called first. - -Removing this hook can be done by using [`napi_remove_env_cleanup_hook`][]. -Typically, that happens when the resource for which this hook was added -is being torn down anyway. - -For asynchronous cleanup, [`napi_add_async_cleanup_hook`][] is available. - -#### napi_remove_env_cleanup_hook - - -```c -NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env, - void (*fun)(void* arg), - void* arg); -``` - -Unregisters `fun` as a function to be run with the `arg` parameter once the -current Node.js environment exits. Both the argument and the function value -need to be exact matches. - -The function must have originally been registered -with `napi_add_env_cleanup_hook`, otherwise the process will abort. - -#### napi_add_async_cleanup_hook - - -> Stability: 1 - Experimental - -```c -NAPI_EXTERN napi_status napi_add_async_cleanup_hook( - napi_env env, - napi_async_cleanup_hook hook, - void* arg, - napi_async_cleanup_hook_handle* remove_handle); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] hook`: The function pointer to call at environment teardown. -* `[in] arg`: The pointer to pass to `hook` when it gets called. -* `[out] remove_handle`: Optional handle that refers to the asynchronous cleanup - hook. - -Registers `hook`, which is a function of type [`napi_async_cleanup_hook`][], as -a function to be run with the `remove_handle` and `arg` parameters once the -current Node.js environment exits. - -Unlike [`napi_add_env_cleanup_hook`][], the hook is allowed to be asynchronous. - -Otherwise, behavior generally matches that of [`napi_add_env_cleanup_hook`][]. - -If `remove_handle` is not `NULL`, an opaque value will be stored in it -that must later be passed to [`napi_remove_async_cleanup_hook`][], -regardless of whether the hook has already been invoked. -Typically, that happens when the resource for which this hook was added -is being torn down anyway. - -#### napi_remove_async_cleanup_hook - - -> Stability: 1 - Experimental - -```c -NAPI_EXTERN napi_status napi_remove_async_cleanup_hook( - napi_async_cleanup_hook_handle remove_handle); -``` - -* `[in] remove_handle`: The handle to an asynchronous cleanup hook that was - created with [`napi_add_async_cleanup_hook`][]. - -Unregisters the cleanup hook corresponding to `remove_handle`. This will prevent -the hook from being executed, unless it has already started executing. -This must be called on any `napi_async_cleanup_hook_handle` value obtained -from [`napi_add_async_cleanup_hook`][]. - -## Module registration -N-API modules are registered in a manner similar to other modules -except that instead of using the `NODE_MODULE` macro the following -is used: - -```c -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) -``` - -The next difference is the signature for the `Init` method. For a N-API -module it is as follows: - -```c -napi_value Init(napi_env env, napi_value exports); -``` - -The return value from `Init` is treated as the `exports` object for the module. -The `Init` method is passed an empty object via the `exports` parameter as a -convenience. If `Init` returns `NULL`, the parameter passed as `exports` is -exported by the module. N-API modules cannot modify the `module` object but can -specify anything as the `exports` property of the module. - -To add the method `hello` as a function so that it can be called as a method -provided by the addon: - -```c -napi_value Init(napi_env env, napi_value exports) { - napi_status status; - napi_property_descriptor desc = { - "hello", - NULL, - Method, - NULL, - NULL, - NULL, - napi_writable | napi_enumerable | napi_configurable, - NULL - }; - status = napi_define_properties(env, exports, 1, &desc); - if (status != napi_ok) return NULL; - return exports; -} -``` - -To set a function to be returned by the `require()` for the addon: - -```c -napi_value Init(napi_env env, napi_value exports) { - napi_value method; - napi_status status; - status = napi_create_function(env, "exports", NAPI_AUTO_LENGTH, Method, NULL, &method); - if (status != napi_ok) return NULL; - return method; -} -``` - -To define a class so that new instances can be created (often used with -[Object wrap][]): - -```c -// NOTE: partial example, not all referenced code is included -napi_value Init(napi_env env, napi_value exports) { - napi_status status; - napi_property_descriptor properties[] = { - { "value", NULL, NULL, GetValue, SetValue, NULL, napi_writable | napi_configurable, NULL }, - DECLARE_NAPI_METHOD("plusOne", PlusOne), - DECLARE_NAPI_METHOD("multiply", Multiply), - }; - - napi_value cons; - status = - napi_define_class(env, "MyObject", New, NULL, 3, properties, &cons); - if (status != napi_ok) return NULL; - - status = napi_create_reference(env, cons, 1, &constructor); - if (status != napi_ok) return NULL; - - status = napi_set_named_property(env, exports, "MyObject", cons); - if (status != napi_ok) return NULL; - - return exports; -} -``` - -You can also use the `NAPI_MODULE_INIT` macro, which acts as a shorthand -for `NAPI_MODULE` and defining an `Init` function: - -```c -NAPI_MODULE_INIT() { - napi_value answer; - napi_status result; - - status = napi_create_int64(env, 42, &answer); - if (status != napi_ok) return NULL; - - status = napi_set_named_property(env, exports, "answer", answer); - if (status != napi_ok) return NULL; - - return exports; -} -``` - -All N-API addons are context-aware, meaning they may be loaded multiple -times. There are a few design considerations when declaring such a module. -The documentation on [context-aware addons][] provides more details. - -The variables `env` and `exports` will be available inside the function body -following the macro invocation. - -For more details on setting properties on objects, see the section on -[Working with JavaScript properties][]. - -For more details on building addon modules in general, refer to the existing -API. - -## Working with JavaScript values -N-API exposes a set of APIs to create all types of JavaScript values. -Some of these types are documented under [Section 6][] -of the [ECMAScript Language Specification][]. - -Fundamentally, these APIs are used to do one of the following: - -1. Create a new JavaScript object -2. Convert from a primitive C type to an N-API value -3. Convert from N-API value to a primitive C type -4. Get global instances including `undefined` and `null` - -N-API values are represented by the type `napi_value`. -Any N-API call that requires a JavaScript value takes in a `napi_value`. -In some cases, the API does check the type of the `napi_value` up-front. -However, for better performance, it's better for the caller to make sure that -the `napi_value` in question is of the JavaScript type expected by the API. - -### Enum types -#### napi_key_collection_mode - - -```c -typedef enum { - napi_key_include_prototypes, - napi_key_own_only -} napi_key_collection_mode; -``` - -Describes the `Keys/Properties` filter enums: - -`napi_key_collection_mode` limits the range of collected properties. - -`napi_key_own_only` limits the collected properties to the given -object only. `napi_key_include_prototypes` will include all keys -of the objects's prototype chain as well. - -#### napi_key_filter - - -```c -typedef enum { - napi_key_all_properties = 0, - napi_key_writable = 1, - napi_key_enumerable = 1 << 1, - napi_key_configurable = 1 << 2, - napi_key_skip_strings = 1 << 3, - napi_key_skip_symbols = 1 << 4 -} napi_key_filter; -``` - -Property filter bits. They can be or'ed to build a composite filter. - -#### napi_key_conversion - - -```c -typedef enum { - napi_key_keep_numbers, - napi_key_numbers_to_strings -} napi_key_conversion; -``` - -`napi_key_numbers_to_strings` will convert integer indices to -strings. `napi_key_keep_numbers` will return numbers for integer -indices. - -#### napi_valuetype - -```c -typedef enum { - // ES6 types (corresponds to typeof) - napi_undefined, - napi_null, - napi_boolean, - napi_number, - napi_string, - napi_symbol, - napi_object, - napi_function, - napi_external, - napi_bigint, -} napi_valuetype; -``` - -Describes the type of a `napi_value`. This generally corresponds to the types -described in [Section 6.1][] of the ECMAScript Language Specification. -In addition to types in that section, `napi_valuetype` can also represent -`Function`s and `Object`s with external data. - -A JavaScript value of type `napi_external` appears in JavaScript as a plain -object such that no properties can be set on it, and no prototype. - -#### napi_typedarray_type - -```c -typedef enum { - napi_int8_array, - napi_uint8_array, - napi_uint8_clamped_array, - napi_int16_array, - napi_uint16_array, - napi_int32_array, - napi_uint32_array, - napi_float32_array, - napi_float64_array, - napi_bigint64_array, - napi_biguint64_array, -} napi_typedarray_type; -``` - -This represents the underlying binary scalar datatype of the `TypedArray`. -Elements of this enum correspond to -[Section 22.2][] of the [ECMAScript Language Specification][]. - -### Object creation functions -#### napi_create_array - - -```c -napi_status napi_create_array(napi_env env, napi_value* result) -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[out] result`: A `napi_value` representing a JavaScript `Array`. - -Returns `napi_ok` if the API succeeded. - -This API returns an N-API value corresponding to a JavaScript `Array` type. -JavaScript arrays are described in -[Section 22.1][] of the ECMAScript Language Specification. - -#### napi_create_array_with_length - - -```c -napi_status napi_create_array_with_length(napi_env env, - size_t length, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] length`: The initial length of the `Array`. -* `[out] result`: A `napi_value` representing a JavaScript `Array`. - -Returns `napi_ok` if the API succeeded. - -This API returns an N-API value corresponding to a JavaScript `Array` type. -The `Array`'s length property is set to the passed-in length parameter. -However, the underlying buffer is not guaranteed to be pre-allocated by the VM -when the array is created. That behavior is left to the underlying VM -implementation. If the buffer must be a contiguous block of memory that can be -directly read and/or written via C, consider using -[`napi_create_external_arraybuffer`][]. - -JavaScript arrays are described in -[Section 22.1][] of the ECMAScript Language Specification. - -#### napi_create_arraybuffer - - -```c -napi_status napi_create_arraybuffer(napi_env env, - size_t byte_length, - void** data, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] length`: The length in bytes of the array buffer to create. -* `[out] data`: Pointer to the underlying byte buffer of the `ArrayBuffer`. -* `[out] result`: A `napi_value` representing a JavaScript `ArrayBuffer`. - -Returns `napi_ok` if the API succeeded. - -This API returns an N-API value corresponding to a JavaScript `ArrayBuffer`. -`ArrayBuffer`s are used to represent fixed-length binary data buffers. They are -normally used as a backing-buffer for `TypedArray` objects. -The `ArrayBuffer` allocated will have an underlying byte buffer whose size is -determined by the `length` parameter that's passed in. -The underlying buffer is optionally returned back to the caller in case the -caller wants to directly manipulate the buffer. This buffer can only be -written to directly from native code. To write to this buffer from JavaScript, -a typed array or `DataView` object would need to be created. - -JavaScript `ArrayBuffer` objects are described in -[Section 24.1][] of the ECMAScript Language Specification. - -#### napi_create_buffer - - -```c -napi_status napi_create_buffer(napi_env env, - size_t size, - void** data, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] size`: Size in bytes of the underlying buffer. -* `[out] data`: Raw pointer to the underlying buffer. -* `[out] result`: A `napi_value` representing a `node::Buffer`. - -Returns `napi_ok` if the API succeeded. - -This API allocates a `node::Buffer` object. While this is still a -fully-supported data structure, in most cases using a `TypedArray` will suffice. - -#### napi_create_buffer_copy - - -```c -napi_status napi_create_buffer_copy(napi_env env, - size_t length, - const void* data, - void** result_data, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] size`: Size in bytes of the input buffer (should be the same as the size - of the new buffer). -* `[in] data`: Raw pointer to the underlying buffer to copy from. -* `[out] result_data`: Pointer to the new `Buffer`'s underlying data buffer. -* `[out] result`: A `napi_value` representing a `node::Buffer`. - -Returns `napi_ok` if the API succeeded. - -This API allocates a `node::Buffer` object and initializes it with data copied -from the passed-in buffer. While this is still a fully-supported data -structure, in most cases using a `TypedArray` will suffice. - -#### napi_create_date - - -```c -napi_status napi_create_date(napi_env env, - double time, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] time`: ECMAScript time value in milliseconds since 01 January, 1970 UTC. -* `[out] result`: A `napi_value` representing a JavaScript `Date`. - -Returns `napi_ok` if the API succeeded. - -This API does not observe leap seconds; they are ignored, as -ECMAScript aligns with POSIX time specification. - -This API allocates a JavaScript `Date` object. - -JavaScript `Date` objects are described in -[Section 20.3][] of the ECMAScript Language Specification. - -#### napi_create_external - - -```c -napi_status napi_create_external(napi_env env, - void* data, - napi_finalize finalize_cb, - void* finalize_hint, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] data`: Raw pointer to the external data. -* `[in] finalize_cb`: Optional callback to call when the external value is being - collected. [`napi_finalize`][] provides more details. -* `[in] finalize_hint`: Optional hint to pass to the finalize callback during - collection. -* `[out] result`: A `napi_value` representing an external value. - -Returns `napi_ok` if the API succeeded. - -This API allocates a JavaScript value with external data attached to it. This -is used to pass external data through JavaScript code, so it can be retrieved -later by native code using [`napi_get_value_external`][]. - -The API adds a `napi_finalize` callback which will be called when the JavaScript -object just created is ready for garbage collection. It is similar to -`napi_wrap()` except that: - -* the native data cannot be retrieved later using `napi_unwrap()`, -* nor can it be removed later using `napi_remove_wrap()`, and -* the object created by the API can be used with `napi_wrap()`. - -The created value is not an object, and therefore does not support additional -properties. It is considered a distinct value type: calling `napi_typeof()` with -an external value yields `napi_external`. - -#### napi_create_external_arraybuffer - - -```c -napi_status -napi_create_external_arraybuffer(napi_env env, - void* external_data, - size_t byte_length, - napi_finalize finalize_cb, - void* finalize_hint, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] external_data`: Pointer to the underlying byte buffer of the - `ArrayBuffer`. -* `[in] byte_length`: The length in bytes of the underlying buffer. -* `[in] finalize_cb`: Optional callback to call when the `ArrayBuffer` is being - collected. [`napi_finalize`][] provides more details. -* `[in] finalize_hint`: Optional hint to pass to the finalize callback during - collection. -* `[out] result`: A `napi_value` representing a JavaScript `ArrayBuffer`. - -Returns `napi_ok` if the API succeeded. - -This API returns an N-API value corresponding to a JavaScript `ArrayBuffer`. -The underlying byte buffer of the `ArrayBuffer` is externally allocated and -managed. The caller must ensure that the byte buffer remains valid until the -finalize callback is called. - -The API adds a `napi_finalize` callback which will be called when the JavaScript -object just created is ready for garbage collection. It is similar to -`napi_wrap()` except that: - -* the native data cannot be retrieved later using `napi_unwrap()`, -* nor can it be removed later using `napi_remove_wrap()`, and -* the object created by the API can be used with `napi_wrap()`. - -JavaScript `ArrayBuffer`s are described in -[Section 24.1][] of the ECMAScript Language Specification. - -#### napi_create_external_buffer - - -```c -napi_status napi_create_external_buffer(napi_env env, - size_t length, - void* data, - napi_finalize finalize_cb, - void* finalize_hint, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] length`: Size in bytes of the input buffer (should be the same as the - size of the new buffer). -* `[in] data`: Raw pointer to the underlying buffer to expose to JavaScript. -* `[in] finalize_cb`: Optional callback to call when the `ArrayBuffer` is being - collected. [`napi_finalize`][] provides more details. -* `[in] finalize_hint`: Optional hint to pass to the finalize callback during - collection. -* `[out] result`: A `napi_value` representing a `node::Buffer`. - -Returns `napi_ok` if the API succeeded. - -This API allocates a `node::Buffer` object and initializes it with data -backed by the passed in buffer. While this is still a fully-supported data -structure, in most cases using a `TypedArray` will suffice. - -The API adds a `napi_finalize` callback which will be called when the JavaScript -object just created is ready for garbage collection. It is similar to -`napi_wrap()` except that: - -* the native data cannot be retrieved later using `napi_unwrap()`, -* nor can it be removed later using `napi_remove_wrap()`, and -* the object created by the API can be used with `napi_wrap()`. - -For Node.js >=4 `Buffers` are `Uint8Array`s. - -#### napi_create_object - - -```c -napi_status napi_create_object(napi_env env, napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] result`: A `napi_value` representing a JavaScript `Object`. - -Returns `napi_ok` if the API succeeded. - -This API allocates a default JavaScript `Object`. -It is the equivalent of doing `new Object()` in JavaScript. - -The JavaScript `Object` type is described in [Section 6.1.7][] of the -ECMAScript Language Specification. - -#### napi_create_symbol - - -```c -napi_status napi_create_symbol(napi_env env, - napi_value description, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] description`: Optional `napi_value` which refers to a JavaScript - `String` to be set as the description for the symbol. -* `[out] result`: A `napi_value` representing a JavaScript `Symbol`. - -Returns `napi_ok` if the API succeeded. - -This API creates a JavaScript `Symbol` object from a UTF8-encoded C string. - -The JavaScript `Symbol` type is described in [Section 19.4][] -of the ECMAScript Language Specification. - -#### napi_create_typedarray - - -```c -napi_status napi_create_typedarray(napi_env env, - napi_typedarray_type type, - size_t length, - napi_value arraybuffer, - size_t byte_offset, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] type`: Scalar datatype of the elements within the `TypedArray`. -* `[in] length`: Number of elements in the `TypedArray`. -* `[in] arraybuffer`: `ArrayBuffer` underlying the typed array. -* `[in] byte_offset`: The byte offset within the `ArrayBuffer` from which to - start projecting the `TypedArray`. -* `[out] result`: A `napi_value` representing a JavaScript `TypedArray`. - -Returns `napi_ok` if the API succeeded. - -This API creates a JavaScript `TypedArray` object over an existing -`ArrayBuffer`. `TypedArray` objects provide an array-like view over an -underlying data buffer where each element has the same underlying binary scalar -datatype. - -It's required that `(length * size_of_element) + byte_offset` should -be <= the size in bytes of the array passed in. If not, a `RangeError` exception -is raised. - -JavaScript `TypedArray` objects are described in -[Section 22.2][] of the ECMAScript Language Specification. - -#### napi_create_dataview - - -```c -napi_status napi_create_dataview(napi_env env, - size_t byte_length, - napi_value arraybuffer, - size_t byte_offset, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] length`: Number of elements in the `DataView`. -* `[in] arraybuffer`: `ArrayBuffer` underlying the `DataView`. -* `[in] byte_offset`: The byte offset within the `ArrayBuffer` from which to - start projecting the `DataView`. -* `[out] result`: A `napi_value` representing a JavaScript `DataView`. - -Returns `napi_ok` if the API succeeded. - -This API creates a JavaScript `DataView` object over an existing `ArrayBuffer`. -`DataView` objects provide an array-like view over an underlying data buffer, -but one which allows items of different size and type in the `ArrayBuffer`. - -It is required that `byte_length + byte_offset` is less than or equal to the -size in bytes of the array passed in. If not, a `RangeError` exception is -raised. - -JavaScript `DataView` objects are described in -[Section 24.3][] of the ECMAScript Language Specification. - -### Functions to convert from C types to N-API -#### napi_create_int32 - - -```c -napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: Integer value to be represented in JavaScript. -* `[out] result`: A `napi_value` representing a JavaScript `Number`. - -Returns `napi_ok` if the API succeeded. - -This API is used to convert from the C `int32_t` type to the JavaScript -`Number` type. - -The JavaScript `Number` type is described in -[Section 6.1.6][] of the ECMAScript Language Specification. - -#### napi_create_uint32 - - -```c -napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: Unsigned integer value to be represented in JavaScript. -* `[out] result`: A `napi_value` representing a JavaScript `Number`. - -Returns `napi_ok` if the API succeeded. - -This API is used to convert from the C `uint32_t` type to the JavaScript -`Number` type. - -The JavaScript `Number` type is described in -[Section 6.1.6][] of the ECMAScript Language Specification. - -#### napi_create_int64 - - -```c -napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: Integer value to be represented in JavaScript. -* `[out] result`: A `napi_value` representing a JavaScript `Number`. - -Returns `napi_ok` if the API succeeded. - -This API is used to convert from the C `int64_t` type to the JavaScript -`Number` type. - -The JavaScript `Number` type is described in [Section 6.1.6][] -of the ECMAScript Language Specification. Note the complete range of `int64_t` -cannot be represented with full precision in JavaScript. Integer values -outside the range of [`Number.MIN_SAFE_INTEGER`][] `-(2**53 - 1)` - -[`Number.MAX_SAFE_INTEGER`][] `(2**53 - 1)` will lose precision. - -#### napi_create_double - - -```c -napi_status napi_create_double(napi_env env, double value, napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: Double-precision value to be represented in JavaScript. -* `[out] result`: A `napi_value` representing a JavaScript `Number`. - -Returns `napi_ok` if the API succeeded. - -This API is used to convert from the C `double` type to the JavaScript -`Number` type. - -The JavaScript `Number` type is described in -[Section 6.1.6][] of the ECMAScript Language Specification. - -#### napi_create_bigint_int64 - - -```c -napi_status napi_create_bigint_int64(napi_env env, - int64_t value, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: Integer value to be represented in JavaScript. -* `[out] result`: A `napi_value` representing a JavaScript `BigInt`. - -Returns `napi_ok` if the API succeeded. - -This API converts the C `int64_t` type to the JavaScript `BigInt` type. - -#### napi_create_bigint_uint64 - - -```c -napi_status napi_create_bigint_uint64(napi_env env, - uint64_t value, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: Unsigned integer value to be represented in JavaScript. -* `[out] result`: A `napi_value` representing a JavaScript `BigInt`. - -Returns `napi_ok` if the API succeeded. - -This API converts the C `uint64_t` type to the JavaScript `BigInt` type. - -#### napi_create_bigint_words - - -```c -napi_status napi_create_bigint_words(napi_env env, - int sign_bit, - size_t word_count, - const uint64_t* words, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] sign_bit`: Determines if the resulting `BigInt` will be positive or - negative. -* `[in] word_count`: The length of the `words` array. -* `[in] words`: An array of `uint64_t` little-endian 64-bit words. -* `[out] result`: A `napi_value` representing a JavaScript `BigInt`. - -Returns `napi_ok` if the API succeeded. - -This API converts an array of unsigned 64-bit words into a single `BigInt` -value. - -The resulting `BigInt` is calculated as: (–1)`sign_bit` (`words[0]` -× (264)0 + `words[1]` × (264)1 + …) - -#### napi_create_string_latin1 - - -```c -napi_status napi_create_string_latin1(napi_env env, - const char* str, - size_t length, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] str`: Character buffer representing an ISO-8859-1-encoded string. -* `[in] length`: The length of the string in bytes, or `NAPI_AUTO_LENGTH` if it - is null-terminated. -* `[out] result`: A `napi_value` representing a JavaScript `String`. - -Returns `napi_ok` if the API succeeded. - -This API creates a JavaScript `String` object from an ISO-8859-1-encoded C -string. The native string is copied. - -The JavaScript `String` type is described in -[Section 6.1.4][] of the ECMAScript Language Specification. - -#### napi_create_string_utf16 - - -```c -napi_status napi_create_string_utf16(napi_env env, - const char16_t* str, - size_t length, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] str`: Character buffer representing a UTF16-LE-encoded string. -* `[in] length`: The length of the string in two-byte code units, or - `NAPI_AUTO_LENGTH` if it is null-terminated. -* `[out] result`: A `napi_value` representing a JavaScript `String`. - -Returns `napi_ok` if the API succeeded. - -This API creates a JavaScript `String` object from a UTF16-LE-encoded C string. -The native string is copied. - -The JavaScript `String` type is described in -[Section 6.1.4][] of the ECMAScript Language Specification. - -#### napi_create_string_utf8 - - -```c -napi_status napi_create_string_utf8(napi_env env, - const char* str, - size_t length, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] str`: Character buffer representing a UTF8-encoded string. -* `[in] length`: The length of the string in bytes, or `NAPI_AUTO_LENGTH` if it - is null-terminated. -* `[out] result`: A `napi_value` representing a JavaScript `String`. - -Returns `napi_ok` if the API succeeded. - -This API creates a JavaScript `String` object from a UTF8-encoded C string. -The native string is copied. - -The JavaScript `String` type is described in -[Section 6.1.4][] of the ECMAScript Language Specification. - -### Functions to convert from N-API to C types -#### napi_get_array_length - - -```c -napi_status napi_get_array_length(napi_env env, - napi_value value, - uint32_t* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing the JavaScript `Array` whose length is - being queried. -* `[out] result`: `uint32` representing length of the array. - -Returns `napi_ok` if the API succeeded. - -This API returns the length of an array. - -`Array` length is described in [Section 22.1.4.1][] of the ECMAScript Language -Specification. - -#### napi_get_arraybuffer_info - - -```c -napi_status napi_get_arraybuffer_info(napi_env env, - napi_value arraybuffer, - void** data, - size_t* byte_length) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] arraybuffer`: `napi_value` representing the `ArrayBuffer` being queried. -* `[out] data`: The underlying data buffer of the `ArrayBuffer`. If byte_length - is `0`, this may be `NULL` or any other pointer value. -* `[out] byte_length`: Length in bytes of the underlying data buffer. - -Returns `napi_ok` if the API succeeded. - -This API is used to retrieve the underlying data buffer of an `ArrayBuffer` and -its length. - -*WARNING*: Use caution while using this API. The lifetime of the underlying data -buffer is managed by the `ArrayBuffer` even after it's returned. A -possible safe way to use this API is in conjunction with -[`napi_create_reference`][], which can be used to guarantee control over the -lifetime of the `ArrayBuffer`. It's also safe to use the returned data buffer -within the same callback as long as there are no calls to other APIs that might -trigger a GC. - -#### napi_get_buffer_info - - -```c -napi_status napi_get_buffer_info(napi_env env, - napi_value value, - void** data, - size_t* length) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing the `node::Buffer` being queried. -* `[out] data`: The underlying data buffer of the `node::Buffer`. - If length is `0`, this may be `NULL` or any other pointer value. -* `[out] length`: Length in bytes of the underlying data buffer. - -Returns `napi_ok` if the API succeeded. - -This API is used to retrieve the underlying data buffer of a `node::Buffer` -and its length. - -*Warning*: Use caution while using this API since the underlying data buffer's -lifetime is not guaranteed if it's managed by the VM. - -#### napi_get_prototype - - -```c -napi_status napi_get_prototype(napi_env env, - napi_value object, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] object`: `napi_value` representing JavaScript `Object` whose prototype - to return. This returns the equivalent of `Object.getPrototypeOf` (which is - not the same as the function's `prototype` property). -* `[out] result`: `napi_value` representing prototype of the given object. - -Returns `napi_ok` if the API succeeded. - -#### napi_get_typedarray_info - - -```c -napi_status napi_get_typedarray_info(napi_env env, - napi_value typedarray, - napi_typedarray_type* type, - size_t* length, - void** data, - napi_value* arraybuffer, - size_t* byte_offset) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] typedarray`: `napi_value` representing the `TypedArray` whose - properties to query. -* `[out] type`: Scalar datatype of the elements within the `TypedArray`. -* `[out] length`: The number of elements in the `TypedArray`. -* `[out] data`: The data buffer underlying the `TypedArray` adjusted by - the `byte_offset` value so that it points to the first element in the - `TypedArray`. If the length of the array is `0`, this may be `NULL` or - any other pointer value. -* `[out] arraybuffer`: The `ArrayBuffer` underlying the `TypedArray`. -* `[out] byte_offset`: The byte offset within the underlying native array - at which the first element of the arrays is located. The value for the data - parameter has already been adjusted so that data points to the first element - in the array. Therefore, the first byte of the native array would be at - `data - byte_offset`. - -Returns `napi_ok` if the API succeeded. - -This API returns various properties of a typed array. - -*Warning*: Use caution while using this API since the underlying data buffer -is managed by the VM. - -#### napi_get_dataview_info - - -```c -napi_status napi_get_dataview_info(napi_env env, - napi_value dataview, - size_t* byte_length, - void** data, - napi_value* arraybuffer, - size_t* byte_offset) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] dataview`: `napi_value` representing the `DataView` whose - properties to query. -* `[out] byte_length`: `Number` of bytes in the `DataView`. -* `[out] data`: The data buffer underlying the `DataView`. - If byte_length is `0`, this may be `NULL` or any other pointer value. -* `[out] arraybuffer`: `ArrayBuffer` underlying the `DataView`. -* `[out] byte_offset`: The byte offset within the data buffer from which - to start projecting the `DataView`. - -Returns `napi_ok` if the API succeeded. - -This API returns various properties of a `DataView`. - -#### napi_get_date_value - - -```c -napi_status napi_get_date_value(napi_env env, - napi_value value, - double* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing a JavaScript `Date`. -* `[out] result`: Time value as a `double` represented as milliseconds since - midnight at the beginning of 01 January, 1970 UTC. - -This API does not observe leap seconds; they are ignored, as -ECMAScript aligns with POSIX time specification. - -Returns `napi_ok` if the API succeeded. If a non-date `napi_value` is passed -in it returns `napi_date_expected`. - -This API returns the C double primitive of time value for the given JavaScript -`Date`. - -#### napi_get_value_bool - - -```c -napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing JavaScript `Boolean`. -* `[out] result`: C boolean primitive equivalent of the given JavaScript - `Boolean`. - -Returns `napi_ok` if the API succeeded. If a non-boolean `napi_value` is -passed in it returns `napi_boolean_expected`. - -This API returns the C boolean primitive equivalent of the given JavaScript -`Boolean`. - -#### napi_get_value_double - - -```c -napi_status napi_get_value_double(napi_env env, - napi_value value, - double* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing JavaScript `Number`. -* `[out] result`: C double primitive equivalent of the given JavaScript - `Number`. - -Returns `napi_ok` if the API succeeded. If a non-number `napi_value` is passed -in it returns `napi_number_expected`. - -This API returns the C double primitive equivalent of the given JavaScript -`Number`. - -#### napi_get_value_bigint_int64 - - -```c -napi_status napi_get_value_bigint_int64(napi_env env, - napi_value value, - int64_t* result, - bool* lossless); -``` - -* `[in] env`: The environment that the API is invoked under -* `[in] value`: `napi_value` representing JavaScript `BigInt`. -* `[out] result`: C `int64_t` primitive equivalent of the given JavaScript - `BigInt`. -* `[out] lossless`: Indicates whether the `BigInt` value was converted - losslessly. - -Returns `napi_ok` if the API succeeded. If a non-`BigInt` is passed in it -returns `napi_bigint_expected`. - -This API returns the C `int64_t` primitive equivalent of the given JavaScript -`BigInt`. If needed it will truncate the value, setting `lossless` to `false`. - -#### napi_get_value_bigint_uint64 - - -```c -napi_status napi_get_value_bigint_uint64(napi_env env, - napi_value value, - uint64_t* result, - bool* lossless); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing JavaScript `BigInt`. -* `[out] result`: C `uint64_t` primitive equivalent of the given JavaScript - `BigInt`. -* `[out] lossless`: Indicates whether the `BigInt` value was converted - losslessly. - -Returns `napi_ok` if the API succeeded. If a non-`BigInt` is passed in it -returns `napi_bigint_expected`. - -This API returns the C `uint64_t` primitive equivalent of the given JavaScript -`BigInt`. If needed it will truncate the value, setting `lossless` to `false`. - -#### napi_get_value_bigint_words - - -```c -napi_status napi_get_value_bigint_words(napi_env env, - napi_value value, - int* sign_bit, - size_t* word_count, - uint64_t* words); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing JavaScript `BigInt`. -* `[out] sign_bit`: Integer representing if the JavaScript `BigInt` is positive - or negative. -* `[in/out] word_count`: Must be initialized to the length of the `words` - array. Upon return, it will be set to the actual number of words that - would be needed to store this `BigInt`. -* `[out] words`: Pointer to a pre-allocated 64-bit word array. - -Returns `napi_ok` if the API succeeded. - -This API converts a single `BigInt` value into a sign bit, 64-bit little-endian -array, and the number of elements in the array. `sign_bit` and `words` may be -both set to `NULL`, in order to get only `word_count`. - -#### napi_get_value_external - - -```c -napi_status napi_get_value_external(napi_env env, - napi_value value, - void** result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing JavaScript external value. -* `[out] result`: Pointer to the data wrapped by the JavaScript external value. - -Returns `napi_ok` if the API succeeded. If a non-external `napi_value` is -passed in it returns `napi_invalid_arg`. - -This API retrieves the external data pointer that was previously passed to -`napi_create_external()`. - -#### napi_get_value_int32 - - -```c -napi_status napi_get_value_int32(napi_env env, - napi_value value, - int32_t* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing JavaScript `Number`. -* `[out] result`: C `int32` primitive equivalent of the given JavaScript - `Number`. - -Returns `napi_ok` if the API succeeded. If a non-number `napi_value` -is passed in `napi_number_expected`. - -This API returns the C `int32` primitive equivalent -of the given JavaScript `Number`. - -If the number exceeds the range of the 32 bit integer, then the result is -truncated to the equivalent of the bottom 32 bits. This can result in a large -positive number becoming a negative number if the value is > 231 - 1. - -Non-finite number values (`NaN`, `+Infinity`, or `-Infinity`) set the -result to zero. - -#### napi_get_value_int64 - - -```c -napi_status napi_get_value_int64(napi_env env, - napi_value value, - int64_t* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing JavaScript `Number`. -* `[out] result`: C `int64` primitive equivalent of the given JavaScript - `Number`. - -Returns `napi_ok` if the API succeeded. If a non-number `napi_value` -is passed in it returns `napi_number_expected`. - -This API returns the C `int64` primitive equivalent of the given JavaScript -`Number`. - -`Number` values outside the range of [`Number.MIN_SAFE_INTEGER`][] -`-(2**53 - 1)` - [`Number.MAX_SAFE_INTEGER`][] `(2**53 - 1)` will lose -precision. - -Non-finite number values (`NaN`, `+Infinity`, or `-Infinity`) set the -result to zero. - -#### napi_get_value_string_latin1 - - -```c -napi_status napi_get_value_string_latin1(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing JavaScript string. -* `[in] buf`: Buffer to write the ISO-8859-1-encoded string into. If `NULL` is - passed in, the length of the string in bytes and excluding the null terminator - is returned in `result`. -* `[in] bufsize`: Size of the destination buffer. When this value is - insufficient, the returned string is truncated and null-terminated. -* `[out] result`: Number of bytes copied into the buffer, excluding the null - terminator. - -Returns `napi_ok` if the API succeeded. If a non-`String` `napi_value` -is passed in it returns `napi_string_expected`. - -This API returns the ISO-8859-1-encoded string corresponding the value passed -in. - -#### napi_get_value_string_utf8 - - -```c -napi_status napi_get_value_string_utf8(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing JavaScript string. -* `[in] buf`: Buffer to write the UTF8-encoded string into. If `NULL` is passed - in, the length of the string in bytes and excluding the null terminator is - returned in `result`. -* `[in] bufsize`: Size of the destination buffer. When this value is - insufficient, the returned string is truncated and null-terminated. -* `[out] result`: Number of bytes copied into the buffer, excluding the null - terminator. - -Returns `napi_ok` if the API succeeded. If a non-`String` `napi_value` -is passed in it returns `napi_string_expected`. - -This API returns the UTF8-encoded string corresponding the value passed in. - -#### napi_get_value_string_utf16 - - -```c -napi_status napi_get_value_string_utf16(napi_env env, - napi_value value, - char16_t* buf, - size_t bufsize, - size_t* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing JavaScript string. -* `[in] buf`: Buffer to write the UTF16-LE-encoded string into. If `NULL` is - passed in, the length of the string in 2-byte code units and excluding the - null terminator is returned. -* `[in] bufsize`: Size of the destination buffer. When this value is - insufficient, the returned string is truncated and null-terminated. -* `[out] result`: Number of 2-byte code units copied into the buffer, excluding - the null terminator. - -Returns `napi_ok` if the API succeeded. If a non-`String` `napi_value` -is passed in it returns `napi_string_expected`. - -This API returns the UTF16-encoded string corresponding the value passed in. - -#### napi_get_value_uint32 - - -```c -napi_status napi_get_value_uint32(napi_env env, - napi_value value, - uint32_t* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: `napi_value` representing JavaScript `Number`. -* `[out] result`: C primitive equivalent of the given `napi_value` as a - `uint32_t`. - -Returns `napi_ok` if the API succeeded. If a non-number `napi_value` -is passed in it returns `napi_number_expected`. - -This API returns the C primitive equivalent of the given `napi_value` as a -`uint32_t`. - -### Functions to get global instances -#### napi_get_boolean - - -```c -napi_status napi_get_boolean(napi_env env, bool value, napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The value of the boolean to retrieve. -* `[out] result`: `napi_value` representing JavaScript `Boolean` singleton to - retrieve. - -Returns `napi_ok` if the API succeeded. - -This API is used to return the JavaScript singleton object that is used to -represent the given boolean value. - -#### napi_get_global - - -```c -napi_status napi_get_global(napi_env env, napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] result`: `napi_value` representing JavaScript `global` object. - -Returns `napi_ok` if the API succeeded. - -This API returns the `global` object. - -#### napi_get_null - - -```c -napi_status napi_get_null(napi_env env, napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] result`: `napi_value` representing JavaScript `null` object. - -Returns `napi_ok` if the API succeeded. - -This API returns the `null` object. - -#### napi_get_undefined - - -```c -napi_status napi_get_undefined(napi_env env, napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] result`: `napi_value` representing JavaScript Undefined value. - -Returns `napi_ok` if the API succeeded. - -This API returns the Undefined object. - -## Working with JavaScript values and abstract operations - -N-API exposes a set of APIs to perform some abstract operations on JavaScript -values. Some of these operations are documented under [Section 7][] -of the [ECMAScript Language Specification][]. - -These APIs support doing one of the following: - -1. Coerce JavaScript values to specific JavaScript types (such as `Number` or - `String`). -2. Check the type of a JavaScript value. -3. Check for equality between two JavaScript values. - -### napi_coerce_to_bool - - -```c -napi_status napi_coerce_to_bool(napi_env env, - napi_value value, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value to coerce. -* `[out] result`: `napi_value` representing the coerced JavaScript `Boolean`. - -Returns `napi_ok` if the API succeeded. - -This API implements the abstract operation `ToBoolean()` as defined in -[Section 7.1.2][] of the ECMAScript Language Specification. -This API can be re-entrant if getters are defined on the passed-in `Object`. - -### napi_coerce_to_number - - -```c -napi_status napi_coerce_to_number(napi_env env, - napi_value value, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value to coerce. -* `[out] result`: `napi_value` representing the coerced JavaScript `Number`. - -Returns `napi_ok` if the API succeeded. - -This API implements the abstract operation `ToNumber()` as defined in -[Section 7.1.3][] of the ECMAScript Language Specification. -This API can be re-entrant if getters are defined on the passed-in `Object`. - -### napi_coerce_to_object - - -```c -napi_status napi_coerce_to_object(napi_env env, - napi_value value, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value to coerce. -* `[out] result`: `napi_value` representing the coerced JavaScript `Object`. - -Returns `napi_ok` if the API succeeded. - -This API implements the abstract operation `ToObject()` as defined in -[Section 7.1.13][] of the ECMAScript Language Specification. -This API can be re-entrant if getters are defined on the passed-in `Object`. - -### napi_coerce_to_string - - -```c -napi_status napi_coerce_to_string(napi_env env, - napi_value value, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value to coerce. -* `[out] result`: `napi_value` representing the coerced JavaScript `String`. - -Returns `napi_ok` if the API succeeded. - -This API implements the abstract operation `ToString()` as defined in -[Section 7.1.13][] of the ECMAScript Language Specification. -This API can be re-entrant if getters are defined on the passed-in `Object`. - -### napi_typeof - - -```c -napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value whose type to query. -* `[out] result`: The type of the JavaScript value. - -Returns `napi_ok` if the API succeeded. - -* `napi_invalid_arg` if the type of `value` is not a known ECMAScript type and - `value` is not an External value. - -This API represents behavior similar to invoking the `typeof` Operator on -the object as defined in [Section 12.5.5][] of the ECMAScript Language -Specification. However, there are some differences: - -1. It has support for detecting an External value. -2. It detects `null` as a separate type, while ECMAScript `typeof` would detect - `object`. - -If `value` has a type that is invalid, an error is returned. - -### napi_instanceof - - -```c -napi_status napi_instanceof(napi_env env, - napi_value object, - napi_value constructor, - bool* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] object`: The JavaScript value to check. -* `[in] constructor`: The JavaScript function object of the constructor function - to check against. -* `[out] result`: Boolean that is set to true if `object instanceof constructor` - is true. - -Returns `napi_ok` if the API succeeded. - -This API represents invoking the `instanceof` Operator on the object as -defined in [Section 12.10.4][] of the ECMAScript Language Specification. - -### napi_is_array - - -```c -napi_status napi_is_array(napi_env env, napi_value value, bool* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value to check. -* `[out] result`: Whether the given object is an array. - -Returns `napi_ok` if the API succeeded. - -This API represents invoking the `IsArray` operation on the object -as defined in [Section 7.2.2][] of the ECMAScript Language Specification. - -### napi_is_arraybuffer - - -```c -napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value to check. -* `[out] result`: Whether the given object is an `ArrayBuffer`. - -Returns `napi_ok` if the API succeeded. - -This API checks if the `Object` passed in is an array buffer. - -### napi_is_buffer - - -```c -napi_status napi_is_buffer(napi_env env, napi_value value, bool* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value to check. -* `[out] result`: Whether the given `napi_value` represents a `node::Buffer` - object. - -Returns `napi_ok` if the API succeeded. - -This API checks if the `Object` passed in is a buffer. - -### napi_is_date - - -```c -napi_status napi_is_date(napi_env env, napi_value value, bool* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value to check. -* `[out] result`: Whether the given `napi_value` represents a JavaScript `Date` - object. - -Returns `napi_ok` if the API succeeded. - -This API checks if the `Object` passed in is a date. - -### napi_is_error - - -```c -napi_status napi_is_error(napi_env env, napi_value value, bool* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value to check. -* `[out] result`: Whether the given `napi_value` represents an `Error` object. - -Returns `napi_ok` if the API succeeded. - -This API checks if the `Object` passed in is an `Error`. - -### napi_is_typedarray - - -```c -napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value to check. -* `[out] result`: Whether the given `napi_value` represents a `TypedArray`. - -Returns `napi_ok` if the API succeeded. - -This API checks if the `Object` passed in is a typed array. - -### napi_is_dataview - - -```c -napi_status napi_is_dataview(napi_env env, napi_value value, bool* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The JavaScript value to check. -* `[out] result`: Whether the given `napi_value` represents a `DataView`. - -Returns `napi_ok` if the API succeeded. - -This API checks if the `Object` passed in is a `DataView`. - -### napi_strict_equals - - -```c -napi_status napi_strict_equals(napi_env env, - napi_value lhs, - napi_value rhs, - bool* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] lhs`: The JavaScript value to check. -* `[in] rhs`: The JavaScript value to check against. -* `[out] result`: Whether the two `napi_value` objects are equal. - -Returns `napi_ok` if the API succeeded. - -This API represents the invocation of the Strict Equality algorithm as -defined in [Section 7.2.14][] of the ECMAScript Language Specification. - -### napi_detach_arraybuffer - - -```c -napi_status napi_detach_arraybuffer(napi_env env, - napi_value arraybuffer) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] arraybuffer`: The JavaScript `ArrayBuffer` to be detached. - -Returns `napi_ok` if the API succeeded. If a non-detachable `ArrayBuffer` is -passed in it returns `napi_detachable_arraybuffer_expected`. - -Generally, an `ArrayBuffer` is non-detachable if it has been detached before. -The engine may impose additional conditions on whether an `ArrayBuffer` is -detachable. For example, V8 requires that the `ArrayBuffer` be external, -that is, created with [`napi_create_external_arraybuffer`][]. - -This API represents the invocation of the `ArrayBuffer` detach operation as -defined in [Section 24.1.1.3][] of the ECMAScript Language Specification. - -### napi_is_detached_arraybuffer - - -```c -napi_status napi_is_detached_arraybuffer(napi_env env, - napi_value arraybuffer, - bool* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] arraybuffer`: The JavaScript `ArrayBuffer` to be checked. -* `[out] result`: Whether the `arraybuffer` is detached. - -Returns `napi_ok` if the API succeeded. - -The `ArrayBuffer` is considered detached if its internal data is `null`. - -This API represents the invocation of the `ArrayBuffer` `IsDetachedBuffer` -operation as defined in [Section 24.1.1.2][] of the ECMAScript Language -Specification. - -## Working with JavaScript properties - -N-API exposes a set of APIs to get and set properties on JavaScript -objects. Some of these types are documented under [Section 7][] of the -[ECMAScript Language Specification][]. - -Properties in JavaScript are represented as a tuple of a key and a value. -Fundamentally, all property keys in N-API can be represented in one of the -following forms: - -* Named: a simple UTF8-encoded string -* Integer-Indexed: an index value represented by `uint32_t` -* JavaScript value: these are represented in N-API by `napi_value`. This can - be a `napi_value` representing a `String`, `Number`, or `Symbol`. - -N-API values are represented by the type `napi_value`. -Any N-API call that requires a JavaScript value takes in a `napi_value`. -However, it's the caller's responsibility to make sure that the -`napi_value` in question is of the JavaScript type expected by the API. - -The APIs documented in this section provide a simple interface to -get and set properties on arbitrary JavaScript objects represented by -`napi_value`. - -For instance, consider the following JavaScript code snippet: - -```js -const obj = {}; -obj.myProp = 123; -``` - -The equivalent can be done using N-API values with the following snippet: - -```c -napi_status status = napi_generic_failure; - -// const obj = {} -napi_value obj, value; -status = napi_create_object(env, &obj); -if (status != napi_ok) return status; - -// Create a napi_value for 123 -status = napi_create_int32(env, 123, &value); -if (status != napi_ok) return status; - -// obj.myProp = 123 -status = napi_set_named_property(env, obj, "myProp", value); -if (status != napi_ok) return status; -``` - -Indexed properties can be set in a similar manner. Consider the following -JavaScript snippet: - -```js -const arr = []; -arr[123] = 'hello'; -``` - -The equivalent can be done using N-API values with the following snippet: - -```c -napi_status status = napi_generic_failure; - -// const arr = []; -napi_value arr, value; -status = napi_create_array(env, &arr); -if (status != napi_ok) return status; - -// Create a napi_value for 'hello' -status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &value); -if (status != napi_ok) return status; - -// arr[123] = 'hello'; -status = napi_set_element(env, arr, 123, value); -if (status != napi_ok) return status; -``` - -Properties can be retrieved using the APIs described in this section. -Consider the following JavaScript snippet: - -```js -const arr = []; -const value = arr[123]; -``` - -The following is the approximate equivalent of the N-API counterpart: - -```c -napi_status status = napi_generic_failure; - -// const arr = [] -napi_value arr, value; -status = napi_create_array(env, &arr); -if (status != napi_ok) return status; - -// const value = arr[123] -status = napi_get_element(env, arr, 123, &value); -if (status != napi_ok) return status; -``` - -Finally, multiple properties can also be defined on an object for performance -reasons. Consider the following JavaScript: - -```js -const obj = {}; -Object.defineProperties(obj, { - 'foo': { value: 123, writable: true, configurable: true, enumerable: true }, - 'bar': { value: 456, writable: true, configurable: true, enumerable: true } -}); -``` - -The following is the approximate equivalent of the N-API counterpart: - -```c -napi_status status = napi_status_generic_failure; - -// const obj = {}; -napi_value obj; -status = napi_create_object(env, &obj); -if (status != napi_ok) return status; - -// Create napi_values for 123 and 456 -napi_value fooValue, barValue; -status = napi_create_int32(env, 123, &fooValue); -if (status != napi_ok) return status; -status = napi_create_int32(env, 456, &barValue); -if (status != napi_ok) return status; - -// Set the properties -napi_property_descriptor descriptors[] = { - { "foo", NULL, NULL, NULL, NULL, fooValue, napi_writable | napi_configurable, NULL }, - { "bar", NULL, NULL, NULL, NULL, barValue, napi_writable | napi_configurable, NULL } -} -status = napi_define_properties(env, - obj, - sizeof(descriptors) / sizeof(descriptors[0]), - descriptors); -if (status != napi_ok) return status; -``` - -### Structures -#### napi_property_attributes - - -```c -typedef enum { - napi_default = 0, - napi_writable = 1 << 0, - napi_enumerable = 1 << 1, - napi_configurable = 1 << 2, - - // Used with napi_define_class to distinguish static properties - // from instance properties. Ignored by napi_define_properties. - napi_static = 1 << 10, - - // Default for class methods. - napi_default_method = napi_writable | napi_configurable, - - // Default for object properties, like in JS obj[prop]. - napi_default_property = napi_writable | - napi_enumerable | - napi_configurable, -} napi_property_attributes; -``` - -`napi_property_attributes` are flags used to control the behavior of properties -set on a JavaScript object. Other than `napi_static` they correspond to the -attributes listed in [Section 6.1.7.1][] -of the [ECMAScript Language Specification][]. -They can be one or more of the following bitflags: - -* `napi_default`: No explicit attributes are set on the property. By default, a - property is read only, not enumerable and not configurable. -* `napi_writable`: The property is writable. -* `napi_enumerable`: The property is enumerable. -* `napi_configurable`: The property is configurable as defined in - [Section 6.1.7.1][] of the [ECMAScript Language Specification][]. -* `napi_static`: The property will be defined as a static property on a class as - opposed to an instance property, which is the default. This is used only by - [`napi_define_class`][]. It is ignored by `napi_define_properties`. -* `napi_default_method`: Like a method in a JS class, the property is - configurable and writeable, but not enumerable. -* `napi_default_property`: Like a property set via assignment in JavaScript, the - property is writable, enumerable, and configurable. - -#### napi_property_descriptor - -```c -typedef struct { - // One of utf8name or name should be NULL. - const char* utf8name; - napi_value name; - - napi_callback method; - napi_callback getter; - napi_callback setter; - napi_value value; - - napi_property_attributes attributes; - void* data; -} napi_property_descriptor; -``` - -* `utf8name`: Optional `String` describing the key for the property, - encoded as UTF8. One of `utf8name` or `name` must be provided for the - property. -* `name`: Optional `napi_value` that points to a JavaScript string or symbol - to be used as the key for the property. One of `utf8name` or `name` must - be provided for the property. -* `value`: The value that's retrieved by a get access of the property if the - property is a data property. If this is passed in, set `getter`, `setter`, - `method` and `data` to `NULL` (since these members won't be used). -* `getter`: A function to call when a get access of the property is performed. - If this is passed in, set `value` and `method` to `NULL` (since these members - won't be used). The given function is called implicitly by the runtime when - the property is accessed from JavaScript code (or if a get on the property is - performed using a N-API call). [`napi_callback`][] provides more details. -* `setter`: A function to call when a set access of the property is performed. - If this is passed in, set `value` and `method` to `NULL` (since these members - won't be used). The given function is called implicitly by the runtime when - the property is set from JavaScript code (or if a set on the property is - performed using a N-API call). [`napi_callback`][] provides more details. -* `method`: Set this to make the property descriptor object's `value` - property to be a JavaScript function represented by `method`. If this is - passed in, set `value`, `getter` and `setter` to `NULL` (since these members - won't be used). [`napi_callback`][] provides more details. -* `attributes`: The attributes associated with the particular property. See - [`napi_property_attributes`][]. -* `data`: The callback data passed into `method`, `getter` and `setter` if this - function is invoked. - -### Functions -#### napi_get_property_names - - -```c -napi_status napi_get_property_names(napi_env env, - napi_value object, - napi_value* result); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object from which to retrieve the properties. -* `[out] result`: A `napi_value` representing an array of JavaScript values - that represent the property names of the object. The API can be used to - iterate over `result` using [`napi_get_array_length`][] - and [`napi_get_element`][]. - -Returns `napi_ok` if the API succeeded. - -This API returns the names of the enumerable properties of `object` as an array -of strings. The properties of `object` whose key is a symbol will not be -included. - -#### napi_get_all_property_names - - -```c -napi_get_all_property_names(napi_env env, - napi_value object, - napi_key_collection_mode key_mode, - napi_key_filter key_filter, - napi_key_conversion key_conversion, - napi_value* result); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object from which to retrieve the properties. -* `[in] key_mode`: Whether to retrieve prototype properties as well. -* `[in] key_filter`: Which properties to retrieve - (enumerable/readable/writable). -* `[in] key_conversion`: Whether to convert numbered property keys to strings. -* `[out] result`: A `napi_value` representing an array of JavaScript values - that represent the property names of the object. [`napi_get_array_length`][] - and [`napi_get_element`][] can be used to iterate over `result`. - -Returns `napi_ok` if the API succeeded. - -This API returns an array containing the names of the available properties -of this object. - -#### napi_set_property - - -```c -napi_status napi_set_property(napi_env env, - napi_value object, - napi_value key, - napi_value value); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object on which to set the property. -* `[in] key`: The name of the property to set. -* `[in] value`: The property value. - -Returns `napi_ok` if the API succeeded. - -This API set a property on the `Object` passed in. - -#### napi_get_property - - -```c -napi_status napi_get_property(napi_env env, - napi_value object, - napi_value key, - napi_value* result); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object from which to retrieve the property. -* `[in] key`: The name of the property to retrieve. -* `[out] result`: The value of the property. - -Returns `napi_ok` if the API succeeded. - -This API gets the requested property from the `Object` passed in. - -#### napi_has_property - - -```c -napi_status napi_has_property(napi_env env, - napi_value object, - napi_value key, - bool* result); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object to query. -* `[in] key`: The name of the property whose existence to check. -* `[out] result`: Whether the property exists on the object or not. - -Returns `napi_ok` if the API succeeded. - -This API checks if the `Object` passed in has the named property. - -#### napi_delete_property - - -```c -napi_status napi_delete_property(napi_env env, - napi_value object, - napi_value key, - bool* result); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object to query. -* `[in] key`: The name of the property to delete. -* `[out] result`: Whether the property deletion succeeded or not. `result` can - optionally be ignored by passing `NULL`. - -Returns `napi_ok` if the API succeeded. - -This API attempts to delete the `key` own property from `object`. - -#### napi_has_own_property - - -```c -napi_status napi_has_own_property(napi_env env, - napi_value object, - napi_value key, - bool* result); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object to query. -* `[in] key`: The name of the own property whose existence to check. -* `[out] result`: Whether the own property exists on the object or not. - -Returns `napi_ok` if the API succeeded. - -This API checks if the `Object` passed in has the named own property. `key` must -be a string or a `Symbol`, or an error will be thrown. N-API will not perform -any conversion between data types. - -#### napi_set_named_property - - -```c -napi_status napi_set_named_property(napi_env env, - napi_value object, - const char* utf8Name, - napi_value value); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object on which to set the property. -* `[in] utf8Name`: The name of the property to set. -* `[in] value`: The property value. - -Returns `napi_ok` if the API succeeded. - -This method is equivalent to calling [`napi_set_property`][] with a `napi_value` -created from the string passed in as `utf8Name`. - -#### napi_get_named_property - - -```c -napi_status napi_get_named_property(napi_env env, - napi_value object, - const char* utf8Name, - napi_value* result); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object from which to retrieve the property. -* `[in] utf8Name`: The name of the property to get. -* `[out] result`: The value of the property. - -Returns `napi_ok` if the API succeeded. - -This method is equivalent to calling [`napi_get_property`][] with a `napi_value` -created from the string passed in as `utf8Name`. - -#### napi_has_named_property - - -```c -napi_status napi_has_named_property(napi_env env, - napi_value object, - const char* utf8Name, - bool* result); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object to query. -* `[in] utf8Name`: The name of the property whose existence to check. -* `[out] result`: Whether the property exists on the object or not. - -Returns `napi_ok` if the API succeeded. - -This method is equivalent to calling [`napi_has_property`][] with a `napi_value` -created from the string passed in as `utf8Name`. - -#### napi_set_element - - -```c -napi_status napi_set_element(napi_env env, - napi_value object, - uint32_t index, - napi_value value); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object from which to set the properties. -* `[in] index`: The index of the property to set. -* `[in] value`: The property value. - -Returns `napi_ok` if the API succeeded. - -This API sets and element on the `Object` passed in. - -#### napi_get_element - - -```c -napi_status napi_get_element(napi_env env, - napi_value object, - uint32_t index, - napi_value* result); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object from which to retrieve the property. -* `[in] index`: The index of the property to get. -* `[out] result`: The value of the property. - -Returns `napi_ok` if the API succeeded. - -This API gets the element at the requested index. - -#### napi_has_element - - -```c -napi_status napi_has_element(napi_env env, - napi_value object, - uint32_t index, - bool* result); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object to query. -* `[in] index`: The index of the property whose existence to check. -* `[out] result`: Whether the property exists on the object or not. - -Returns `napi_ok` if the API succeeded. - -This API returns if the `Object` passed in has an element at the -requested index. - -#### napi_delete_element - - -```c -napi_status napi_delete_element(napi_env env, - napi_value object, - uint32_t index, - bool* result); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object to query. -* `[in] index`: The index of the property to delete. -* `[out] result`: Whether the element deletion succeeded or not. `result` can - optionally be ignored by passing `NULL`. - -Returns `napi_ok` if the API succeeded. - -This API attempts to delete the specified `index` from `object`. - -#### napi_define_properties - - -```c -napi_status napi_define_properties(napi_env env, - napi_value object, - size_t property_count, - const napi_property_descriptor* properties); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object from which to retrieve the properties. -* `[in] property_count`: The number of elements in the `properties` array. -* `[in] properties`: The array of property descriptors. - -Returns `napi_ok` if the API succeeded. - -This method allows the efficient definition of multiple properties on a given -object. The properties are defined using property descriptors (see -[`napi_property_descriptor`][]). Given an array of such property descriptors, -this API will set the properties on the object one at a time, as defined by -`DefineOwnProperty()` (described in [Section 9.1.6][] of the ECMA-262 -specification). - -#### napi_object_freeze - - -> Stability: 1 - Experimental - -```c -napi_status napi_object_freeze(napi_env env, - napi_value object); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object to freeze. - -Returns `napi_ok` if the API succeeded. - -This method freezes a given object. This prevents new properties from -being added to it, existing properties from being removed, prevents -changing the enumerability, configurability, or writability of existing -properties, and prevents the values of existing properties from being changed. -It also prevents the object's prototype from being changed. This is described -in [Section 19.1.2.6](https://tc39.es/ecma262/#sec-object.freeze) of the -ECMA-262 specification. - -#### napi_object_seal - - -> Stability: 1 - Experimental - -```c -napi_status napi_object_seal(napi_env env, - napi_value object); -``` - -* `[in] env`: The environment that the N-API call is invoked under. -* `[in] object`: The object to seal. - -Returns `napi_ok` if the API succeeded. - -This method seals a given object. This prevents new properties from being -added to it, as well as marking all existing properties as non-configurable. -This is described in [Section 19.1.2.20](https://tc39.es/ecma262/#sec-object.seal) -of the ECMA-262 specification. - -## Working with JavaScript functions - -N-API provides a set of APIs that allow JavaScript code to -call back into native code. N-API APIs that support calling back -into native code take in a callback functions represented by -the `napi_callback` type. When the JavaScript VM calls back to -native code, the `napi_callback` function provided is invoked. The APIs -documented in this section allow the callback function to do the -following: - -* Get information about the context in which the callback was invoked. -* Get the arguments passed into the callback. -* Return a `napi_value` back from the callback. - -Additionally, N-API provides a set of functions which allow calling -JavaScript functions from native code. One can either call a function -like a regular JavaScript function call, or as a constructor -function. - -Any non-`NULL` data which is passed to this API via the `data` field of the -`napi_property_descriptor` items can be associated with `object` and freed -whenever `object` is garbage-collected by passing both `object` and the data to -[`napi_add_finalizer`][]. - -### napi_call_function - - -```c -NAPI_EXTERN napi_status napi_call_function(napi_env env, - napi_value recv, - napi_value func, - size_t argc, - const napi_value* argv, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] recv`: The `this` object passed to the called function. -* `[in] func`: `napi_value` representing the JavaScript function to be invoked. -* `[in] argc`: The count of elements in the `argv` array. -* `[in] argv`: Array of `napi_values` representing JavaScript values passed in - as arguments to the function. -* `[out] result`: `napi_value` representing the JavaScript object returned. - -Returns `napi_ok` if the API succeeded. - -This method allows a JavaScript function object to be called from a native -add-on. This is the primary mechanism of calling back *from* the add-on's -native code *into* JavaScript. For the special case of calling into JavaScript -after an async operation, see [`napi_make_callback`][]. - -A sample use case might look as follows. Consider the following JavaScript -snippet: - -```js -function AddTwo(num) { - return num + 2; -} -``` - -Then, the above function can be invoked from a native add-on using the -following code: - -```c -// Get the function named "AddTwo" on the global object -napi_value global, add_two, arg; -napi_status status = napi_get_global(env, &global); -if (status != napi_ok) return; - -status = napi_get_named_property(env, global, "AddTwo", &add_two); -if (status != napi_ok) return; - -// const arg = 1337 -status = napi_create_int32(env, 1337, &arg); -if (status != napi_ok) return; - -napi_value* argv = &arg; -size_t argc = 1; - -// AddTwo(arg); -napi_value return_val; -status = napi_call_function(env, global, add_two, argc, argv, &return_val); -if (status != napi_ok) return; - -// Convert the result back to a native type -int32_t result; -status = napi_get_value_int32(env, return_val, &result); -if (status != napi_ok) return; -``` - -### napi_create_function - - -```c -napi_status napi_create_function(napi_env env, - const char* utf8name, - size_t length, - napi_callback cb, - void* data, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] utf8Name`: The name of the function encoded as UTF8. This is visible - within JavaScript as the new function object's `name` property. -* `[in] length`: The length of the `utf8name` in bytes, or `NAPI_AUTO_LENGTH` if - it is null-terminated. -* `[in] cb`: The native function which should be called when this function - object is invoked. [`napi_callback`][] provides more details. -* `[in] data`: User-provided data context. This will be passed back into the - function when invoked later. -* `[out] result`: `napi_value` representing the JavaScript function object for - the newly created function. - -Returns `napi_ok` if the API succeeded. - -This API allows an add-on author to create a function object in native code. -This is the primary mechanism to allow calling *into* the add-on's native code -*from* JavaScript. - -The newly created function is not automatically visible from script after this -call. Instead, a property must be explicitly set on any object that is visible -to JavaScript, in order for the function to be accessible from script. - -In order to expose a function as part of the -add-on's module exports, set the newly created function on the exports -object. A sample module might look as follows: - -```c -napi_value SayHello(napi_env env, napi_callback_info info) { - printf("Hello\n"); - return NULL; -} - -napi_value Init(napi_env env, napi_value exports) { - napi_status status; - - napi_value fn; - status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn); - if (status != napi_ok) return NULL; - - status = napi_set_named_property(env, exports, "sayHello", fn); - if (status != napi_ok) return NULL; - - return exports; -} - -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) -``` - -Given the above code, the add-on can be used from JavaScript as follows: - -```js -const myaddon = require('./addon'); -myaddon.sayHello(); -``` - -The string passed to `require()` is the name of the target in `binding.gyp` -responsible for creating the `.node` file. - -Any non-`NULL` data which is passed to this API via the `data` parameter can -be associated with the resulting JavaScript function (which is returned in the -`result` parameter) and freed whenever the function is garbage-collected by -passing both the JavaScript function and the data to [`napi_add_finalizer`][]. - -JavaScript `Function`s are described in [Section 19.2][] of the ECMAScript -Language Specification. - -### napi_get_cb_info - - -```c -napi_status napi_get_cb_info(napi_env env, - napi_callback_info cbinfo, - size_t* argc, - napi_value* argv, - napi_value* thisArg, - void** data) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] cbinfo`: The callback info passed into the callback function. -* `[in-out] argc`: Specifies the length of the provided `argv` array and - receives the actual count of arguments. -* `[out] argv`: Buffer to which the `napi_value` representing the arguments are - copied. If there are more arguments than the provided count, only the - requested number of arguments are copied. If there are fewer arguments - provided than claimed, the rest of `argv` is filled with `napi_value` values - that represent `undefined`. -* `[out] this`: Receives the JavaScript `this` argument for the call. -* `[out] data`: Receives the data pointer for the callback. - -Returns `napi_ok` if the API succeeded. - -This method is used within a callback function to retrieve details about the -call like the arguments and the `this` pointer from a given callback info. - -### napi_get_new_target - - -```c -napi_status napi_get_new_target(napi_env env, - napi_callback_info cbinfo, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] cbinfo`: The callback info passed into the callback function. -* `[out] result`: The `new.target` of the constructor call. - -Returns `napi_ok` if the API succeeded. - -This API returns the `new.target` of the constructor call. If the current -callback is not a constructor call, the result is `NULL`. - -### napi_new_instance - - -```c -napi_status napi_new_instance(napi_env env, - napi_value cons, - size_t argc, - napi_value* argv, - napi_value* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] cons`: `napi_value` representing the JavaScript function to be invoked - as a constructor. -* `[in] argc`: The count of elements in the `argv` array. -* `[in] argv`: Array of JavaScript values as `napi_value` representing the - arguments to the constructor. -* `[out] result`: `napi_value` representing the JavaScript object returned, - which in this case is the constructed object. - -This method is used to instantiate a new JavaScript value using a given -`napi_value` that represents the constructor for the object. For example, -consider the following snippet: - -```js -function MyObject(param) { - this.param = param; -} - -const arg = 'hello'; -const value = new MyObject(arg); -``` - -The following can be approximated in N-API using the following snippet: - -```c -// Get the constructor function MyObject -napi_value global, constructor, arg, value; -napi_status status = napi_get_global(env, &global); -if (status != napi_ok) return; - -status = napi_get_named_property(env, global, "MyObject", &constructor); -if (status != napi_ok) return; - -// const arg = "hello" -status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &arg); -if (status != napi_ok) return; - -napi_value* argv = &arg; -size_t argc = 1; - -// const value = new MyObject(arg) -status = napi_new_instance(env, constructor, argc, argv, &value); -``` - -Returns `napi_ok` if the API succeeded. - -## Object wrap - -N-API offers a way to "wrap" C++ classes and instances so that the class -constructor and methods can be called from JavaScript. - -1. The [`napi_define_class`][] API defines a JavaScript class with constructor, - static properties and methods, and instance properties and methods that - correspond to the C++ class. -2. When JavaScript code invokes the constructor, the constructor callback - uses [`napi_wrap`][] to wrap a new C++ instance in a JavaScript object, - then returns the wrapper object. -3. When JavaScript code invokes a method or property accessor on the class, - the corresponding `napi_callback` C++ function is invoked. For an instance - callback, [`napi_unwrap`][] obtains the C++ instance that is the target of - the call. - -For wrapped objects it may be difficult to distinguish between a function -called on a class prototype and a function called on an instance of a class. -A common pattern used to address this problem is to save a persistent -reference to the class constructor for later `instanceof` checks. - -```c -napi_value MyClass_constructor = NULL; -status = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor); -assert(napi_ok == status); -bool is_instance = false; -status = napi_instanceof(env, es_this, MyClass_constructor, &is_instance); -assert(napi_ok == status); -if (is_instance) { - // napi_unwrap() ... -} else { - // otherwise... -} -``` - -The reference must be freed once it is no longer needed. - -There are occasions where `napi_instanceof()` is insufficient for ensuring that -a JavaScript object is a wrapper for a certain native type. This is the case -especially when wrapped JavaScript objects are passed back into the addon via -static methods rather than as the `this` value of prototype methods. In such -cases there is a chance that they may be unwrapped incorrectly. - -```js -const myAddon = require('./build/Release/my_addon.node'); - -// `openDatabase()` returns a JavaScript object that wraps a native database -// handle. -const dbHandle = myAddon.openDatabase(); - -// `query()` returns a JavaScript object that wraps a native query handle. -const queryHandle = myAddon.query(dbHandle, 'Gimme ALL the things!'); - -// There is an accidental error in the line below. The first parameter to -// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not -// the query handle (`query`), so the correct condition for the while-loop -// should be -// -// myAddon.queryHasRecords(dbHandle, queryHandle) -// -while (myAddon.queryHasRecords(queryHandle, dbHandle)) { - // retrieve records -} -``` - -In the above example `myAddon.queryHasRecords()` is a method that accepts two -arguments. The first is a database handle and the second is a query handle. -Internally, it unwraps the first argument and casts the resulting pointer to a -native database handle. It then unwraps the second argument and casts the -resulting pointer to a query handle. If the arguments are passed in the wrong -order, the casts will work, however, there is a good chance that the underlying -database operation will fail, or will even cause an invalid memory access. - -To ensure that the pointer retrieved from the first argument is indeed a pointer -to a database handle and, similarly, that the pointer retrieved from the second -argument is indeed a pointer to a query handle, the implementation of -`queryHasRecords()` has to perform a type validation. Retaining the JavaScript -class constructor from which the database handle was instantiated and the -constructor from which the query handle was instantiated in `napi_ref`s can -help, because `napi_instanceof()` can then be used to ensure that the instances -passed into `queryHashRecords()` are indeed of the correct type. - -Unfortunately, `napi_instanceof()` does not protect against prototype -manipulation. For example, the prototype of the database handle instance can be -set to the prototype of the constructor for query handle instances. In this -case, the database handle instance can appear as a query handle instance, and it -will pass the `napi_instanceof()` test for a query handle instance, while still -containing a pointer to a database handle. - -To this end, N-API provides type-tagging capabilities. - -A type tag is a 128-bit integer unique to the addon. N-API provides the -`napi_type_tag` structure for storing a type tag. When such a value is passed -along with a JavaScript object stored in a `napi_value` to -`napi_type_tag_object()`, the JavaScript object will be "marked" with the -type tag. The "mark" is invisible on the JavaScript side. When a JavaScript -object arrives into a native binding, `napi_check_object_type_tag()` can be used -along with the original type tag to determine whether the JavaScript object was -previously "marked" with the type tag. This creates a type-checking capability -of a higher fidelity than `napi_instanceof()` can provide, because such type- -tagging survives prototype manipulation and addon unloading/reloading. - -Continuing the above example, the following skeleton addon implementation -illustrates the use of `napi_type_tag_object()` and -`napi_check_object_type_tag()`. - -```c -// This value is the type tag for a database handle. The command -// -// uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\1, 0x\2/' -// -// can be used to obtain the two values with which to initialize the structure. -static const napi_type_tag DatabaseHandleTypeTag = { - 0x1edf75a38336451d, 0xa5ed9ce2e4c00c38 -}; - -// This value is the type tag for a query handle. -static const napi_type_tag QueryHandleTypeTag = { - 0x9c73317f9fad44a3, 0x93c3920bf3b0ad6a -}; - -static napi_value -openDatabase(napi_env env, napi_callback_info info) { - napi_status status; - napi_value result; - - // Perform the underlying action which results in a database handle. - DatabaseHandle* dbHandle = open_database(); - - // Create a new, empty JS object. - status = napi_create_object(env, &result); - if (status != napi_ok) return NULL; - - // Tag the object to indicate that it holds a pointer to a `DatabaseHandle`. - status = napi_type_tag_object(env, result, &DatabaseHandleTypeTag); - if (status != napi_ok) return NULL; - - // Store the pointer to the `DatabaseHandle` structure inside the JS object. - status = napi_wrap(env, result, dbHandle, NULL, NULL, NULL); - if (status != napi_ok) return NULL; - - return result; -} - -// Later when we receive a JavaScript object purporting to be a database handle -// we can use `napi_check_object_type_tag()` to ensure that it is indeed such a -// handle. - -static napi_value -query(napi_env env, napi_callback_info info) { - napi_status status; - size_t argc = 2; - napi_value argv[2]; - bool is_db_handle; - - status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL); - if (status != napi_ok) return NULL; - - // Check that the object passed as the first parameter has the previously - // applied tag. - status = napi_check_object_type_tag(env, - argv[0], - &DatabaseHandleTypeTag, - &is_db_handle); - if (status != napi_ok) return NULL; - - // Throw a `TypeError` if it doesn't. - if (!is_db_handle) { - // Throw a TypeError. - return NULL; - } -} -``` - -### napi_define_class - - -```c -napi_status napi_define_class(napi_env env, - const char* utf8name, - size_t length, - napi_callback constructor, - void* data, - size_t property_count, - const napi_property_descriptor* properties, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] utf8name`: Name of the JavaScript constructor function; When wrapping a - C++ class, we recommend for clarity that this name be the same as that of - the C++ class. -* `[in] length`: The length of the `utf8name` in bytes, or `NAPI_AUTO_LENGTH` - if it is null-terminated. -* `[in] constructor`: Callback function that handles constructing instances - of the class. When wrapping a C++ class, this method must be a static member - with the [`napi_callback`][] signature. A C++ class constructor cannot be - used. [`napi_callback`][] provides more details. -* `[in] data`: Optional data to be passed to the constructor callback as - the `data` property of the callback info. -* `[in] property_count`: Number of items in the `properties` array argument. -* `[in] properties`: Array of property descriptors describing static and - instance data properties, accessors, and methods on the class - See `napi_property_descriptor`. -* `[out] result`: A `napi_value` representing the constructor function for - the class. - -Returns `napi_ok` if the API succeeded. - -Defines a JavaScript class, including: - -* A JavaScript constructor function that has the class name. When wrapping a - corresponding C++ class, the callback passed via `constructor` can be used to - instantiate a new C++ class instance, which can then be placed inside the - JavaScript object instance being constructed using [`napi_wrap`][]. -* Properties on the constructor function whose implementation can call - corresponding _static_ data properties, accessors, and methods of the C++ - class (defined by property descriptors with the `napi_static` attribute). -* Properties on the constructor function's `prototype` object. When wrapping a - C++ class, _non-static_ data properties, accessors, and methods of the C++ - class can be called from the static functions given in the property - descriptors without the `napi_static` attribute after retrieving the C++ class - instance placed inside the JavaScript object instance by using - [`napi_unwrap`][]. - -When wrapping a C++ class, the C++ constructor callback passed via `constructor` -should be a static method on the class that calls the actual class constructor, -then wraps the new C++ instance in a JavaScript object, and returns the wrapper -object. See [`napi_wrap`][] for details. - -The JavaScript constructor function returned from [`napi_define_class`][] is -often saved and used later to construct new instances of the class from native -code, and/or to check whether provided values are instances of the class. In -that case, to prevent the function value from being garbage-collected, a -strong persistent reference to it can be created using -[`napi_create_reference`][], ensuring that the reference count is kept >= 1. - -Any non-`NULL` data which is passed to this API via the `data` parameter or via -the `data` field of the `napi_property_descriptor` array items can be associated -with the resulting JavaScript constructor (which is returned in the `result` -parameter) and freed whenever the class is garbage-collected by passing both -the JavaScript function and the data to [`napi_add_finalizer`][]. - -### napi_wrap - - -```c -napi_status napi_wrap(napi_env env, - napi_value js_object, - void* native_object, - napi_finalize finalize_cb, - void* finalize_hint, - napi_ref* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] js_object`: The JavaScript object that will be the wrapper for the - native object. -* `[in] native_object`: The native instance that will be wrapped in the - JavaScript object. -* `[in] finalize_cb`: Optional native callback that can be used to free the - native instance when the JavaScript object is ready for garbage-collection. - [`napi_finalize`][] provides more details. -* `[in] finalize_hint`: Optional contextual hint that is passed to the - finalize callback. -* `[out] result`: Optional reference to the wrapped object. - -Returns `napi_ok` if the API succeeded. - -Wraps a native instance in a JavaScript object. The native instance can be -retrieved later using `napi_unwrap()`. - -When JavaScript code invokes a constructor for a class that was defined using -`napi_define_class()`, the `napi_callback` for the constructor is invoked. -After constructing an instance of the native class, the callback must then call -`napi_wrap()` to wrap the newly constructed instance in the already-created -JavaScript object that is the `this` argument to the constructor callback. -(That `this` object was created from the constructor function's `prototype`, -so it already has definitions of all the instance properties and methods.) - -Typically when wrapping a class instance, a finalize callback should be -provided that simply deletes the native instance that is received as the `data` -argument to the finalize callback. - -The optional returned reference is initially a weak reference, meaning it -has a reference count of 0. Typically this reference count would be incremented -temporarily during async operations that require the instance to remain valid. - -*Caution*: The optional returned reference (if obtained) should be deleted via -[`napi_delete_reference`][] ONLY in response to the finalize callback -invocation. If it is deleted before then, then the finalize callback may never -be invoked. Therefore, when obtaining a reference a finalize callback is also -required in order to enable correct disposal of the reference. - -Calling `napi_wrap()` a second time on an object will return an error. To -associate another native instance with the object, use `napi_remove_wrap()` -first. - -### napi_unwrap - - -```c -napi_status napi_unwrap(napi_env env, - napi_value js_object, - void** result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] js_object`: The object associated with the native instance. -* `[out] result`: Pointer to the wrapped native instance. - -Returns `napi_ok` if the API succeeded. - -Retrieves a native instance that was previously wrapped in a JavaScript -object using `napi_wrap()`. - -When JavaScript code invokes a method or property accessor on the class, the -corresponding `napi_callback` is invoked. If the callback is for an instance -method or accessor, then the `this` argument to the callback is the wrapper -object; the wrapped C++ instance that is the target of the call can be obtained -then by calling `napi_unwrap()` on the wrapper object. - -### napi_remove_wrap - - -```c -napi_status napi_remove_wrap(napi_env env, - napi_value js_object, - void** result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] js_object`: The object associated with the native instance. -* `[out] result`: Pointer to the wrapped native instance. - -Returns `napi_ok` if the API succeeded. - -Retrieves a native instance that was previously wrapped in the JavaScript -object `js_object` using `napi_wrap()` and removes the wrapping. If a finalize -callback was associated with the wrapping, it will no longer be called when the -JavaScript object becomes garbage-collected. - -### napi_type_tag_object - - -> Stability: 1 - Experimental - -```c -napi_status napi_type_tag_object(napi_env env, - napi_value js_object, - const napi_type_tag* type_tag); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] js_object`: The JavaScript object to be marked. -* `[in] type_tag`: The tag with which the object is to be marked. - -Returns `napi_ok` if the API succeeded. - -Associates the value of the `type_tag` pointer with the JavaScript object. -`napi_check_object_type_tag()` can then be used to compare the tag that was -attached to the object with one owned by the addon to ensure that the object -has the right type. - -If the object already has an associated type tag, this API will return -`napi_invalid_arg`. - -### napi_check_object_type_tag - - -> Stability: 1 - Experimental - -```c -napi_status napi_check_object_type_tag(napi_env env, - napi_value js_object, - const napi_type_tag* type_tag, - bool* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] js_object`: The JavaScript object whose type tag to examine. -* `[in] type_tag`: The tag with which to compare any tag found on the object. -* `[out] result`: Whether the type tag given matched the type tag on the - object. `false` is also returned if no type tag was found on the object. - -Returns `napi_ok` if the API succeeded. - -Compares the pointer given as `type_tag` with any that can be found on -`js_object`. If no tag is found on `js_object` or, if a tag is found but it does -not match `type_tag`, then `result` is set to `false`. If a tag is found and it -matches `type_tag`, then `result` is set to `true`. - -### napi_add_finalizer - - - -```c -napi_status napi_add_finalizer(napi_env env, - napi_value js_object, - void* native_object, - napi_finalize finalize_cb, - void* finalize_hint, - napi_ref* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] js_object`: The JavaScript object to which the native data will be - attached. -* `[in] native_object`: The native data that will be attached to the JavaScript - object. -* `[in] finalize_cb`: Native callback that will be used to free the - native data when the JavaScript object is ready for garbage-collection. - [`napi_finalize`][] provides more details. -* `[in] finalize_hint`: Optional contextual hint that is passed to the - finalize callback. -* `[out] result`: Optional reference to the JavaScript object. - -Returns `napi_ok` if the API succeeded. - -Adds a `napi_finalize` callback which will be called when the JavaScript object -in `js_object` is ready for garbage collection. This API is similar to -`napi_wrap()` except that: - -* the native data cannot be retrieved later using `napi_unwrap()`, -* nor can it be removed later using `napi_remove_wrap()`, and -* the API can be called multiple times with different data items in order to - attach each of them to the JavaScript object, and -* the object manipulated by the API can be used with `napi_wrap()`. - -*Caution*: The optional returned reference (if obtained) should be deleted via -[`napi_delete_reference`][] ONLY in response to the finalize callback -invocation. If it is deleted before then, then the finalize callback may never -be invoked. Therefore, when obtaining a reference a finalize callback is also -required in order to enable correct disposal of the reference. - -## Simple asynchronous operations - -Addon modules often need to leverage async helpers from libuv as part of their -implementation. This allows them to schedule work to be executed asynchronously -so that their methods can return in advance of the work being completed. This -allows them to avoid blocking overall execution of the Node.js application. - -N-API provides an ABI-stable interface for these -supporting functions which covers the most common asynchronous use cases. - -N-API defines the `napi_async_work` structure which is used to manage -asynchronous workers. Instances are created/deleted with -[`napi_create_async_work`][] and [`napi_delete_async_work`][]. - -The `execute` and `complete` callbacks are functions that will be -invoked when the executor is ready to execute and when it completes its -task respectively. - -The `execute` function should avoid making any N-API calls -that could result in the execution of JavaScript or interaction with -JavaScript objects. Most often, any code that needs to make N-API -calls should be made in `complete` callback instead. -Avoid using the `napi_env` parameter in the execute callback as -it will likely execute JavaScript. - -These functions implement the following interfaces: - -```c -typedef void (*napi_async_execute_callback)(napi_env env, - void* data); -typedef void (*napi_async_complete_callback)(napi_env env, - napi_status status, - void* data); -``` - -When these methods are invoked, the `data` parameter passed will be the -addon-provided `void*` data that was passed into the -`napi_create_async_work` call. - -Once created the async worker can be queued -for execution using the [`napi_queue_async_work`][] function: - -```c -napi_status napi_queue_async_work(napi_env env, - napi_async_work work); -``` - -[`napi_cancel_async_work`][] can be used if the work needs -to be cancelled before the work has started execution. - -After calling [`napi_cancel_async_work`][], the `complete` callback -will be invoked with a status value of `napi_cancelled`. -The work should not be deleted before the `complete` -callback invocation, even when it was cancelled. - -### napi_create_async_work - - -```c -napi_status napi_create_async_work(napi_env env, - napi_value async_resource, - napi_value async_resource_name, - napi_async_execute_callback execute, - napi_async_complete_callback complete, - void* data, - napi_async_work* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] async_resource`: An optional object associated with the async work - that will be passed to possible `async_hooks` [`init` hooks][]. -* `[in] async_resource_name`: Identifier for the kind of resource that is being - provided for diagnostic information exposed by the `async_hooks` API. -* `[in] execute`: The native function which should be called to execute the - logic asynchronously. The given function is called from a worker pool thread - and can execute in parallel with the main event loop thread. -* `[in] complete`: The native function which will be called when the - asynchronous logic is completed or is cancelled. The given function is called - from the main event loop thread. [`napi_async_complete_callback`][] provides - more details. -* `[in] data`: User-provided data context. This will be passed back into the - execute and complete functions. -* `[out] result`: `napi_async_work*` which is the handle to the newly created - async work. - -Returns `napi_ok` if the API succeeded. - -This API allocates a work object that is used to execute logic asynchronously. -It should be freed using [`napi_delete_async_work`][] once the work is no longer -required. - -`async_resource_name` should be a null-terminated, UTF-8-encoded string. - -The `async_resource_name` identifier is provided by the user and should be -representative of the type of async work being performed. It is also recommended -to apply namespacing to the identifier, e.g. by including the module name. See -the [`async_hooks` documentation][async_hooks `type`] for more information. - -### napi_delete_async_work - - -```c -napi_status napi_delete_async_work(napi_env env, - napi_async_work work); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] work`: The handle returned by the call to `napi_create_async_work`. - -Returns `napi_ok` if the API succeeded. - -This API frees a previously allocated work object. - -This API can be called even if there is a pending JavaScript exception. - -### napi_queue_async_work - - -```c -napi_status napi_queue_async_work(napi_env env, - napi_async_work work); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] work`: The handle returned by the call to `napi_create_async_work`. - -Returns `napi_ok` if the API succeeded. - -This API requests that the previously allocated work be scheduled -for execution. Once it returns successfully, this API must not be called again -with the same `napi_async_work` item or the result will be undefined. - -### napi_cancel_async_work - - -```c -napi_status napi_cancel_async_work(napi_env env, - napi_async_work work); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] work`: The handle returned by the call to `napi_create_async_work`. - -Returns `napi_ok` if the API succeeded. - -This API cancels queued work if it has not yet -been started. If it has already started executing, it cannot be -cancelled and `napi_generic_failure` will be returned. If successful, -the `complete` callback will be invoked with a status value of -`napi_cancelled`. The work should not be deleted before the `complete` -callback invocation, even if it has been successfully cancelled. - -This API can be called even if there is a pending JavaScript exception. - -## Custom asynchronous operations - -The simple asynchronous work APIs above may not be appropriate for every -scenario. When using any other asynchronous mechanism, the following APIs -are necessary to ensure an asynchronous operation is properly tracked by -the runtime. - -### napi_async_init - - -```c -napi_status napi_async_init(napi_env env, - napi_value async_resource, - napi_value async_resource_name, - napi_async_context* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] async_resource`: Object associated with the async work - that will be passed to possible `async_hooks` [`init` hooks][] and can be - accessed by [`async_hooks.executionAsyncResource()`][]. -* `[in] async_resource_name`: Identifier for the kind of resource that is being - provided for diagnostic information exposed by the `async_hooks` API. -* `[out] result`: The initialized async context. - -Returns `napi_ok` if the API succeeded. - -The `async_resource` object needs to be kept alive until -[`napi_async_destroy`][] to keep `async_hooks` related API acts correctly. In -order to retain ABI compatibility with previous versions, `napi_async_context`s -are not maintaining the strong reference to the `async_resource` objects to -avoid introducing causing memory leaks. However, if the `async_resource` is -garbage collected by JavaScript engine before the `napi_async_context` was -destroyed by `napi_async_destroy`, calling `napi_async_context` related APIs -like [`napi_open_callback_scope`][] and [`napi_make_callback`][] can cause -problems like loss of async context when using the `AsyncLocalStoage` API. - -In order to retain ABI compatibility with previous versions, passing `NULL` -for `async_resource` does not result in an error. However, this is not -recommended as this will result poor results with `async_hooks` -[`init` hooks][] and `async_hooks.executionAsyncResource()` as the resource is -now required by the underlying `async_hooks` implementation in order to provide -the linkage between async callbacks. - -### napi_async_destroy - - -```c -napi_status napi_async_destroy(napi_env env, - napi_async_context async_context); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] async_context`: The async context to be destroyed. - -Returns `napi_ok` if the API succeeded. - -This API can be called even if there is a pending JavaScript exception. - -### napi_make_callback - - -```c -NAPI_EXTERN napi_status napi_make_callback(napi_env env, - napi_async_context async_context, - napi_value recv, - napi_value func, - size_t argc, - const napi_value* argv, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] async_context`: Context for the async operation that is - invoking the callback. This should normally be a value previously - obtained from [`napi_async_init`][]. - In order to retain ABI compatibility with previous versions, passing `NULL` - for `async_context` does not result in an error. However, this results - in incorrect operation of async hooks. Potential issues include loss of - async context when using the `AsyncLocalStorage` API. -* `[in] recv`: The `this` object passed to the called function. -* `[in] func`: `napi_value` representing the JavaScript function to be invoked. -* `[in] argc`: The count of elements in the `argv` array. -* `[in] argv`: Array of JavaScript values as `napi_value` representing the - arguments to the function. -* `[out] result`: `napi_value` representing the JavaScript object returned. - -Returns `napi_ok` if the API succeeded. - -This method allows a JavaScript function object to be called from a native -add-on. This API is similar to `napi_call_function`. However, it is used to call -*from* native code back *into* JavaScript *after* returning from an async -operation (when there is no other script on the stack). It is a fairly simple -wrapper around `node::MakeCallback`. - -Note it is *not* necessary to use `napi_make_callback` from within a -`napi_async_complete_callback`; in that situation the callback's async -context has already been set up, so a direct call to `napi_call_function` -is sufficient and appropriate. Use of the `napi_make_callback` function -may be required when implementing custom async behavior that does not use -`napi_create_async_work`. - -Any `process.nextTick`s or Promises scheduled on the microtask queue by -JavaScript during the callback are ran before returning back to C/C++. - -### napi_open_callback_scope - - -```c -NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env, - napi_value resource_object, - napi_async_context context, - napi_callback_scope* result) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] resource_object`: An object associated with the async work - that will be passed to possible `async_hooks` [`init` hooks][]. This - parameter has been deprecated and is ignored at runtime. Use the - `async_resource` parameter in [`napi_async_init`][] instead. -* `[in] context`: Context for the async operation that is invoking the callback. - This should be a value previously obtained from [`napi_async_init`][]. -* `[out] result`: The newly created scope. - -There are cases (for example, resolving promises) where it is -necessary to have the equivalent of the scope associated with a callback -in place when making certain N-API calls. If there is no other script on -the stack the [`napi_open_callback_scope`][] and -[`napi_close_callback_scope`][] functions can be used to open/close -the required scope. - -### napi_close_callback_scope - - -```c -NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env, - napi_callback_scope scope) -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] scope`: The scope to be closed. - -This API can be called even if there is a pending JavaScript exception. - -## Version management - -### napi_get_node_version - - -```c -typedef struct { - uint32_t major; - uint32_t minor; - uint32_t patch; - const char* release; -} napi_node_version; - -napi_status napi_get_node_version(napi_env env, - const napi_node_version** version); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] version`: A pointer to version information for Node.js itself. - -Returns `napi_ok` if the API succeeded. - -This function fills the `version` struct with the major, minor, and patch -version of Node.js that is currently running, and the `release` field with the -value of [`process.release.name`][`process.release`]. - -The returned buffer is statically allocated and does not need to be freed. - -### napi_get_version - - -```c -napi_status napi_get_version(napi_env env, - uint32_t* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] result`: The highest version of N-API supported. - -Returns `napi_ok` if the API succeeded. - -This API returns the highest N-API version supported by the -Node.js runtime. N-API is planned to be additive such that -newer releases of Node.js may support additional API functions. -In order to allow an addon to use a newer function when running with -versions of Node.js that support it, while providing -fallback behavior when running with Node.js versions that don't -support it: - -* Call `napi_get_version()` to determine if the API is available. -* If available, dynamically load a pointer to the function using `uv_dlsym()`. -* Use the dynamically loaded pointer to invoke the function. -* If the function is not available, provide an alternate implementation - that does not use the function. - -## Memory management - -### napi_adjust_external_memory - - -```c -NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env, - int64_t change_in_bytes, - int64_t* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] change_in_bytes`: The change in externally allocated memory that is kept - alive by JavaScript objects. -* `[out] result`: The adjusted value - -Returns `napi_ok` if the API succeeded. - -This function gives V8 an indication of the amount of externally allocated -memory that is kept alive by JavaScript objects (i.e. a JavaScript object -that points to its own memory allocated by a native module). Registering -externally allocated memory will trigger global garbage collections more -often than it would otherwise. - -## Promises - -N-API provides facilities for creating `Promise` objects as described in -[Section 25.4][] of the ECMA specification. It implements promises as a pair of -objects. When a promise is created by `napi_create_promise()`, a "deferred" -object is created and returned alongside the `Promise`. The deferred object is -bound to the created `Promise` and is the only means to resolve or reject the -`Promise` using `napi_resolve_deferred()` or `napi_reject_deferred()`. The -deferred object that is created by `napi_create_promise()` is freed by -`napi_resolve_deferred()` or `napi_reject_deferred()`. The `Promise` object may -be returned to JavaScript where it can be used in the usual fashion. - -For example, to create a promise and pass it to an asynchronous worker: - -```c -napi_deferred deferred; -napi_value promise; -napi_status status; - -// Create the promise. -status = napi_create_promise(env, &deferred, &promise); -if (status != napi_ok) return NULL; - -// Pass the deferred to a function that performs an asynchronous action. -do_something_asynchronous(deferred); - -// Return the promise to JS -return promise; -``` - -The above function `do_something_asynchronous()` would perform its asynchronous -action and then it would resolve or reject the deferred, thereby concluding the -promise and freeing the deferred: - -```c -napi_deferred deferred; -napi_value undefined; -napi_status status; - -// Create a value with which to conclude the deferred. -status = napi_get_undefined(env, &undefined); -if (status != napi_ok) return NULL; - -// Resolve or reject the promise associated with the deferred depending on -// whether the asynchronous action succeeded. -if (asynchronous_action_succeeded) { - status = napi_resolve_deferred(env, deferred, undefined); -} else { - status = napi_reject_deferred(env, deferred, undefined); -} -if (status != napi_ok) return NULL; - -// At this point the deferred has been freed, so we should assign NULL to it. -deferred = NULL; -``` - -### napi_create_promise - - -```c -napi_status napi_create_promise(napi_env env, - napi_deferred* deferred, - napi_value* promise); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] deferred`: A newly created deferred object which can later be passed to - `napi_resolve_deferred()` or `napi_reject_deferred()` to resolve resp. reject - the associated promise. -* `[out] promise`: The JavaScript promise associated with the deferred object. - -Returns `napi_ok` if the API succeeded. - -This API creates a deferred object and a JavaScript promise. - -### napi_resolve_deferred - - -```c -napi_status napi_resolve_deferred(napi_env env, - napi_deferred deferred, - napi_value resolution); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] deferred`: The deferred object whose associated promise to resolve. -* `[in] resolution`: The value with which to resolve the promise. - -This API resolves a JavaScript promise by way of the deferred object -with which it is associated. Thus, it can only be used to resolve JavaScript -promises for which the corresponding deferred object is available. This -effectively means that the promise must have been created using -`napi_create_promise()` and the deferred object returned from that call must -have been retained in order to be passed to this API. - -The deferred object is freed upon successful completion. - -### napi_reject_deferred - - -```c -napi_status napi_reject_deferred(napi_env env, - napi_deferred deferred, - napi_value rejection); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] deferred`: The deferred object whose associated promise to resolve. -* `[in] rejection`: The value with which to reject the promise. - -This API rejects a JavaScript promise by way of the deferred object -with which it is associated. Thus, it can only be used to reject JavaScript -promises for which the corresponding deferred object is available. This -effectively means that the promise must have been created using -`napi_create_promise()` and the deferred object returned from that call must -have been retained in order to be passed to this API. - -The deferred object is freed upon successful completion. - -### napi_is_promise - - -```c -napi_status napi_is_promise(napi_env env, - napi_value value, - bool* is_promise); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] value`: The value to examine -* `[out] is_promise`: Flag indicating whether `promise` is a native promise - object (that is, a promise object created by the underlying engine). - -## Script execution - -N-API provides an API for executing a string containing JavaScript using the -underlying JavaScript engine. - -### napi_run_script - - -```c -NAPI_EXTERN napi_status napi_run_script(napi_env env, - napi_value script, - napi_value* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] script`: A JavaScript string containing the script to execute. -* `[out] result`: The value resulting from having executed the script. - -This function executes a string of JavaScript code and returns its result with -the following caveats: - -* Unlike `eval`, this function does not allow the script to access the current - lexical scope, and therefore also does not allow to access the - [module scope][], meaning that pseudo-globals such as `require` will not be - available. -* The script can access the [global scope][]. Function and `var` declarations - in the script will be added to the [`global`][] object. Variable declarations - made using `let` and `const` will be visible globally, but will not be added - to the [`global`][] object. -* The value of `this` is [`global`][] within the script. - -## libuv event loop - -N-API provides a function for getting the current event loop associated with -a specific `napi_env`. - -### napi_get_uv_event_loop - - -```c -NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env, - struct uv_loop_s** loop); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[out] loop`: The current libuv loop instance. - -## Asynchronous thread-safe function calls - -JavaScript functions can normally only be called from a native addon's main -thread. If an addon creates additional threads, then N-API functions that -require a `napi_env`, `napi_value`, or `napi_ref` must not be called from those -threads. - -When an addon has additional threads and JavaScript functions need to be invoked -based on the processing completed by those threads, those threads must -communicate with the addon's main thread so that the main thread can invoke the -JavaScript function on their behalf. The thread-safe function APIs provide an -easy way to do this. - -These APIs provide the type `napi_threadsafe_function` as well as APIs to -create, destroy, and call objects of this type. -`napi_create_threadsafe_function()` creates a persistent reference to a -`napi_value` that holds a JavaScript function which can be called from multiple -threads. The calls happen asynchronously. This means that values with which the -JavaScript callback is to be called will be placed in a queue, and, for each -value in the queue, a call will eventually be made to the JavaScript function. - -Upon creation of a `napi_threadsafe_function` a `napi_finalize` callback can be -provided. This callback will be invoked on the main thread when the thread-safe -function is about to be destroyed. It receives the context and the finalize data -given during construction, and provides an opportunity for cleaning up after the -threads e.g. by calling `uv_thread_join()`. **Aside from the main loop thread, -no threads should be using the thread-safe function after the finalize callback -completes.** - -The `context` given during the call to `napi_create_threadsafe_function()` can -be retrieved from any thread with a call to -`napi_get_threadsafe_function_context()`. - -### Calling a thread-safe function - -`napi_call_threadsafe_function()` can be used for initiating a call into -JavaScript. `napi_call_threadsafe_function()` accepts a parameter which controls -whether the API behaves blockingly. If set to `napi_tsfn_nonblocking`, the API -behaves non-blockingly, returning `napi_queue_full` if the queue was full, -preventing data from being successfully added to the queue. If set to -`napi_tsfn_blocking`, the API blocks until space becomes available in the queue. -`napi_call_threadsafe_function()` never blocks if the thread-safe function was -created with a maximum queue size of 0. - -`napi_call_threadsafe_function()` should not be called with `napi_tsfn_blocking` -from a JavaScript thread, because, if the queue is full, it may cause the -JavaScript thread to deadlock. - -The actual call into JavaScript is controlled by the callback given via the -`call_js_cb` parameter. `call_js_cb` is invoked on the main thread once for each -value that was placed into the queue by a successful call to -`napi_call_threadsafe_function()`. If such a callback is not given, a default -callback will be used, and the resulting JavaScript call will have no arguments. -The `call_js_cb` callback receives the JavaScript function to call as a -`napi_value` in its parameters, as well as the `void*` context pointer used when -creating the `napi_threadsafe_function`, and the next data pointer that was -created by one of the secondary threads. The callback can then use an API such -as `napi_call_function()` to call into JavaScript. - -The callback may also be invoked with `env` and `call_js_cb` both set to `NULL` -to indicate that calls into JavaScript are no longer possible, while items -remain in the queue that may need to be freed. This normally occurs when the -Node.js process exits while there is a thread-safe function still active. - -It is not necessary to call into JavaScript via `napi_make_callback()` because -N-API runs `call_js_cb` in a context appropriate for callbacks. - -### Reference counting of thread-safe functions - -Threads can be added to and removed from a `napi_threadsafe_function` object -during its existence. Thus, in addition to specifying an initial number of -threads upon creation, `napi_acquire_threadsafe_function` can be called to -indicate that a new thread will start making use of the thread-safe function. -Similarly, `napi_release_threadsafe_function` can be called to indicate that an -existing thread will stop making use of the thread-safe function. - -`napi_threadsafe_function` objects are destroyed when every thread which uses -the object has called `napi_release_threadsafe_function()` or has received a -return status of `napi_closing` in response to a call to -`napi_call_threadsafe_function`. The queue is emptied before the -`napi_threadsafe_function` is destroyed. `napi_release_threadsafe_function()` -should be the last API call made in conjunction with a given -`napi_threadsafe_function`, because after the call completes, there is no -guarantee that the `napi_threadsafe_function` is still allocated. For the same -reason, do not use a thread-safe function -after receiving a return value of `napi_closing` in response to a call to -`napi_call_threadsafe_function`. Data associated with the -`napi_threadsafe_function` can be freed in its `napi_finalize` callback which -was passed to `napi_create_threadsafe_function()`. The parameter -`initial_thread_count` of `napi_create_threadsafe_function` marks the initial -number of aquisitions of the thread-safe functions, instead of calling -`napi_acquire_threadsafe_function` multiple times at creation. - -Once the number of threads making use of a `napi_threadsafe_function` reaches -zero, no further threads can start making use of it by calling -`napi_acquire_threadsafe_function()`. In fact, all subsequent API calls -associated with it, except `napi_release_threadsafe_function()`, will return an -error value of `napi_closing`. - -The thread-safe function can be "aborted" by giving a value of `napi_tsfn_abort` -to `napi_release_threadsafe_function()`. This will cause all subsequent APIs -associated with the thread-safe function except -`napi_release_threadsafe_function()` to return `napi_closing` even before its -reference count reaches zero. In particular, `napi_call_threadsafe_function()` -will return `napi_closing`, thus informing the threads that it is no longer -possible to make asynchronous calls to the thread-safe function. This can be -used as a criterion for terminating the thread. **Upon receiving a return value -of `napi_closing` from `napi_call_threadsafe_function()` a thread must not use -the thread-safe function anymore because it is no longer guaranteed to -be allocated.** - -### Deciding whether to keep the process running - -Similarly to libuv handles, thread-safe functions can be "referenced" and -"unreferenced". A "referenced" thread-safe function will cause the event loop on -the thread on which it is created to remain alive until the thread-safe function -is destroyed. In contrast, an "unreferenced" thread-safe function will not -prevent the event loop from exiting. The APIs `napi_ref_threadsafe_function` and -`napi_unref_threadsafe_function` exist for this purpose. - -Neither does `napi_unref_threadsafe_function` mark the thread-safe functions as -able to be destroyed nor does `napi_ref_threadsafe_function` prevent it from -being destroyed. - -### napi_create_threadsafe_function - - - -```c -NAPI_EXTERN napi_status -napi_create_threadsafe_function(napi_env env, - napi_value func, - napi_value async_resource, - napi_value async_resource_name, - size_t max_queue_size, - size_t initial_thread_count, - void* thread_finalize_data, - napi_finalize thread_finalize_cb, - void* context, - napi_threadsafe_function_call_js call_js_cb, - napi_threadsafe_function* result); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] func`: An optional JavaScript function to call from another thread. It - must be provided if `NULL` is passed to `call_js_cb`. -* `[in] async_resource`: An optional object associated with the async work that - will be passed to possible `async_hooks` [`init` hooks][]. -* `[in] async_resource_name`: A JavaScript string to provide an identifier for - the kind of resource that is being provided for diagnostic information exposed - by the `async_hooks` API. -* `[in] max_queue_size`: Maximum size of the queue. `0` for no limit. -* `[in] initial_thread_count`: The initial number of acquisitions, i.e. the - initial number of threads, including the main thread, which will be making use - of this function. -* `[in] thread_finalize_data`: Optional data to be passed to `thread_finalize_cb`. -* `[in] thread_finalize_cb`: Optional function to call when the - `napi_threadsafe_function` is being destroyed. -* `[in] context`: Optional data to attach to the resulting - `napi_threadsafe_function`. -* `[in] call_js_cb`: Optional callback which calls the JavaScript function in - response to a call on a different thread. This callback will be called on the - main thread. If not given, the JavaScript function will be called with no - parameters and with `undefined` as its `this` value. - [`napi_threadsafe_function_call_js`][] provides more details. -* `[out] result`: The asynchronous thread-safe JavaScript function. - -### napi_get_threadsafe_function_context - - - -```c -NAPI_EXTERN napi_status -napi_get_threadsafe_function_context(napi_threadsafe_function func, - void** result); -``` - -* `[in] func`: The thread-safe function for which to retrieve the context. -* `[out] result`: The location where to store the context. - -This API may be called from any thread which makes use of `func`. - -### napi_call_threadsafe_function - - - -```c -NAPI_EXTERN napi_status -napi_call_threadsafe_function(napi_threadsafe_function func, - void* data, - napi_threadsafe_function_call_mode is_blocking); -``` - -* `[in] func`: The asynchronous thread-safe JavaScript function to invoke. -* `[in] data`: Data to send into JavaScript via the callback `call_js_cb` - provided during the creation of the thread-safe JavaScript function. -* `[in] is_blocking`: Flag whose value can be either `napi_tsfn_blocking` to - indicate that the call should block if the queue is full or - `napi_tsfn_nonblocking` to indicate that the call should return immediately - with a status of `napi_queue_full` whenever the queue is full. - -This API should not be called with `napi_tsfn_blocking` from a JavaScript -thread, because, if the queue is full, it may cause the JavaScript thread to -deadlock. - -This API will return `napi_closing` if `napi_release_threadsafe_function()` was -called with `abort` set to `napi_tsfn_abort` from any thread. The value is only -added to the queue if the API returns `napi_ok`. - -This API may be called from any thread which makes use of `func`. - -### napi_acquire_threadsafe_function - - - -```c -NAPI_EXTERN napi_status -napi_acquire_threadsafe_function(napi_threadsafe_function func); -``` - -* `[in] func`: The asynchronous thread-safe JavaScript function to start making - use of. - -A thread should call this API before passing `func` to any other thread-safe -function APIs to indicate that it will be making use of `func`. This prevents -`func` from being destroyed when all other threads have stopped making use of -it. - -This API may be called from any thread which will start making use of `func`. - -### napi_release_threadsafe_function - - - -```c -NAPI_EXTERN napi_status -napi_release_threadsafe_function(napi_threadsafe_function func, - napi_threadsafe_function_release_mode mode); -``` - -* `[in] func`: The asynchronous thread-safe JavaScript function whose reference - count to decrement. -* `[in] mode`: Flag whose value can be either `napi_tsfn_release` to indicate - that the current thread will make no further calls to the thread-safe - function, or `napi_tsfn_abort` to indicate that in addition to the current - thread, no other thread should make any further calls to the thread-safe - function. If set to `napi_tsfn_abort`, further calls to - `napi_call_threadsafe_function()` will return `napi_closing`, and no further - values will be placed in the queue. - -A thread should call this API when it stops making use of `func`. Passing `func` -to any thread-safe APIs after having called this API has undefined results, as -`func` may have been destroyed. - -This API may be called from any thread which will stop making use of `func`. - -### napi_ref_threadsafe_function - - - -```c -NAPI_EXTERN napi_status -napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] func`: The thread-safe function to reference. - -This API is used to indicate that the event loop running on the main thread -should not exit until `func` has been destroyed. Similar to [`uv_ref`][] it is -also idempotent. - -Neither does `napi_unref_threadsafe_function` mark the thread-safe functions as -able to be destroyed nor does `napi_ref_threadsafe_function` prevent it from -being destroyed. `napi_acquire_threadsafe_function` and -`napi_release_threadsafe_function` are available for that purpose. - -This API may only be called from the main thread. - -### napi_unref_threadsafe_function - - - -```c -NAPI_EXTERN napi_status -napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func); -``` - -* `[in] env`: The environment that the API is invoked under. -* `[in] func`: The thread-safe function to unreference. - -This API is used to indicate that the event loop running on the main thread -may exit before `func` is destroyed. Similar to [`uv_unref`][] it is also -idempotent. - -This API may only be called from the main thread. - -[ABI Stability]: https://nodejs.org/en/docs/guides/abi-stability/ -[AppVeyor]: https://www.appveyor.com -[C++ Addons]: addons.md -[CMake]: https://cmake.org -[CMake.js]: https://github.com/cmake-js/cmake-js -[ECMAScript Language Specification]: https://tc39.github.io/ecma262/ -[Error handling]: #n_api_error_handling -[GCC]: https://gcc.gnu.org -[GYP]: https://gyp.gsrc.io -[GitHub releases]: https://help.github.com/en/github/administering-a-repository/about-releases -[LLVM]: https://llvm.org -[Native Abstractions for Node.js]: https://github.com/nodejs/nan -[Object lifetime management]: #n_api_object_lifetime_management -[Object wrap]: #n_api_object_wrap -[Section 12.10.4]: https://tc39.github.io/ecma262/#sec-instanceofoperator -[Section 12.5.5]: https://tc39.github.io/ecma262/#sec-typeof-operator -[Section 19.2]: https://tc39.github.io/ecma262/#sec-function-objects -[Section 19.4]: https://tc39.github.io/ecma262/#sec-symbol-objects -[Section 20.3]: https://tc39.github.io/ecma262/#sec-date-objects -[Section 22.1]: https://tc39.github.io/ecma262/#sec-array-objects -[Section 22.1.4.1]: https://tc39.github.io/ecma262/#sec-properties-of-array-instances-length -[Section 22.2]: https://tc39.github.io/ecma262/#sec-typedarray-objects -[Section 24.1]: https://tc39.github.io/ecma262/#sec-arraybuffer-objects -[Section 24.1.1.2]: https://tc39.es/ecma262/#sec-isdetachedbuffer -[Section 24.1.1.3]: https://tc39.es/ecma262/#sec-detacharraybuffer -[Section 24.3]: https://tc39.github.io/ecma262/#sec-dataview-objects -[Section 25.4]: https://tc39.github.io/ecma262/#sec-promise-objects -[Section 6]: https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values -[Section 6.1]: https://tc39.github.io/ecma262/#sec-ecmascript-language-types -[Section 6.1.4]: https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type -[Section 6.1.6]: https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type -[Section 6.1.7]: https://tc39.github.io/ecma262/#sec-object-type -[Section 6.1.7.1]: https://tc39.github.io/ecma262/#table-2 -[Section 7]: https://tc39.github.io/ecma262/#sec-abstract-operations -[Section 7.1.13]: https://tc39.github.io/ecma262/#sec-toobject -[Section 7.1.2]: https://tc39.github.io/ecma262/#sec-toboolean -[Section 7.1.3]: https://tc39.github.io/ecma262/#sec-tonumber -[Section 7.2.14]: https://tc39.github.io/ecma262/#sec-strict-equality-comparison -[Section 7.2.2]: https://tc39.github.io/ecma262/#sec-isarray -[Section 8.7]: https://tc39.es/ecma262/#sec-agents -[Section 9.1.6]: https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-defineownproperty-p-desc -[Travis CI]: https://travis-ci.org -[Visual Studio]: https://visualstudio.microsoft.com -[Working with JavaScript properties]: #n_api_working_with_javascript_properties -[Xcode]: https://developer.apple.com/xcode/ -[`Number.MAX_SAFE_INTEGER`]: https://tc39.github.io/ecma262/#sec-number.max_safe_integer -[`Number.MIN_SAFE_INTEGER`]: https://tc39.github.io/ecma262/#sec-number.min_safe_integer -[`Worker`]: worker_threads.md#worker_threads_class_worker -[`async_hooks.executionAsyncResource()`]: async_hooks.md#async_hooks_async_hooks_executionasyncresource -[`global`]: globals.md#globals_global -[`init` hooks]: async_hooks.md#async_hooks_init_asyncid_type_triggerasyncid_resource -[`napi_add_async_cleanup_hook`]: #n_api_napi_add_async_cleanup_hook -[`napi_add_env_cleanup_hook`]: #n_api_napi_add_env_cleanup_hook -[`napi_add_finalizer`]: #n_api_napi_add_finalizer -[`napi_async_cleanup_hook`]: #n_api_napi_async_cleanup_hook -[`napi_async_complete_callback`]: #n_api_napi_async_complete_callback -[`napi_async_destroy`]: #n_api_napi_async_destroy -[`napi_async_init`]: #n_api_napi_async_init -[`napi_callback`]: #n_api_napi_callback -[`napi_cancel_async_work`]: #n_api_napi_cancel_async_work -[`napi_close_callback_scope`]: #n_api_napi_close_callback_scope -[`napi_close_escapable_handle_scope`]: #n_api_napi_close_escapable_handle_scope -[`napi_close_handle_scope`]: #n_api_napi_close_handle_scope -[`napi_create_async_work`]: #n_api_napi_create_async_work -[`napi_create_error`]: #n_api_napi_create_error -[`napi_create_external_arraybuffer`]: #n_api_napi_create_external_arraybuffer -[`napi_create_range_error`]: #n_api_napi_create_range_error -[`napi_create_reference`]: #n_api_napi_create_reference -[`napi_create_type_error`]: #n_api_napi_create_type_error -[`napi_define_class`]: #n_api_napi_define_class -[`napi_delete_async_work`]: #n_api_napi_delete_async_work -[`napi_delete_reference`]: #n_api_napi_delete_reference -[`napi_escape_handle`]: #n_api_napi_escape_handle -[`napi_finalize`]: #n_api_napi_finalize -[`napi_get_and_clear_last_exception`]: #n_api_napi_get_and_clear_last_exception -[`napi_get_array_length`]: #n_api_napi_get_array_length -[`napi_get_element`]: #n_api_napi_get_element -[`napi_get_last_error_info`]: #n_api_napi_get_last_error_info -[`napi_get_property`]: #n_api_napi_get_property -[`napi_get_reference_value`]: #n_api_napi_get_reference_value -[`napi_get_value_external`]: #n_api_napi_get_value_external -[`napi_has_property`]: #n_api_napi_has_property -[`napi_instanceof`]: #n_api_napi_instanceof -[`napi_is_error`]: #n_api_napi_is_error -[`napi_is_exception_pending`]: #n_api_napi_is_exception_pending -[`napi_make_callback`]: #n_api_napi_make_callback -[`napi_open_callback_scope`]: #n_api_napi_open_callback_scope -[`napi_open_escapable_handle_scope`]: #n_api_napi_open_escapable_handle_scope -[`napi_open_handle_scope`]: #n_api_napi_open_handle_scope -[`napi_property_attributes`]: #n_api_napi_property_attributes -[`napi_property_descriptor`]: #n_api_napi_property_descriptor -[`napi_queue_async_work`]: #n_api_napi_queue_async_work -[`napi_reference_ref`]: #n_api_napi_reference_ref -[`napi_reference_unref`]: #n_api_napi_reference_unref -[`napi_remove_async_cleanup_hook`]: #n_api_napi_remove_async_cleanup_hook -[`napi_remove_env_cleanup_hook`]: #n_api_napi_remove_env_cleanup_hook -[`napi_set_instance_data`]: #n_api_napi_set_instance_data -[`napi_set_property`]: #n_api_napi_set_property -[`napi_threadsafe_function_call_js`]: #n_api_napi_threadsafe_function_call_js -[`napi_throw_error`]: #n_api_napi_throw_error -[`napi_throw_range_error`]: #n_api_napi_throw_range_error -[`napi_throw_type_error`]: #n_api_napi_throw_type_error -[`napi_throw`]: #n_api_napi_throw -[`napi_unwrap`]: #n_api_napi_unwrap -[`napi_wrap`]: #n_api_napi_wrap -[`node-addon-api`]: https://github.com/nodejs/node-addon-api -[`node_api.h`]: https://github.com/nodejs/node/blob/master/src/node_api.h -[`process.release`]: process.md#process_process_release -[`uv_ref`]: https://docs.libuv.org/en/v1.x/handle.html#c.uv_ref -[`uv_unref`]: https://docs.libuv.org/en/v1.x/handle.html#c.uv_unref -[async_hooks `type`]: async_hooks.md#async_hooks_type -[context-aware addons]: addons.md#addons_context_aware_addons -[docs]: https://github.com/nodejs/node-addon-api#api-documentation -[global scope]: globals.md -[module scope]: modules.md#modules_the_module_scope -[node-gyp]: https://github.com/nodejs/node-gyp -[node-pre-gyp]: https://github.com/mapbox/node-pre-gyp -[prebuild]: https://github.com/prebuild/prebuild -[prebuildify]: https://github.com/prebuild/prebuildify -[worker threads]: https://nodejs.org/api/worker_threads.html diff --git a/doc/api/node-api.md b/doc/api/node-api.md new file mode 100644 index 00000000000000..ab0663b76001b6 --- /dev/null +++ b/doc/api/node-api.md @@ -0,0 +1,6172 @@ +#The Node.js API + + + + +> Stability: 2 - Stable + +The Node.js API is an API for building native Addons. It is independent from +the underlying JavaScript runtime (for example, V8) and is maintained as part +of Node.js itself. This API will be Application Binary Interface (ABI) stable +across versions of Node.js. It is intended to insulate Addons from +changes in the underlying JavaScript engine and allow modules +compiled for one major version to run on later major versions of Node.js +without recompilation. The [ABI Stability][] guide provides a more in-depth +explanation. + +Addons are built/packaged with the same approach/tools outlined in the section +titled [C++ Addons][]. The only difference is the set of APIs that are used by +the native code. Instead of using the V8 or [Native Abstractions for Node.js][] +APIs, the functions available in the Node.js API are used. + +APIs exposed by the Node.js API are generally used to create and manipulate +JavaScript values. Concepts and operations generally map to ideas specified +in the ECMA-262 Language Specification. The APIs have the following +properties: + +* All Node.js API calls return a status code of type `node_api_status`. This + status indicates whether the API call succeeded or failed. +* The API's return value is passed via an out parameter. +* All JavaScript values are abstracted behind an opaque type named + `node_api_value`. +* In case of an error status code, additional information can be obtained + using `node_api_get_last_error_info`. More information can be found in the + error handling section [Error handling][]. + +The Node.js API is a C API that ensures ABI stability across Node.js versions +and different compiler levels. A C++ API can be easier to use. +To support using C++, the project maintains a +C++ wrapper module called [`node-addon-api`][]. +This wrapper provides an inlineable C++ API. Binaries built +with `node-addon-api` will depend on the symbols for the Node.js API C-based +functions exported by Node.js. `node-addon-api` is a more +efficient way to write code that calls the Node.js API. Take, for example, the +following `node-addon-api` code. The first section shows the +`node-addon-api` code and the second section shows what actually gets +used in the addon. + +```cpp +Object obj = Object::New(env); +obj["foo"] = String::New(env, "bar"); +``` + +```cpp +node_api_status status; +node_api_value object, string; +status = node_api_create_object(env, &object); +if (status != node_api_ok) { + node_api_throw_error(env, ...); + return; +} + +status = + node_api_create_string_utf8(env, "bar", NODE_API_AUTO_LENGTH, &string); +if (status != node_api_ok) { + node_api_throw_error(env, ...); + return; +} + +status = node_api_set_named_property(env, object, "foo", string); +if (status != node_api_ok) { + node_api_throw_error(env, ...); + return; +} +``` + +The end result is that the addon only uses the exported C APIs. As a result, +it still gets the benefits of the ABI stability provided by the C API. + +When using `node-addon-api` instead of the C APIs, start with the API [docs][] +for `node-addon-api`. + +The [Node.js API Resource](https://nodejs.github.io/node-addon-examples/) +offers an excellent orientation and tips for developers just getting started +with the Node.js API and `node-addon-api`. + +# Implications of ABI stability + +Although the Node.js API provides an ABI stability guarantee, other parts of +Node.js do not, and any external libraries used from the addon may not. In +particular, none of the following APIs provide an ABI stability guarantee +across major versions: + +* the Node.js C++ APIs available via any of + + ```cpp + #include + #include + #include + #include + ``` + +* the libuv APIs which are also included with Node.js and available via + + ```cpp + #include + ``` + +* the V8 API available via + + ```cpp + #include + ``` + +Thus, for an addon to remain ABI-compatible across Node.js major versions, it +must use the Node.js API exclusively by restricting itself to using + +```c +#include +``` + +and by checking, for all external libraries that it uses, that the external +library makes ABI stability guarantees similar to the Node.js API. + +## Building + +Unlike modules written in JavaScript, developing and deploying Node.js +native addons using the Node.js API requires an additional set of tools. +Besides the basic tools required to develop for Node.js, the native addon +developer requires a toolchain that can compile C and C++ code into a binary. +In addition, depending upon how the native addon is deployed, the *user* of +the native addon will also need to have a C/C++ toolchain installed. + +For Linux developers, the necessary C/C++ toolchain packages are readily +available. [GCC][] is widely used in the Node.js community to build and +test across a variety of platforms. For many developers, the [LLVM][] +compiler infrastructure is also a good choice. + +For Mac developers, [Xcode][] offers all the required compiler tools. +However, it is not necessary to install the entire Xcode IDE. The following +command installs the necessary toolchain: + +```bash +xcode-select --install +``` + +For Windows developers, [Visual Studio][] offers all the required compiler +tools. However, it is not necessary to install the entire Visual Studio +IDE. The following command installs the necessary toolchain: + +```bash +npm install --global windows-build-tools +``` + +The sections below describe the additional tools available for developing +and deploying Node.js native addons. + +### Build tools + +Both the tools listed here require that *users* of the native +addon have a C/C++ toolchain installed in order to successfully install +the native addon. + +#### node-gyp + +[node-gyp][] is a build system based on Google's [GYP][] tool and comes +bundled with npm. GYP, and therefore node-gyp, requires that Python be +installed. + +Historically, node-gyp has been the tool of choice for building native +addons. It has widespread adoption and documentation. However, some +developers have run into limitations in node-gyp. + +#### CMake.js + +[CMake.js][] is an alternative build system based on [CMake][]. + +CMake.js is a good choice for projects that already use CMake or for +developers affected by limitations in node-gyp. + +### Uploading precompiled binaries + +The three tools listed here permit native addon developers and maintainers +to create and upload binaries to public or private servers. These tools are +typically integrated with CI/CD build systems like [Travis CI][] and +[AppVeyor][] to build and upload binaries for a variety of platforms and +architectures. These binaries are then available for download by users who +do not need to have a C/C++ toolchain installed. + +#### node-pre-gyp + +[node-pre-gyp][] is a tool based on node-gyp that adds the ability to +upload binaries to a server of the developer's choice. node-pre-gyp has +particularly good support for uploading binaries to Amazon S3. + +#### prebuild + +[prebuild][] is a tool that supports builds using either node-gyp or +CMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild +uploads binaries only to [GitHub releases][]. prebuild is a good choice for +GitHub projects using CMake.js. + +#### prebuildify + +[prebuildify][] is a tool based on node-gyp. The advantage of prebuildify is +that the built binaries are bundled with the native module when it's +uploaded to npm. The binaries are downloaded from npm and are immediately +available to the module user when the native module is installed. + +## Usage + +In order to use the Node.js API functions, include the file [`node_api.h`][] +which is located in the src directory in the node development tree: + +```c +#include +``` + +This will opt into the default `NODE_API_VERSION` for the given release of +Node.js. In order to ensure compatibility with specific versions of the Node.js +API, the version can be specified explicitly when including the header: + +```c +#define NODE_API_VERSION 3 +#include +``` + +This restricts the Node.js API surface to just the functionality that was +available in the specified (and earlier) versions. + +Some of the Node.js API surface is experimental and requires explicit opt-in: + +```c +#define NODE_API_EXPERIMENTAL +#include +``` + +In this case the entire API surface, including any experimental APIs, will be +available to the module code. + +## The Node.js API version matrix + +Node.js API versions are additive and versioned independently from Node.js. +Version 4 is an extension to version 3 in that it has all of the APIs +from version 3 with some additions. This means that it is not necessary +to recompile for new versions of Node.js which are +listed as supporting a later version. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
123
v6.xv6.14.2*
v8.xv8.6.0**v8.10.0*v8.11.2
v9.xv9.0.0*v9.3.0*v9.11.0*
≥ v10.xall releasesall releasesall releases
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
4567
v10.xv10.16.0v10.17.0v10.20.0
v11.xv11.8.0
v12.xv12.0.0v12.11.0v12.17.0v12.19.0
v13.xv13.0.0v13.0.0
v14.xv14.0.0v14.0.0v14.0.0v14.12.0
+ +\* The Node.js API was experimental. + +\*\* Node.js 8.0.0 included the Node.js API as experimental. It was released as +the Node.js API version 1 but continued to evolve until Node.js 8.6.0. The API +is different in versions prior to Node.js 8.6.0. We recommend the Node.js API +version 3 or later. + +Each API documented for the Node.js API will have a header named `added in:`, +and APIs which are stable will have the additional header +`Node.js API version:`. +APIs are directly usable when using a Node.js version which supports +the Node.js API version shown in `The Node.js API version:` or higher. +When using a Node.js version that does not support the header +`Node.js API version:` listed or if there is no `Node.js API version:` listed, +then the API will only be available if +`#define NODE_API_EXPERIMENTAL` precedes the inclusion of `node_api.h` +or `js_native_api.h`. If an API appears not to be available on +a version of Node.js which is later than the one shown in `added in:` then +this is most likely the reason for the apparent absence. + +The Node.js APIs associated strictly with accessing ECMAScript features from +native code can be found separately in `js_native_api.h` and +`js_native_api_types.h`. The APIs defined in these headers are included in +`node_api.h` and `node_api_types.h`. The headers are structured in this way in +order to allow implementations of the Node.js API outside of Node.js. For those +implementations the Node.js specific APIs may not be applicable. + +The Node.js-specific parts of an addon can be separated from the code that +exposes the actual functionality to the JavaScript environment so that the +latter may be used with multiple implementations of the Node.js API. In the +example below, `addon.c` and `addon.h` refer only to `js_native_api.h`. This +ensures that `addon.c` can be reused to compile against either the Node.js +implementation of the Node.js API or any implementation of the Node.js API +outside of Node.js. + +`addon_node.c` is a separate file that contains the Node.js specific entry +point to the addon and which instantiates the addon by calling into `addon.c` +when the addon is loaded into a Node.js environment. + +```c +// addon.h +#ifndef _ADDON_H_ +#define _ADDON_H_ +#include +node_api_value create_addon(node_api_env env); +#endif // _ADDON_H_ +``` + +```c +// addon.c +#include "addon.h" + +#define NODE_API_CALL(env, call) \ + do { \ + node_api_status status = (call); \ + if (status != node_api_ok) { \ + const node_api_extended_error_info* error_info = NULL; \ + node_api_get_last_error_info((env), &error_info); \ + bool is_pending; \ + node_api_is_exception_pending((env), &is_pending); \ + if (!is_pending) { \ + const char* message = (error_info->error_message == NULL) \ + ? "empty error message" \ + : error_info->error_message; \ + node_api_throw_error((env), NULL, message); \ + return NULL; \ + } \ + } \ + } while(0) + +static node_api_value +DoSomethingUseful(node_api_env env, node_api_callback_info info) { + // Do something useful. + return NULL; +} + +node_api_value create_addon(node_api_env env) { + node_api_value result; + NODE_API_CALL(env, node_api_create_object(env, &result)); + + node_api_value exported_function; + NODE_API_CALL(env, node_api_create_function(env, + "doSomethingUseful", + NODE_API_AUTO_LENGTH, + DoSomethingUseful, + NULL, + &exported_function)); + + NODE_API_CALL(env, node_api_set_named_property(env, + result, + "doSomethingUseful", + exported_function)); + + return result; +} +``` + +```c +// addon_node.c +#include +#include "addon.h" + +NODE_API_MODULE_INIT() { + // This function body is expected to return a `node_api_value`. + // The variables `node_api_env env` and `node_api_value exports` may be used + // within the body, as they are provided by the definition of + // `NODE_API_MODULE_INIT()`. + return create_addon(env); +} +``` + +## Environment life cycle APIs + +[Section 8.7][] of the [ECMAScript Language Specification][] defines the +concept of an "Agent" as a self-contained environment in which JavaScript code +runs. Multiple such Agents may be started and terminated either concurrently or +in sequence by the process. + +A Node.js environment corresponds to an ECMAScript Agent. In the main process, +an environment is created at startup, and additional environments can be +created on separate threads to serve as [worker threads][]. When Node.js is +embedded in another application, the main thread of the application may also +construct and destroy a Node.js environment multiple times during the life +cycle of the application process such that each Node.js environment created by +the application may, in turn, during its life cycle create and destroy +additional environments as worker threads. + +From the perspective of a native addon this means that the bindings it provides +may be called multiple times, from multiple contexts, and even concurrently +from multiple threads. + +Native addons may need to allocate global state which they use during +their entire life cycle such that the state must be unique to each instance of +the addon. + +To this end, the Node.js API provides a way to allocate data such that its life +cycle is tied to the life cycle of the Agent. + +### node_api_set_instance_data + + +```c +node_api_status node_api_set_instance_data(node_api_env env, + void* data, + node_api_finalize finalize_cb, + void* finalize_hint); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] data`: The data item to make available to bindings of this instance. +* `[in] finalize_cb`: The function to call when the environment is being torn + down. The function receives `data` so that it might free it. + [`node_api_finalize`][] provides more details. +* `[in] finalize_hint`: Optional hint to pass to the finalize callback during + collection. + +Returns `node_api_ok` if the API succeeded. + +This API associates `data` with the currently running Agent. `data` can later +be retrieved using `node_api_get_instance_data()`. Any existing data associated +with the currently running Agent which was set by means of a previous call to +`node_api_set_instance_data()` will be overwritten. If a `finalize_cb` was +provided by the previous call, it will not be called. + +### node_api_get_instance_data + + +```c +node_api_status node_api_get_instance_data(node_api_env env, + void** data); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[out] data`: The data item that was previously associated with the currently + running Agent by a call to `node_api_set_instance_data()`. + +Returns `node_api_ok` if the API succeeded. + +This API retrieves data that was previously associated with the currently +running Agent via `node_api_set_instance_data()`. If no data is set, the call +will succeed and `data` will be set to `NULL`. + +## Basic Node.js API data types + +The Node.js API exposes the following fundamental datatypes as abstractions +that are consumed by the various APIs. These APIs should be treated as opaque, +introspectable only with other Node.js API calls. + +### node_api_status + +Integral status code indicating the success or failure of a Node.js API call. +Currently, the following status codes are supported. + +```c +typedef enum { + node_api_ok, + node_api_invalid_arg, + node_api_object_expected, + node_api_string_expected, + node_api_name_expected, + node_api_function_expected, + node_api_number_expected, + node_api_boolean_expected, + node_api_array_expected, + node_api_generic_failure, + node_api_pending_exception, + node_api_cancelled, + node_api_escape_called_twice, + node_api_handle_scope_mismatch, + node_api_callback_scope_mismatch, + node_api_queue_full, + node_api_closing, + node_api_bigint_expected, + node_api_date_expected, + node_api_arraybuffer_expected, + node_api_detachable_arraybuffer_expected, + node_api_would_deadlock, /* unused */ +} node_api_status; +``` + +If additional information is required upon an API returning a failed status, +it can be obtained by calling `node_api_get_last_error_info`. + +### node_api_extended_error_info + + +```c +typedef struct { + const char* error_message; + void* engine_reserved; + uint32_t engine_error_code; + node_api_status error_code; +} node_api_extended_error_info; +``` + +* `error_message`: UTF8-encoded string containing a VM-neutral description of + the error. +* `engine_reserved`: Reserved for VM-specific error details. This is currently + not implemented for any VM. +* `engine_error_code`: VM-specific error code. This is currently + not implemented for any VM. +* `error_code`: The Node.js API status code that originated with the last + error. + +See the [Error handling][] section for additional information. + +### node_api_env + +`node_api_env` is used to represent a context that the underlying Node.js API +implementation can use to persist VM-specific state. This structure is passed +to native functions when they're invoked, and it must be passed back when +making Node.js API calls. Specifically, the same `node_api_env` that was passed +in when the initial native function was called must be passed to any subsequent +nested Node.js API calls. Caching the `node_api_env` for the purpose of general +reuse, and passing the `node_api_env` between instances of the same addon +running on different [`Worker`][] threads is not allowed. The `node_api_env` +becomes invalid when an instance of a native addon is unloaded. Notification of +this event is delivered through the callbacks given to +[`node_api_add_env_cleanup_hook`][] and [`node_api_set_instance_data`][]. + +### node_api_value + +This is an opaque pointer that is used to represent a JavaScript value. + +### node_api_threadsafe_function + + +This is an opaque pointer that represents a JavaScript function which can be +called asynchronously from multiple threads via +`node_api_call_threadsafe_function()`. + +### node_api_threadsafe_function_release_mode + + +A value to be given to `node_api_release_threadsafe_function()` to indicate +whether the thread-safe function is to be closed immediately +(`node_api_tsfn_abort`) or merely released (`node_api_tsfn_release`) and thus +available for subsequent use via `node_api_acquire_threadsafe_function()` and +`node_api_call_threadsafe_function()`. + +```c +typedef enum { + node_api_tsfn_release, + node_api_tsfn_abort +} node_api_threadsafe_function_release_mode; +``` + +### node_api_threadsafe_function_call_mode + + +A value to be given to `node_api_call_threadsafe_function()` to indicate +whether the call should block whenever the queue associated with the +thread-safe function is full. + +```c +typedef enum { + node_api_tsfn_nonblocking, + node_api_tsfn_blocking +} node_api_threadsafe_function_call_mode; +``` + +### Node.js API memory management types +#### node_api_handle_scope + +This is an abstraction used to control and modify the lifetime of objects +created within a particular scope. In general, Node.js API values are created +within the context of a handle scope. When a native method is called from +JavaScript, a default handle scope will exist. If the user does not explicitly +create a new handle scope, Node.js API values will be created in the default +handle scope. For any invocations of code outside the execution of a native +method (for instance, during a libuv callback invocation), the module is +required to create a scope before invoking any functions that can result in the +creation of JavaScript values. + +Handle scopes are created using [`node_api_open_handle_scope`][] and are +destroyed using [`node_api_close_handle_scope`][]. Closing the scope can +indicate to the GC that all `node_api_value`s created during the lifetime of +the handle scope are no longer referenced from the current stack frame. + +For more details, review the [Object lifetime management][]. + +#### node_api_escapable_handle_scope + +Escapable handle scopes are a special type of handle scope to return values +created within a particular handle scope to a parent scope. + +#### node_api_ref + +This is the abstraction to use to reference a `node_api_value`. This allows for +users to manage the lifetimes of JavaScript values, including defining their +minimum lifetimes explicitly. + +For more details, review the [Object lifetime management][]. + +#### node_api_type_tag + + +A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID +with which JavaScript objects can be "tagged" in order to ensure that they are +of a certain type. This is a stronger check than [`node_api_instanceof`][], +because the latter can report a false positive if the object's prototype has +been manipulated. Type-tagging is most useful in conjunction with +[`node_api_wrap`][] because it ensures that the pointer retrieved from a +wrapped object can be safely cast to the native type corresponding to the type +tag that had been previously applied to the JavaScript object. + +```c +typedef struct { + uint64_t lower; + uint64_t upper; +} node_api_type_tag; +``` + +#### node_api_async_cleanup_hook_handle + + +An opaque value returned by [`node_api_add_async_cleanup_hook`][]. It must be +passed to [`node_api_remove_async_cleanup_hook`][] when the chain of +asynchronous cleanup events completes. + +### Node.js API callback types + +#### node_api_callback_info + +Opaque datatype that is passed to a callback function. It can be used for +getting additional information about the context in which the callback was +invoked. + +#### node_api_callback + +Function pointer type for user-provided native functions which are to be +exposed to JavaScript via the Node.js API. Callback functions should satisfy +the following signature: + +```c +typedef node_api_value (*node_api_callback)(node_api_env, + node_api_callback_info); +``` + +Unless for reasons discussed in [Object Lifetime Management][], creating a +handle and/or callback scope inside a `node_api_callback` is not necessary. + +#### node_api_finalize + +Function pointer type for add-on provided functions that allow the user to be +notified when externally-owned data is ready to be cleaned up because the +object with which it was associated with, has been garbage-collected. The user +must provide a function satisfying the following signature which would get +called upon the object's collection. Currently, `node_api_finalize` can be used +for finding out when objects that have external data are collected. + +```c +typedef void (*node_api_finalize)(node_api_env env, + void* finalize_data, + void* finalize_hint); +``` + +Unless for reasons discussed in [Object Lifetime Management][], creating a +handle and/or callback scope inside the function body is not necessary. + +#### node_api_async_execute_callback + +Function pointer used with functions that support asynchronous +operations. Callback functions must satisfy the following signature: + +```c +typedef void (*node_api_async_execute_callback)(node_api_env env, void* data); +``` + +Implementations of this function must avoid making Node.js API calls that +execute JavaScript or interact with JavaScript objects. Node.js API calls +should be in the `node_api_async_complete_callback` instead. Do not use the +`node_api_env` parameter as it will likely result in execution of JavaScript. + +#### node_api_async_complete_callback + +Function pointer used with functions that support asynchronous +operations. Callback functions must satisfy the following signature: + +```c +typedef void (*node_api_async_complete_callback)(node_api_env env, + node_api_status status, + void* data); +``` + +Unless for reasons discussed in [Object Lifetime Management][], creating a +handle and/or callback scope inside the function body is not necessary. + +#### node_api_threadsafe_function_call_js + + +Function pointer used with asynchronous thread-safe function calls. The +callback will be called on the main thread. Its purpose is to use a data item +arriving via the queue from one of the secondary threads to construct the +parameters necessary for a call into JavaScript, usually via +`node_api_call_function`, and then make the call into JavaScript. + +The data arriving from the secondary thread via the queue is given in the +`data` parameter and the JavaScript function to call is given in the +`js_callback` parameter. + +The Node.js API sets up the environment prior to calling this callback, so it +is sufficient to call the JavaScript function via `node_api_call_function` +rather than via `node_api_make_callback`. + +Callback functions must satisfy the following signature: + +```c +typedef void (*node_api_threadsafe_function_call_js)(node_api_env env, + node_api_value js_callback, + void* context, + void* data); +``` + +* `[in] env`: The environment to use for API calls, or `NULL` if the + thread-safe function is being torn down and `data` may need to be freed. +* `[in] js_callback`: The JavaScript function to call, or `NULL` if the + thread-safe function is being torn down and `data` may need to be freed. It + may also be `NULL` if the thread-safe function was created without + `js_callback`. +* `[in] context`: The optional data with which the thread-safe function was + created. +* `[in] data`: Data created by the secondary thread. It is the responsibility + of the callback to convert this native data to JavaScript values (with + Node.js API functions) that can be passed as parameters when `js_callback` is + invoked. This pointer is managed entirely by the threads and this callback. + Thus this callback should free the data. + +Unless for reasons discussed in [Object Lifetime Management][], creating a +handle and/or callback scope inside the function body is not necessary. + +#### node_api_async_cleanup_hook + + +Function pointer used with [`node_api_add_async_cleanup_hook`][]. It will be +called when the environment is being torn down. + +Callback functions must satisfy the following signature: + +```c +typedef void (*node_api_async_cleanup_hook)( + node_api_async_cleanup_hook_handle handle, void* data); +``` + +* `[in] handle`: The handle that must be passed to + [`node_api_remove_async_cleanup_hook`][] after completion of the asynchronous + cleanup. +* `[in] data`: The data that was passed to + [`node_api_add_async_cleanup_hook`][]. + +The body of the function should initiate the asynchronous cleanup actions at +the end of which `handle` must be passed in a call to +[`node_api_remove_async_cleanup_hook`][]. + +## Error handling + +The Node.js API uses both return values and JavaScript exceptions for error +handling. The following sections explain the approach for each case. + +### Return values + +All of the Node.js API functions share the same error handling pattern. The +return type of all API functions is `node_api_status`. + +The return value will be `node_api_ok` if the request was successful and +no uncaught JavaScript exception was thrown. If an error occurred AND +an exception was thrown, the `node_api_status` value for the error +will be returned. If an exception was thrown, and no error occurred, +`node_api_pending_exception` will be returned. + +In cases where a return value other than `node_api_ok` or +`node_api_pending_exception` is returned, [`node_api_is_exception_pending`][] +must be called to check if an exception is pending. +See the section on exceptions for more details. + +The full set of possible `node_api_status` values is defined +in `node_api_api_types.h`. + +The `node_api_status` return value provides a VM-independent representation of +the error which occurred. In some cases it is useful to be able to get +more detailed information, including a string representing the error as well as +VM (engine)-specific information. + +In order to retrieve this information [`node_api_get_last_error_info`][] +is provided which returns a `node_api_extended_error_info` structure. +The format of the `node_api_extended_error_info` structure is as follows: + + + +```c +typedef struct node_api_extended_error_info { + const char* error_message; + void* engine_reserved; + uint32_t engine_error_code; + node_api_status error_code; +}; +``` + +* `error_message`: Textual representation of the error that occurred. +* `engine_reserved`: Opaque handle reserved for engine use only. +* `engine_error_code`: VM specific error code. +* `error_code`: Node.js API status code for the last error. + +[`node_api_get_last_error_info`][] returns the information for the last +Node.js API call that was made. + +Do not rely on the content or format of any of the extended information as it +is not subject to SemVer and may change at any time. It is intended only for +logging purposes. + +#### node_api_get_last_error_info + + +```c +node_api_status +node_api_get_last_error_info(node_api_env env, + const node_api_extended_error_info** result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] result`: The `node_api_extended_error_info` structure with more + information about the error. + +Returns `node_api_ok` if the API succeeded. + +This API retrieves a `node_api_extended_error_info` structure with information +about the last error that occurred. + +The content of the `node_api_extended_error_info` returned is only valid up +until a Node.js API function is called on the same `env`. + +Do not rely on the content or format of any of the extended information as it +is not subject to SemVer and may change at any time. It is intended only for +logging purposes. + +This API can be called even if there is a pending JavaScript exception. + +### Exceptions + +Any Node.js API function call may result in a pending JavaScript exception. +This is the case for any of the API functions, even those that may not cause +the execution of JavaScript. + +If the `node_api_status` returned by a function is `node_api_ok` then no +exception is pending and no additional action is required. If the +`node_api_status` returned is anything other than `node_api_ok` or +`node_api_pending_exception`, in order to try to recover and continue +instead of simply returning immediately, [`node_api_is_exception_pending`][] +must be called in order to determine if an exception is pending or not. + +In many cases when a Node.js API function is called and an exception is +already pending, the function will return immediately with a +`node_api_status` of `node_api_pending_exception`. However, this is not the +case for all functions. The Node.js API allows a subset of the functions to be +called to allow for some minimal cleanup before returning to JavaScript. +In that case, `node_api_status` will reflect the status for the function. It +will not reflect previous pending exceptions. To avoid confusion, check +the error status after every function call. + +When an exception is pending one of two approaches can be employed. + +The first approach is to do any appropriate cleanup and then return so that +execution will return to JavaScript. As part of the transition back to +JavaScript, the exception will be thrown at the point in the JavaScript +code where the native method was invoked. The behavior of most Node.js API +calls is unspecified while an exception is pending, and many will simply return +`node_api_pending_exception`, so do as little as possible and then return to +JavaScript where the exception can be handled. + +The second approach is to try to handle the exception. There will be cases +where the native code can catch the exception, take the appropriate action, +and then continue. This is only recommended in specific cases +where it is known that the exception can be safely handled. In these +cases [`node_api_get_and_clear_last_exception`][] can be used to get and +clear the exception. On success, result will contain the handle to +the last JavaScript `Object` thrown. If it is determined, after +retrieving the exception, the exception cannot be handled after all +it can be re-thrown it with [`node_api_throw`][] where error is the +JavaScript `Error` object to be thrown. + +The following utility functions are also available in case native code +needs to throw an exception or determine if a `node_api_value` is an instance +of a JavaScript `Error` object: [`node_api_throw_error`][], +[`node_api_throw_type_error`][], [`node_api_throw_range_error`][] and +[`node_api_is_error`][]. + +The following utility functions are also available in case native +code needs to create an `Error` object: [`node_api_create_error`][], +[`node_api_create_type_error`][], and [`node_api_create_range_error`][], +where result is the `node_api_value` that refers to the newly created +JavaScript `Error` object. + +The Node.js project is adding error codes to all of the errors +generated internally. The goal is for applications to use these +error codes for all error checking. The associated error messages +will remain, but will only be meant to be used for logging and +display with the expectation that the message can change without +SemVer applying. In order to support this model with the Node.js API, both +in internal functionality and for module specific functionality +(as its good practice), the `throw_` and `create_` functions +take an optional code parameter which is the string for the code +to be added to the error object. If the optional parameter is `NULL` +then no code will be associated with the error. If a code is provided, +the name associated with the error is also updated to be: + +```text +originalName [code] +``` + +where `originalName` is the original name associated with the error +and `code` is the code that was provided. For example, if the code +is `'ERR_ERROR_1'` and a `TypeError` is being created the name will be: + +```text +TypeError [ERR_ERROR_1] +``` + +#### node_api_throw + + +```c +NODE_API_EXTERN node_api_status +node_api_throw(node_api_env env, node_api_value error); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] error`: The JavaScript value to be thrown. + +Returns `node_api_ok` if the API succeeded. + +This API throws the JavaScript value provided. + +#### node_api_throw_error + + +```c +NODE_API_EXTERN node_api_status node_api_throw_error(node_api_env env, + const char* code, + const char* msg); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] code`: Optional error code to be set on the error. +* `[in] msg`: C string representing the text to be associated with the error. + +Returns `node_api_ok` if the API succeeded. + +This API throws a JavaScript `Error` with the text provided. + +#### node_api_throw_type_error + + +```c +NODE_API_EXTERN node_api_status node_api_throw_type_error(node_api_env env, + const char* code, + const char* msg); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] code`: Optional error code to be set on the error. +* `[in] msg`: C string representing the text to be associated with the error. + +Returns `node_api_ok` if the API succeeded. + +This API throws a JavaScript `TypeError` with the text provided. + +#### node_api_throw_range_error + + +```c +NODE_API_EXTERN node_api_status node_api_throw_range_error(node_api_env env, + const char* code, + const char* msg); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] code`: Optional error code to be set on the error. +* `[in] msg`: C string representing the text to be associated with the error. + +Returns `node_api_ok` if the API succeeded. + +This API throws a JavaScript `RangeError` with the text provided. + +#### node_api_is_error + + +```c +NODE_API_EXTERN node_api_status node_api_is_error(node_api_env env, + node_api_value value, + bool* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The `node_api_value` to be checked. +* `[out] result`: Boolean value that is set to true if `node_api_value` + represents an error, false otherwise. + +Returns `node_api_ok` if the API succeeded. + +This API queries a `node_api_value` to check if it represents an error object. + +#### node_api_create_error + + +```c +NODE_API_EXTERN node_api_status node_api_create_error(node_api_env env, + node_api_value code, + node_api_value msg, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] code`: Optional `node_api_value` with the string for the error code to + be associated with the error. +* `[in] msg`: `node_api_value` that references a JavaScript `String` to be used + as the message for the `Error`. +* `[out] result`: `node_api_value` representing the error created. + +Returns `node_api_ok` if the API succeeded. + +This API returns a JavaScript `Error` with the text provided. + +#### node_api_create_type_error + + +```c +NODE_API_EXTERN node_api_status node_api_create_type_error(node_api_env env, + node_api_value code, + node_api_value msg, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] code`: Optional `node_api_value` with the string for the error code to + be associated with the error. +* `[in] msg`: `node_api_value` that references a JavaScript `String` to be used + as the message for the `Error`. +* `[out] result`: `node_api_value` representing the error created. + +Returns `node_api_ok` if the API succeeded. + +This API returns a JavaScript `TypeError` with the text provided. + +#### node_api_create_range_error + + +```c +NODE_API_EXTERN node_api_status node_api_create_range_error(node_api_env env, + node_api_value code, + node_api_value msg, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] code`: Optional `node_api_value` with the string for the error code to + be associated with the error. +* `[in] msg`: `node_api_value` that references a JavaScript `String` to be used + as the message for the `Error`. +* `[out] result`: `node_api_value` representing the error created. + +Returns `node_api_ok` if the API succeeded. + +This API returns a JavaScript `RangeError` with the text provided. + +#### node_api_get_and_clear_last_exception + + +```c +node_api_status node_api_get_and_clear_last_exception(node_api_env env, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] result`: The exception if one is pending, `NULL` otherwise. + +Returns `node_api_ok` if the API succeeded. + +This API can be called even if there is a pending JavaScript exception. + +#### node_api_is_exception_pending + + +```c +node_api_status node_api_is_exception_pending(node_api_env env, bool* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] result`: Boolean value that is set to true if an exception is pending. + +Returns `node_api_ok` if the API succeeded. + +This API can be called even if there is a pending JavaScript exception. + +#### node_api_fatal_exception + + +```c +node_api_status node_api_fatal_exception(node_api_env env, node_api_value err); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] err`: The error that is passed to `'uncaughtException'`. + +Trigger an `'uncaughtException'` in JavaScript. Useful if an async +callback throws an exception with no way to recover. + +### Fatal errors + +In the event of an unrecoverable error in a native module, a fatal error can be +thrown to immediately terminate the process. + +#### node_api_fatal_error + + +```c +NODE_API_NO_RETURN void node_api_fatal_error(const char* location, + size_t location_len, + const char* message, + size_t message_len); +``` + +* `[in] location`: Optional location at which the error occurred. +* `[in] location_len`: The length of the location in bytes, or + `NODE_API_AUTO_LENGTH` if it is null-terminated. +* `[in] message`: The message associated with the error. +* `[in] message_len`: The length of the message in bytes, or + `NODE_API_AUTO_LENGTH` if it is null-terminated. + +The function call does not return, the process will be terminated. + +This API can be called even if there is a pending JavaScript exception. + +## Object lifetime management + +As Node.js API calls are made, handles to objects in the heap for the +underlying VM may be returned as `node_api_values`. These handles must hold the +objects 'live' until they are no longer required by the native code, +otherwise the objects could be collected before the native code was +finished using them. + +As object handles are returned they are associated with a +'scope'. The lifespan for the default scope is tied to the lifespan +of the native method call. The result is that, by default, handles +remain valid and the objects associated with these handles will be +held live for the lifespan of the native method call. + +In many cases, however, it is necessary that the handles remain valid for +either a shorter or longer lifespan than that of the native method. +The sections which follow describe the Node.js API functions that can be used +to change the handle lifespan from the default. + +### Making handle lifespan shorter than that of the native method +It is often necessary to make the lifespan of handles shorter than +the lifespan of a native method. For example, consider a native method +that has a loop which iterates through the elements in a large array: + +```c +for (int i = 0; i < 1000000; i++) { + node_api_value result; + node_api_status status = node_api_get_element(env, object, i, &result); + if (status != node_api_ok) { + break; + } + // do something with element +} +``` + +This would result in a large number of handles being created, consuming +substantial resources. In addition, even though the native code could only +use the most recent handle, all of the associated objects would also be +kept alive since they all share the same scope. + +To handle this case, the Node.js API provides the ability to establish a new +'scope' to which newly created handles will be associated. Once those handles +are no longer required, the scope can be 'closed' and any handles associated +with the scope are invalidated. The methods available to open/close scopes are +[`node_api_open_handle_scope`][] and [`node_api_close_handle_scope`][]. + +The Node.js API only supports a single nested hierarchy of scopes. There is +only one active scope at any time, and all new handles will be associated with +that scope while it is active. Scopes must be closed in the reverse order from +which they are opened. In addition, all scopes created within a native method +must be closed before returning from that method. + +Taking the earlier example, adding calls to [`node_api_open_handle_scope`][] +and [`node_api_close_handle_scope`][] would ensure that at most a single handle +is valid throughout the execution of the loop: + +```c +for (int i = 0; i < 1000000; i++) { + node_api_handle_scope scope; + node_api_status status = node_api_open_handle_scope(env, &scope); + if (status != node_api_ok) { + break; + } + node_api_value result; + status = node_api_get_element(env, object, i, &result); + if (status != node_api_ok) { + break; + } + // do something with element + status = node_api_close_handle_scope(env, scope); + if (status != node_api_ok) { + break; + } +} +``` + +When nesting scopes, there are cases where a handle from an +inner scope needs to live beyond the lifespan of that scope. The Node.js API +supports an 'escapable scope' in order to support this case. An escapable scope +allows one handle to be 'promoted' so that it 'escapes' the +current scope and the lifespan of the handle changes from the current +scope to that of the outer scope. + +The methods available to open/close escapable scopes are +[`node_api_open_escapable_handle_scope`][] and +[`node_api_close_escapable_handle_scope`][]. + +The request to promote a handle is made through [`node_api_escape_handle`][] +which can only be called once. + +#### node_api_open_handle_scope + + +```c +NODE_API_EXTERN node_api_status +node_api_open_handle_scope(node_api_env env, node_api_handle_scope* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] result`: `node_api_value` representing the new scope. + +Returns `node_api_ok` if the API succeeded. + +This API opens a new scope. + +#### node_api_close_handle_scope + + +```c +NODE_API_EXTERN node_api_status +node_api_close_handle_scope(node_api_env env, node_api_handle_scope scope); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] scope`: `node_api_value` representing the scope to be closed. + +Returns `node_api_ok` if the API succeeded. + +This API closes the scope passed in. Scopes must be closed in the +reverse order from which they were created. + +This API can be called even if there is a pending JavaScript exception. + +#### node_api_open_escapable_handle_scope + + +```c +NODE_API_EXTERN node_api_status +node_api_open_escapable_handle_scope(node_api_env env, + node_api_handle_scope* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] result`: `node_api_value` representing the new scope. + +Returns `node_api_ok` if the API succeeded. + +This API opens a new scope from which one object can be promoted +to the outer scope. + +#### node_api_close_escapable_handle_scope + + +```c +NODE_API_EXTERN node_api_status +node_api_close_escapable_handle_scope(node_api_env env, + node_api_handle_scope scope); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] scope`: `node_api_value` representing the scope to be closed. + +Returns `node_api_ok` if the API succeeded. + +This API closes the scope passed in. Scopes must be closed in the +reverse order from which they were created. + +This API can be called even if there is a pending JavaScript exception. + +#### node_api_escape_handle + + +```c +node_api_status node_api_escape_handle(node_api_env env, + node_api_escapable_handle_scope scope, + node_api_value escapee, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] scope`: `node_api_value` representing the current scope. +* `[in] escapee`: `node_api_value` representing the JavaScript `Object` to be + escaped. +* `[out] result`: `node_api_value` representing the handle to the escaped + `Object` in the outer scope. + +Returns `node_api_ok` if the API succeeded. + +This API promotes the handle to the JavaScript object so that it is valid +for the lifetime of the outer scope. It can only be called once per scope. +If it is called more than once an error will be returned. + +This API can be called even if there is a pending JavaScript exception. + +### References to objects with a lifespan longer than that of the native method + +In some cases an addon will need to be able to create and reference objects +with a lifespan longer than that of a single native method invocation. For +example, to create a constructor and later use that constructor +in a request to creates instances, it must be possible to reference +the constructor object across many different instance creation requests. This +would not be possible with a normal handle returned as a `node_api_value` as +described in the earlier section. The lifespan of a normal handle is +managed by scopes and all scopes must be closed before the end of a native +method. + +The Node.js API provides methods to create persistent references to an object. +Each persistent reference has an associated count with a value of 0 +or higher. The count determines if the reference will keep +the corresponding object live. References with a count of 0 do not +prevent the object from being collected and are often called 'weak' +references. Any count greater than 0 will prevent the object +from being collected. + +References can be created with an initial reference count. The count can +then be modified through [`node_api_reference_ref`][] and +[`node_api_reference_unref`][]. If an object is collected while the count +for a reference is 0, all subsequent calls to +get the object associated with the reference [`node_api_get_reference_value`][] +will return `NULL` for the returned `node_api_value`. An attempt to call +[`node_api_reference_ref`][] for a reference whose object has been collected +results in an error. + +References must be deleted once they are no longer required by the addon. When +a reference is deleted, it will no longer prevent the corresponding object from +being collected. Failure to delete a persistent reference results in +a 'memory leak' with both the native memory for the persistent reference and +the corresponding object on the heap being retained forever. + +There can be multiple persistent references created which refer to the same +object, each of which will either keep the object live or not based on its +individual count. + +#### node_api_create_reference + + +```c +NODE_API_EXTERN node_api_status +node_api_create_reference(node_api_env env, + node_api_value value, + uint32_t initial_refcount, + node_api_ref* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing the `Object` to which we want a + reference. +* `[in] initial_refcount`: Initial reference count for the new reference. +* `[out] result`: `node_api_ref` pointing to the new reference. + +Returns `node_api_ok` if the API succeeded. + +This API create a new reference with the specified reference count +to the `Object` passed in. + +#### node_api_delete_reference + + +```c +NODE_API_EXTERN node_api_status +node_api_delete_reference(node_api_env env, node_api_ref ref); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] ref`: `node_api_ref` to be deleted. + +Returns `node_api_ok` if the API succeeded. + +This API deletes the reference passed in. + +This API can be called even if there is a pending JavaScript exception. + +#### node_api_reference_ref + + +```c +NODE_API_EXTERN node_api_status +node_api_reference_ref(node_api_env env, node_api_ref ref, uint32_t* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] ref`: `node_api_ref` for which the reference count will be incremented. +* `[out] result`: The new reference count. + +Returns `node_api_ok` if the API succeeded. + +This API increments the reference count for the reference +passed in and returns the resulting reference count. + +#### node_api_reference_unref + + +```c +NODE_API_EXTERN node_api_status +node_api_reference_unref(node_api_env env, node_api_ref ref, uint32_t* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] ref`: `node_api_ref` for which the reference count will be decremented. +* `[out] result`: The new reference count. + +Returns `node_api_ok` if the API succeeded. + +This API decrements the reference count for the reference +passed in and returns the resulting reference count. + +#### node_api_get_reference_value + + +```c +NODE_API_EXTERN node_api_status +node_api_get_reference_value(node_api_env env, + node_api_ref ref, + node_api_value* result); +``` + +the `node_api_value passed` in or out of these methods is a handle to the +object to which the reference is related. + +* `[in] env`: The environment that the API is invoked under. +* `[in] ref`: `node_api_ref` for which we requesting the corresponding + `Object`. +* `[out] result`: The `node_api_value` for the `Object` referenced by the + `node_api_ref`. + +Returns `node_api_ok` if the API succeeded. + +If still valid, this API returns the `node_api_value` representing the +JavaScript `Object` associated with the `node_api_ref`. Otherwise, result +will be `NULL`. + +### Cleanup on exit of the current Node.js instance + +While a Node.js process typically releases all its resources when exiting, +embedders of Node.js, or future Worker support, may require addons to register +clean-up hooks that will be run once the current Node.js instance exits. + +The Node.js API provides functions for registering and un-registering such +callbacks. When those callbacks are run, all resources that are being held by +the addon should be freed up. + +#### node_api_add_env_cleanup_hook + + +```c +NODE_EXTERN node_api_status +node_api_add_env_cleanup_hook(node_api_env env, + void (*fun)(void* arg), + void* arg); +``` + +Registers `fun` as a function to be run with the `arg` parameter once the +current Node.js environment exits. + +A function can safely be specified multiple times with different +`arg` values. In that case, it will be called multiple times as well. +Providing the same `fun` and `arg` values multiple times is not allowed +and will lead the process to abort. + +The hooks will be called in reverse order, i.e. the most recently added one +will be called first. + +Removing this hook can be done by using [`node_api_remove_env_cleanup_hook`][]. +Typically, that happens when the resource for which this hook was added +is being torn down anyway. + +For asynchronous cleanup, [`node_api_add_async_cleanup_hook`][] is available. + +#### node_api_remove_env_cleanup_hook + + +```c +NODE_API_EXTERN node_api_status +node_api_remove_env_cleanup_hook(node_api_env env, + void (*fun)(void* arg), + void* arg); +``` + +Unregisters `fun` as a function to be run with the `arg` parameter once the +current Node.js environment exits. Both the argument and the function value +need to be exact matches. + +The function must have originally been registered +with `node_api_add_env_cleanup_hook`, otherwise the process will abort. + +#### node_api_add_async_cleanup_hook + + +> Stability: 1 - Experimental + +```c +NODE_API_EXTERN node_api_status +node_api_add_async_cleanup_hook(node_api_env env, + node_api_async_cleanup_hook hook, + void* arg, + node_api_async_cleanup_hook_handle* remove_handle); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] hook`: The function pointer to call at environment teardown. +* `[in] arg`: The pointer to pass to `hook` when it gets called. +* `[out] remove_handle`: Optional handle that refers to the asynchronous + cleanup hook. + +Registers `hook`, which is a function of type +[`node_api_async_cleanup_hook`][], as a function to be run with the +`remove_handle` and `arg` parameters once the current Node.js environment +exits. + +Unlike [`node_api_add_env_cleanup_hook`][], the hook is allowed to be +asynchronous. + +Otherwise, behavior generally matches that of +[`node_api_add_env_cleanup_hook`][]. + +If `remove_handle` is not `NULL`, an opaque value will be stored in it +that must later be passed to [`node_api_remove_async_cleanup_hook`][], +regardless of whether the hook has already been invoked. Typically, that +happens when the resource for which this hook was added is being torn down +anyway. + +#### node_api_remove_async_cleanup_hook + + +> Stability: 1 - Experimental + +```c +NODE_API_EXTERN node_api_status node_api_remove_async_cleanup_hook( + node_api_async_cleanup_hook_handle remove_handle); +``` + +* `[in] remove_handle`: The handle to an asynchronous cleanup hook that was + created with [`node_api_add_async_cleanup_hook`][]. + +Unregisters the cleanup hook corresponding to `remove_handle`. This will +prevent the hook from being executed, unless it has already started executing. +This must be called on any `node_api_async_cleanup_hook_handle` value obtained +from [`node_api_add_async_cleanup_hook`][]. + +## Module registration +Node.js API modules are registered in a manner similar to other modules +except that instead of using the `NODE_MODULE` macro the following +is used: + +```c +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) +``` + +The next difference is the signature for the `Init` method. For a Node.js API +module it is as follows: + +```c +node_api_value Init(node_api_env env, node_api_value exports); +``` + +The return value from `Init` is treated as the `exports` object for the module. +The `Init` method is passed an empty object via the `exports` parameter as a +convenience. If `Init` returns `NULL`, the parameter passed as `exports` is +exported by the module. Node.js API modules cannot modify the `module` object +but can specify anything as the `exports` property of the module. + +To add the method `hello` as a function so that it can be called as a method +provided by the addon: + +```c +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_status status; + node_api_property_descriptor desc = { + "hello", + NULL, + Method, + NULL, + NULL, + NULL, + node_api_writable | node_api_enumerable | node_api_configurable, + NULL + }; + status = node_api_define_properties(env, exports, 1, &desc); + if (status != node_api_ok) return NULL; + return exports; +} +``` + +To set a function to be returned by the `require()` for the addon: + +```c +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_value method; + node_api_status status; + status = node_api_create_function( + env, "exports", NODE_API_AUTO_LENGTH, Method, NULL, &method); + if (status != node_api_ok) return NULL; + return method; +} +``` + +To define a class so that new instances can be created (often used with +[Object wrap][]): + +```c +// NOTE: partial example, not all referenced code is included +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_status status; + node_api_property_descriptor properties[] = { + { "value", NULL, NULL, GetValue, SetValue, NULL, + node_api_writable | node_api_configurable, NULL }, + DECLARE_NODE_API_METHOD("plusOne", PlusOne), + DECLARE_NODE_API_METHOD("multiply", Multiply), + }; + + node_api_value cons; + status = + node_api_define_class(env, "MyObject", New, NULL, 3, properties, &cons); + if (status != node_api_ok) return NULL; + + status = node_api_create_reference(env, cons, 1, &constructor); + if (status != node_api_ok) return NULL; + + status = node_api_set_named_property(env, exports, "MyObject", cons); + if (status != node_api_ok) return NULL; + + return exports; +} +``` + +You can also use the `NODE_API_MODULE_INIT` macro, which acts as a shorthand +for `NODE_API_MODULE` and defining an `Init` function: + +```c +NODE_API_MODULE_INIT() { + node_api_value answer; + node_api_status result; + + status = node_api_create_int64(env, 42, &answer); + if (status != node_api_ok) return NULL; + + status = node_api_set_named_property(env, exports, "answer", answer); + if (status != node_api_ok) return NULL; + + return exports; +} +``` + +All Node.js API addons are context-aware, meaning they may be loaded multiple +times. There are a few design considerations when declaring such a module. +The documentation on [context-aware addons][] provides more details. + +The variables `env` and `exports` will be available inside the function body +following the macro invocation. + +For more details on setting properties on objects, see the section on +[Working with JavaScript properties][]. + +For more details on building addon modules in general, refer to the existing +API. + +## Working with JavaScript values +The Node.js API exposes a set of APIs to create all types of JavaScript values. +Some of these types are documented under [Section 6][] +of the [ECMAScript Language Specification][]. + +Fundamentally, these APIs are used to do one of the following: + +1. Create a new JavaScript object +2. Convert from a primitive C type to a Node.js API value +3. Convert from a Node.js API value to a primitive C type +4. Get global instances including `undefined` and `null` + +Node.js API values are represented by the type `node_api_value`. +Any Node.js API call that requires a JavaScript value takes in a +`node_api_value`. In some cases, the API does check the type of the +`node_api_value` up-front. However, for better performance, it's better for the +caller to make sure that the `node_api_value` in question is of the JavaScript +type expected by the API. + +### Enum types +#### node_api_key_collection_mode + + +```c +typedef enum { + node_api_key_include_prototypes, + node_api_key_own_only +} node_api_key_collection_mode; +``` + +Describes the `Keys/Properties` filter enums: + +`node_api_key_collection_mode` limits the range of collected properties. + +`node_api_key_own_only` limits the collected properties to the given +object only. `node_api_key_include_prototypes` will include all keys +of the objects's prototype chain as well. + +#### node_api_key_filter + + +```c +typedef enum { + node_api_key_all_properties = 0, + node_api_key_writable = 1, + node_api_key_enumerable = 1 << 1, + node_api_key_configurable = 1 << 2, + node_api_key_skip_strings = 1 << 3, + node_api_key_skip_symbols = 1 << 4 +} node_api_key_filter; +``` + +Property filter bits. They can be or'ed to build a composite filter. + +#### node_api_key_conversion + + +```c +typedef enum { + node_api_key_keep_numbers, + node_api_key_numbers_to_strings +} node_api_key_conversion; +``` + +`node_api_key_numbers_to_strings` will convert integer indices to +strings. `node_api_key_keep_numbers` will return numbers for integer +indices. + +#### node_api_valuetype + +```c +typedef enum { + // ES6 types (corresponds to typeof) + node_api_undefined, + node_api_null, + node_api_boolean, + node_api_number, + node_api_string, + node_api_symbol, + node_api_object, + node_api_function, + node_api_external, + node_api_bigint, +} node_api_valuetype; +``` + +Describes the type of a `node_api_value`. This generally corresponds to the +types described in [Section 6.1][] of the ECMAScript Language Specification. +In addition to types in that section, `node_api_valuetype` can also represent +`Function`s and `Object`s with external data. + +A JavaScript value of type `node_api_external` appears in JavaScript as a plain +object such that no properties can be set on it, and no prototype. + +#### node_api_typedarray_type + +```c +typedef enum { + node_api_int8_array, + node_api_uint8_array, + node_api_uint8_clamped_array, + node_api_int16_array, + node_api_uint16_array, + node_api_int32_array, + node_api_uint32_array, + node_api_float32_array, + node_api_float64_array, + node_api_bigint64_array, + node_api_biguint64_array, +} node_api_typedarray_type; +``` + +This represents the underlying binary scalar datatype of the `TypedArray`. +Elements of this enum correspond to +[Section 22.2][] of the [ECMAScript Language Specification][]. + +### Object creation functions +#### node_api_create_array + + +```c +node_api_status node_api_create_array(node_api_env env, node_api_value* result) +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[out] result`: A `node_api_value` representing a JavaScript `Array`. + +Returns `node_api_ok` if the API succeeded. + +This API returns a Node.js API value corresponding to a JavaScript `Array` +type. JavaScript arrays are described in +[Section 22.1][] of the ECMAScript Language Specification. + +#### node_api_create_array_with_length + + +```c +node_api_status node_api_create_array_with_length(node_api_env env, + size_t length, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] length`: The initial length of the `Array`. +* `[out] result`: A `node_api_value` representing a JavaScript `Array`. + +Returns `node_api_ok` if the API succeeded. + +This API returns a Node.js API value corresponding to a JavaScript `Array` +type. The `Array`'s length property is set to the passed-in length parameter. +However, the underlying buffer is not guaranteed to be pre-allocated by the VM +when the array is created. That behavior is left to the underlying VM +implementation. If the buffer must be a contiguous block of memory that can be +directly read and/or written via C, consider using +[`node_api_create_external_arraybuffer`][]. + +JavaScript arrays are described in +[Section 22.1][] of the ECMAScript Language Specification. + +#### node_api_create_arraybuffer + + +```c +node_api_status node_api_create_arraybuffer(node_api_env env, + size_t byte_length, + void** data, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] length`: The length in bytes of the array buffer to create. +* `[out] data`: Pointer to the underlying byte buffer of the `ArrayBuffer`. +* `[out] result`: A `node_api_value` representing a JavaScript `ArrayBuffer`. + +Returns `node_api_ok` if the API succeeded. + +This API returns a Node.js API value corresponding to a JavaScript +`ArrayBuffer`. `ArrayBuffer`s are used to represent fixed-length binary data +buffers. They are normally used as a backing-buffer for `TypedArray` objects. +The `ArrayBuffer` allocated will have an underlying byte buffer whose size is +determined by the `length` parameter that's passed in. +The underlying buffer is optionally returned back to the caller in case the +caller wants to directly manipulate the buffer. This buffer can only be +written to directly from native code. To write to this buffer from JavaScript, +a typed array or `DataView` object would need to be created. + +JavaScript `ArrayBuffer` objects are described in +[Section 24.1][] of the ECMAScript Language Specification. + +#### node_api_create_buffer + + +```c +node_api_status node_api_create_buffer(node_api_env env, + size_t size, + void** data, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] size`: Size in bytes of the underlying buffer. +* `[out] data`: Raw pointer to the underlying buffer. +* `[out] result`: A `node_api_value` representing a `node::Buffer`. + +Returns `node_api_ok` if the API succeeded. + +This API allocates a `node::Buffer` object. While this is still a +fully-supported data structure, in most cases using a `TypedArray` will +suffice. + +#### node_api_create_buffer_copy + + +```c +node_api_status node_api_create_buffer_copy(node_api_env env, + size_t length, + const void* data, + void** result_data, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] size`: Size in bytes of the input buffer (should be the same as the + size of the new buffer). +* `[in] data`: Raw pointer to the underlying buffer to copy from. +* `[out] result_data`: Pointer to the new `Buffer`'s underlying data buffer. +* `[out] result`: A `node_api_value` representing a `node::Buffer`. + +Returns `node_api_ok` if the API succeeded. + +This API allocates a `node::Buffer` object and initializes it with data copied +from the passed-in buffer. While this is still a fully-supported data +structure, in most cases using a `TypedArray` will suffice. + +#### node_api_create_date + + +```c +node_api_status node_api_create_date(node_api_env env, + double time, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] time`: ECMAScript time value in milliseconds since + 01 January, 1970 UTC. +* `[out] result`: A `node_api_value` representing a JavaScript `Date`. + +Returns `node_api_ok` if the API succeeded. + +This API does not observe leap seconds; they are ignored, as +ECMAScript aligns with POSIX time specification. + +This API allocates a JavaScript `Date` object. + +JavaScript `Date` objects are described in +[Section 20.3][] of the ECMAScript Language Specification. + +#### node_api_create_external + + +```c +node_api_status node_api_create_external(node_api_env env, + void* data, + node_api_finalize finalize_cb, + void* finalize_hint, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] data`: Raw pointer to the external data. +* `[in] finalize_cb`: Optional callback to call when the external value is + being collected. [`node_api_finalize`][] provides more details. +* `[in] finalize_hint`: Optional hint to pass to the finalize callback during + collection. +* `[out] result`: A `node_api_value` representing an external value. + +Returns `node_api_ok` if the API succeeded. + +This API allocates a JavaScript value with external data attached to it. This +is used to pass external data through JavaScript code, so it can be retrieved +later by native code using [`node_api_get_value_external`][]. + +The API adds a `node_api_finalize` callback which will be called when the +JavaScript object just created is ready for garbage collection. It is similar +to `node_api_wrap()` except that: + +* the native data cannot be retrieved later using `node_api_unwrap()`, +* nor can it be removed later using `node_api_remove_wrap()`, and +* the object created by the API can be used with `node_api_wrap()`. + +The created value is not an object, and therefore does not support additional +properties. It is considered a distinct value type: calling `node_api_typeof()` +with an external value yields `node_api_external`. + +#### node_api_create_external_arraybuffer + + +```c +node_api_status +node_api_create_external_arraybuffer(node_api_env env, + void* external_data, + size_t byte_length, + node_api_finalize finalize_cb, + void* finalize_hint, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] external_data`: Pointer to the underlying byte buffer of the + `ArrayBuffer`. +* `[in] byte_length`: The length in bytes of the underlying buffer. +* `[in] finalize_cb`: Optional callback to call when the `ArrayBuffer` is being + collected. [`node_api_finalize`][] provides more details. +* `[in] finalize_hint`: Optional hint to pass to the finalize callback during + collection. +* `[out] result`: A `node_api_value` representing a JavaScript `ArrayBuffer`. + +Returns `node_api_ok` if the API succeeded. + +This API returns a Node.js API value corresponding to a JavaScript +`ArrayBuffer`. The underlying byte buffer of the `ArrayBuffer` is externally +allocated and managed. The caller must ensure that the byte buffer remains +valid until the finalize callback is called. + +The API adds a `node_api_finalize` callback which will be called when the +JavaScript object just created is ready for garbage collection. It is similar +to `node_api_wrap()` except that: + +* the native data cannot be retrieved later using `node_api_unwrap()`, +* nor can it be removed later using `node_api_remove_wrap()`, and +* the object created by the API can be used with `node_api_wrap()`. + +JavaScript `ArrayBuffer`s are described in +[Section 24.1][] of the ECMAScript Language Specification. + +#### node_api_create_external_buffer + + +```c +node_api_status node_api_create_external_buffer(node_api_env env, + size_t length, + void* data, + node_api_finalize finalize_cb, + void* finalize_hint, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] length`: Size in bytes of the input buffer (should be the same as the + size of the new buffer). +* `[in] data`: Raw pointer to the underlying buffer to expose to JavaScript. +* `[in] finalize_cb`: Optional callback to call when the `ArrayBuffer` is being + collected. [`node_api_finalize`][] provides more details. +* `[in] finalize_hint`: Optional hint to pass to the finalize callback during + collection. +* `[out] result`: A `node_api_value` representing a `node::Buffer`. + +Returns `node_api_ok` if the API succeeded. + +This API allocates a `node::Buffer` object and initializes it with data +backed by the passed in buffer. While this is still a fully-supported data +structure, in most cases using a `TypedArray` will suffice. + +The API adds a `node_api_finalize` callback which will be called when the +JavaScript object just created is ready for garbage collection. It is similar +to `node_api_wrap()` except that: + +* the native data cannot be retrieved later using `node_api_unwrap()`, +* nor can it be removed later using `node_api_remove_wrap()`, and +* the object created by the API can be used with `node_api_wrap()`. + +For Node.js >=4 `Buffers` are `Uint8Array`s. + +#### node_api_create_object + + +```c +node_api_status +node_api_create_object(node_api_env env, node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] result`: A `node_api_value` representing a JavaScript `Object`. + +Returns `node_api_ok` if the API succeeded. + +This API allocates a default JavaScript `Object`. +It is the equivalent of doing `new Object()` in JavaScript. + +The JavaScript `Object` type is described in [Section 6.1.7][] of the +ECMAScript Language Specification. + +#### node_api_create_symbol + + +```c +node_api_status node_api_create_symbol(node_api_env env, + node_api_value description, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] description`: Optional `node_api_value` which refers to a JavaScript + `String` to be set as the description for the symbol. +* `[out] result`: A `node_api_value` representing a JavaScript `Symbol`. + +Returns `node_api_ok` if the API succeeded. + +This API creates a JavaScript `Symbol` object from a UTF8-encoded C string. + +The JavaScript `Symbol` type is described in [Section 19.4][] +of the ECMAScript Language Specification. + +#### node_api_create_typedarray + + +```c +node_api_status node_api_create_typedarray(node_api_env env, + node_api_typedarray_type type, + size_t length, + node_api_value arraybuffer, + size_t byte_offset, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] type`: Scalar datatype of the elements within the `TypedArray`. +* `[in] length`: Number of elements in the `TypedArray`. +* `[in] arraybuffer`: `ArrayBuffer` underlying the typed array. +* `[in] byte_offset`: The byte offset within the `ArrayBuffer` from which to + start projecting the `TypedArray`. +* `[out] result`: A `node_api_value` representing a JavaScript `TypedArray`. + +Returns `node_api_ok` if the API succeeded. + +This API creates a JavaScript `TypedArray` object over an existing +`ArrayBuffer`. `TypedArray` objects provide an array-like view over an +underlying data buffer where each element has the same underlying binary scalar +datatype. + +It's required that `(length * size_of_element) + byte_offset` should +be <= the size in bytes of the array passed in. If not, a `RangeError` +exception is raised. + +JavaScript `TypedArray` objects are described in +[Section 22.2][] of the ECMAScript Language Specification. + +#### node_api_create_dataview + + +```c +node_api_status node_api_create_dataview(node_api_env env, + size_t byte_length, + node_api_value arraybuffer, + size_t byte_offset, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] length`: Number of elements in the `DataView`. +* `[in] arraybuffer`: `ArrayBuffer` underlying the `DataView`. +* `[in] byte_offset`: The byte offset within the `ArrayBuffer` from which to + start projecting the `DataView`. +* `[out] result`: A `node_api_value` representing a JavaScript `DataView`. + +Returns `node_api_ok` if the API succeeded. + +This API creates a JavaScript `DataView` object over an existing `ArrayBuffer`. +`DataView` objects provide an array-like view over an underlying data buffer, +but one which allows items of different size and type in the `ArrayBuffer`. + +It is required that `byte_length + byte_offset` is less than or equal to the +size in bytes of the array passed in. If not, a `RangeError` exception is +raised. + +JavaScript `DataView` objects are described in +[Section 24.3][] of the ECMAScript Language Specification. + +### Functions to convert from C types to the Node.js API +#### node_api_create_int32 + + +```c +node_api_status +node_api_create_int32(node_api_env env, int32_t value, node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: Integer value to be represented in JavaScript. +* `[out] result`: A `node_api_value` representing a JavaScript `Number`. + +Returns `node_api_ok` if the API succeeded. + +This API is used to convert from the C `int32_t` type to the JavaScript +`Number` type. + +The JavaScript `Number` type is described in +[Section 6.1.6][] of the ECMAScript Language Specification. + +#### node_api_create_uint32 + + +```c +node_api_status node_api_create_uint32(node_api_env env, + uint32_t value, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: Unsigned integer value to be represented in JavaScript. +* `[out] result`: A `node_api_value` representing a JavaScript `Number`. + +Returns `node_api_ok` if the API succeeded. + +This API is used to convert from the C `uint32_t` type to the JavaScript +`Number` type. + +The JavaScript `Number` type is described in +[Section 6.1.6][] of the ECMAScript Language Specification. + +#### node_api_create_int64 + + +```c +node_api_status +node_api_create_int64(node_api_env env, int64_t value, node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: Integer value to be represented in JavaScript. +* `[out] result`: A `node_api_value` representing a JavaScript `Number`. + +Returns `node_api_ok` if the API succeeded. + +This API is used to convert from the C `int64_t` type to the JavaScript +`Number` type. + +The JavaScript `Number` type is described in [Section 6.1.6][] +of the ECMAScript Language Specification. Note the complete range of `int64_t` +cannot be represented with full precision in JavaScript. Integer values +outside the range of [`Number.MIN_SAFE_INTEGER`][] `-(2**53 - 1)` - +[`Number.MAX_SAFE_INTEGER`][] `(2**53 - 1)` will lose precision. + +#### node_api_create_double + + +```c +node_api_status +node_api_create_double(node_api_env env, double value, node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: Double-precision value to be represented in JavaScript. +* `[out] result`: A `node_api_value` representing a JavaScript `Number`. + +Returns `node_api_ok` if the API succeeded. + +This API is used to convert from the C `double` type to the JavaScript +`Number` type. + +The JavaScript `Number` type is described in +[Section 6.1.6][] of the ECMAScript Language Specification. + +#### node_api_create_bigint_int64 + + +```c +node_api_status node_api_create_bigint_int64(node_api_env env, + int64_t value, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: Integer value to be represented in JavaScript. +* `[out] result`: A `node_api_value` representing a JavaScript `BigInt`. + +Returns `node_api_ok` if the API succeeded. + +This API converts the C `int64_t` type to the JavaScript `BigInt` type. + +#### node_api_create_bigint_uint64 + + +```c +node_api_status node_api_create_bigint_uint64(node_api_env env, + uint64_t value, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: Unsigned integer value to be represented in JavaScript. +* `[out] result`: A `node_api_value` representing a JavaScript `BigInt`. + +Returns `node_api_ok` if the API succeeded. + +This API converts the C `uint64_t` type to the JavaScript `BigInt` type. + +#### node_api_create_bigint_words + + +```c +node_api_status node_api_create_bigint_words(node_api_env env, + int sign_bit, + size_t word_count, + const uint64_t* words, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] sign_bit`: Determines if the resulting `BigInt` will be positive or + negative. +* `[in] word_count`: The length of the `words` array. +* `[in] words`: An array of `uint64_t` little-endian 64-bit words. +* `[out] result`: A `node_api_value` representing a JavaScript `BigInt`. + +Returns `node_api_ok` if the API succeeded. + +This API converts an array of unsigned 64-bit words into a single `BigInt` +value. + +The resulting `BigInt` is calculated as: (–1)`sign_bit` (`words[0]` +× (264)0 + `words[1]` × (264)1 + …) + +#### node_api_create_string_latin1 + + +```c +node_api_status node_api_create_string_latin1(node_api_env env, + const char* str, + size_t length, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] str`: Character buffer representing an ISO-8859-1-encoded string. +* `[in] length`: The length of the string in bytes, or `NODE_API_AUTO_LENGTH` + if it is null-terminated. +* `[out] result`: A `node_api_value` representing a JavaScript `String`. + +Returns `node_api_ok` if the API succeeded. + +This API creates a JavaScript `String` object from an ISO-8859-1-encoded C +string. The native string is copied. + +The JavaScript `String` type is described in +[Section 6.1.4][] of the ECMAScript Language Specification. + +#### node_api_create_string_utf16 + + +```c +node_api_status node_api_create_string_utf16(node_api_env env, + const char16_t* str, + size_t length, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] str`: Character buffer representing a UTF16-LE-encoded string. +* `[in] length`: The length of the string in two-byte code units, or + `NODE_API_AUTO_LENGTH` if it is null-terminated. +* `[out] result`: A `node_api_value` representing a JavaScript `String`. + +Returns `node_api_ok` if the API succeeded. + +This API creates a JavaScript `String` object from a UTF16-LE-encoded C string. +The native string is copied. + +The JavaScript `String` type is described in +[Section 6.1.4][] of the ECMAScript Language Specification. + +#### node_api_create_string_utf8 + + +```c +node_api_status node_api_create_string_utf8(node_api_env env, + const char* str, + size_t length, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] str`: Character buffer representing a UTF8-encoded string. +* `[in] length`: The length of the string in bytes, or `NODE_API_AUTO_LENGTH` + if it is null-terminated. +* `[out] result`: A `node_api_value` representing a JavaScript `String`. + +Returns `node_api_ok` if the API succeeded. + +This API creates a JavaScript `String` object from a UTF8-encoded C string. +The native string is copied. + +The JavaScript `String` type is described in +[Section 6.1.4][] of the ECMAScript Language Specification. + +### Functions to convert from the Node.js API to C types +#### node_api_get_array_length + + +```c +node_api_status node_api_get_array_length(node_api_env env, + node_api_value value, + uint32_t* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing the JavaScript `Array` whose + length is being queried. +* `[out] result`: `uint32` representing length of the array. + +Returns `node_api_ok` if the API succeeded. + +This API returns the length of an array. + +`Array` length is described in [Section 22.1.4.1][] of the ECMAScript Language +Specification. + +#### node_api_get_arraybuffer_info + + +```c +node_api_status node_api_get_arraybuffer_info(node_api_env env, + node_api_value arraybuffer, + void** data, + size_t* byte_length) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] arraybuffer`: `node_api_value` representing the `ArrayBuffer` being + queried. +* `[out] data`: The underlying data buffer of the `ArrayBuffer`. If + `byte_length` is `0`, this may be `NULL` or any other pointer value. +* `[out] byte_length`: Length in bytes of the underlying data buffer. + +Returns `node_api_ok` if the API succeeded. + +This API is used to retrieve the underlying data buffer of an `ArrayBuffer` and +its length. + +*WARNING*: Use caution while using this API. The lifetime of the underlying +data buffer is managed by the `ArrayBuffer` even after it's returned. A +possible safe way to use this API is in conjunction with +[`node_api_create_reference`][], which can be used to guarantee control over +the lifetime of the `ArrayBuffer`. It's also safe to use the returned data +buffer within the same callback as long as there are no calls to other APIs +that might trigger a GC. + +#### node_api_get_buffer_info + + +```c +node_api_status node_api_get_buffer_info(node_api_env env, + node_api_value value, + void** data, + size_t* length) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing the `node::Buffer` being queried. +* `[out] data`: The underlying data buffer of the `node::Buffer`. + If length is `0`, this may be `NULL` or any other pointer value. +* `[out] length`: Length in bytes of the underlying data buffer. + +Returns `node_api_ok` if the API succeeded. + +This API is used to retrieve the underlying data buffer of a `node::Buffer` +and its length. + +*Warning*: Use caution while using this API since the underlying data buffer's +lifetime is not guaranteed if it's managed by the VM. + +#### node_api_get_prototype + + +```c +node_api_status node_api_get_prototype(node_api_env env, + node_api_value object, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] object`: `node_api_value` representing JavaScript `Object` whose + prototype to return. This returns the equivalent of `Object.getPrototypeOf` + (which is not the same as the function's `prototype` property). +* `[out] result`: `node_api_value` representing prototype of the given object. + +Returns `node_api_ok` if the API succeeded. + +#### node_api_get_typedarray_info + + +```c +node_api_status node_api_get_typedarray_info(node_api_env env, + node_api_value typedarray, + node_api_typedarray_type* type, + size_t* length, + void** data, + node_api_value* arraybuffer, + size_t* byte_offset) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] typedarray`: `node_api_value` representing the `TypedArray` whose + properties to query. +* `[out] type`: Scalar datatype of the elements within the `TypedArray`. +* `[out] length`: The number of elements in the `TypedArray`. +* `[out] data`: The data buffer underlying the `TypedArray` adjusted by + the `byte_offset` value so that it points to the first element in the + `TypedArray`. If the length of the array is `0`, this may be `NULL` or + any other pointer value. +* `[out] arraybuffer`: The `ArrayBuffer` underlying the `TypedArray`. +* `[out] byte_offset`: The byte offset within the underlying native array + at which the first element of the arrays is located. The value for the data + parameter has already been adjusted so that data points to the first element + in the array. Therefore, the first byte of the native array would be at + `data - byte_offset`. + +Returns `node_api_ok` if the API succeeded. + +This API returns various properties of a typed array. + +*Warning*: Use caution while using this API since the underlying data buffer +is managed by the VM. + +#### node_api_get_dataview_info + + +```c +node_api_status node_api_get_dataview_info(node_api_env env, + node_api_value dataview, + size_t* byte_length, + void** data, + node_api_value* arraybuffer, + size_t* byte_offset) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] dataview`: `node_api_value` representing the `DataView` whose + properties to query. +* `[out] byte_length`: `Number` of bytes in the `DataView`. +* `[out] data`: The data buffer underlying the `DataView`. + If byte_length is `0`, this may be `NULL` or any other pointer value. +* `[out] arraybuffer`: `ArrayBuffer` underlying the `DataView`. +* `[out] byte_offset`: The byte offset within the data buffer from which + to start projecting the `DataView`. + +Returns `node_api_ok` if the API succeeded. + +This API returns various properties of a `DataView`. + +#### node_api_get_date_value + + +```c +node_api_status node_api_get_date_value(node_api_env env, + node_api_value value, + double* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing a JavaScript `Date`. +* `[out] result`: Time value as a `double` represented as milliseconds since + midnight at the beginning of 01 January, 1970 UTC. + +This API does not observe leap seconds; they are ignored, as +ECMAScript aligns with POSIX time specification. + +Returns `node_api_ok` if the API succeeded. If a non-date `node_api_value` is +passed in it returns `node_api_date_expected`. + +This API returns the C double primitive of time value for the given JavaScript +`Date`. + +#### node_api_get_value_bool + + +```c +node_api_status +node_api_get_value_bool(node_api_env env, node_api_value value, bool* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing JavaScript `Boolean`. +* `[out] result`: C boolean primitive equivalent of the given JavaScript + `Boolean`. + +Returns `node_api_ok` if the API succeeded. If a non-boolean `node_api_value` +is passed in it returns `node_api_boolean_expected`. + +This API returns the C boolean primitive equivalent of the given JavaScript +`Boolean`. + +#### node_api_get_value_double + + +```c +node_api_status node_api_get_value_double(node_api_env env, + node_api_value value, + double* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing JavaScript `Number`. +* `[out] result`: C double primitive equivalent of the given JavaScript + `Number`. + +Returns `node_api_ok` if the API succeeded. If a non-number `node_api_value` is +passed in it returns `node_api_number_expected`. + +This API returns the C double primitive equivalent of the given JavaScript +`Number`. + +#### node_api_get_value_bigint_int64 + + +```c +node_api_status node_api_get_value_bigint_int64(node_api_env env, + node_api_value value, + int64_t* result, + bool* lossless); +``` + +* `[in] env`: The environment that the API is invoked under +* `[in] value`: `node_api_value` representing JavaScript `BigInt`. +* `[out] result`: C `int64_t` primitive equivalent of the given JavaScript + `BigInt`. +* `[out] lossless`: Indicates whether the `BigInt` value was converted + losslessly. + +Returns `node_api_ok` if the API succeeded. If a non-`BigInt` is passed in it +returns `node_api_bigint_expected`. + +This API returns the C `int64_t` primitive equivalent of the given JavaScript +`BigInt`. If needed it will truncate the value, setting `lossless` to `false`. + +#### node_api_get_value_bigint_uint64 + + +```c +node_api_status node_api_get_value_bigint_uint64(node_api_env env, + node_api_value value, + uint64_t* result, + bool* lossless); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing JavaScript `BigInt`. +* `[out] result`: C `uint64_t` primitive equivalent of the given JavaScript + `BigInt`. +* `[out] lossless`: Indicates whether the `BigInt` value was converted + losslessly. + +Returns `node_api_ok` if the API succeeded. If a non-`BigInt` is passed in it +returns `node_api_bigint_expected`. + +This API returns the C `uint64_t` primitive equivalent of the given JavaScript +`BigInt`. If needed it will truncate the value, setting `lossless` to `false`. + +#### node_api_get_value_bigint_words + + +```c +node_api_status node_api_get_value_bigint_words(node_api_env env, + node_api_value value, + int* sign_bit, + size_t* word_count, + uint64_t* words); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing JavaScript `BigInt`. +* `[out] sign_bit`: Integer representing if the JavaScript `BigInt` is positive + or negative. +* `[in/out] word_count`: Must be initialized to the length of the `words` + array. Upon return, it will be set to the actual number of words that + would be needed to store this `BigInt`. +* `[out] words`: Pointer to a pre-allocated 64-bit word array. + +Returns `node_api_ok` if the API succeeded. + +This API converts a single `BigInt` value into a sign bit, 64-bit little-endian +array, and the number of elements in the array. `sign_bit` and `words` may be +both set to `NULL`, in order to get only `word_count`. + +#### node_api_get_value_external + + +```c +node_api_status node_api_get_value_external(node_api_env env, + node_api_value value, + void** result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing JavaScript external value. +* `[out] result`: Pointer to the data wrapped by the JavaScript external value. + +Returns `node_api_ok` if the API succeeded. If a non-external `node_api_value` +is passed in it returns `node_api_invalid_arg`. + +This API retrieves the external data pointer that was previously passed to +`node_api_create_external()`. + +#### node_api_get_value_int32 + + +```c +node_api_status node_api_get_value_int32(node_api_env env, + node_api_value value, + int32_t* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing JavaScript `Number`. +* `[out] result`: C `int32` primitive equivalent of the given JavaScript + `Number`. + +Returns `node_api_ok` if the API succeeded. If a non-number `node_api_value` +is passed in `node_api_number_expected`. + +This API returns the C `int32` primitive equivalent of the given JavaScript +`Number`. + +If the number exceeds the range of the 32 bit integer, then the result is +truncated to the equivalent of the bottom 32 bits. This can result in a large +positive number becoming a negative number if the value is +> 231 - 1. + +Non-finite number values (`NaN`, `+Infinity`, or `-Infinity`) set the result to +zero. + +#### node_api_get_value_int64 + + +```c +node_api_status node_api_get_value_int64(node_api_env env, + node_api_value value, + int64_t* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing JavaScript `Number`. +* `[out] result`: C `int64` primitive equivalent of the given JavaScript + `Number`. + +Returns `node_api_ok` if the API succeeded. If a non-number `node_api_value` +is passed in it returns `node_api_number_expected`. + +This API returns the C `int64` primitive equivalent of the given JavaScript +`Number`. + +`Number` values outside the range of [`Number.MIN_SAFE_INTEGER`][] +`-(2**53 - 1)` - [`Number.MAX_SAFE_INTEGER`][] `(2**53 - 1)` will lose +precision. + +Non-finite number values (`NaN`, `+Infinity`, or `-Infinity`) set the result to +zero. + +#### node_api_get_value_string_latin1 + + +```c +node_api_status node_api_get_value_string_latin1(node_api_env env, + node_api_value value, + char* buf, + size_t bufsize, + size_t* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing JavaScript string. +* `[in] buf`: Buffer to write the ISO-8859-1-encoded string into. If `NULL` is + passed in, the length of the string in bytes and excluding the null + terminator is returned in `result`. +* `[in] bufsize`: Size of the destination buffer. When this value is + insufficient, the returned string is truncated and null-terminated. +* `[out] result`: Number of bytes copied into the buffer, excluding the null + terminator. + +Returns `node_api_ok` if the API succeeded. If a non-`String` `node_api_value` +is passed in it returns `node_api_string_expected`. + +This API returns the ISO-8859-1-encoded string corresponding the value passed +in. + +#### node_api_get_value_string_utf8 + + +```c +node_api_status node_api_get_value_string_utf8(node_api_env env, + node_api_value value, + char* buf, + size_t bufsize, + size_t* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing JavaScript string. +* `[in] buf`: Buffer to write the UTF8-encoded string into. If `NULL` is passed + in, the length of the string in bytes and excluding the null terminator is + returned in `result`. +* `[in] bufsize`: Size of the destination buffer. When this value is + insufficient, the returned string is truncated and null-terminated. +* `[out] result`: Number of bytes copied into the buffer, excluding the null + terminator. + +Returns `node_api_ok` if the API succeeded. If a non-`String` `node_api_value` +is passed in it returns `node_api_string_expected`. + +This API returns the UTF8-encoded string corresponding the value passed in. + +#### node_api_get_value_string_utf16 + + +```c +node_api_status node_api_get_value_string_utf16(node_api_env env, + node_api_value value, + char16_t* buf, + size_t bufsize, + size_t* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing JavaScript string. +* `[in] buf`: Buffer to write the UTF16-LE-encoded string into. If `NULL` is + passed in, the length of the string in 2-byte code units and excluding the + null terminator is returned. +* `[in] bufsize`: Size of the destination buffer. When this value is + insufficient, the returned string is truncated and null-terminated. +* `[out] result`: Number of 2-byte code units copied into the buffer, excluding + the null terminator. + +Returns `node_api_ok` if the API succeeded. If a non-`String` `node_api_value` +is passed in it returns `node_api_string_expected`. + +This API returns the UTF16-encoded string corresponding the value passed in. + +#### node_api_get_value_uint32 + + +```c +node_api_status node_api_get_value_uint32(node_api_env env, + node_api_value value, + uint32_t* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: `node_api_value` representing JavaScript `Number`. +* `[out] result`: C primitive equivalent of the given `node_api_value` as a + `uint32_t`. + +Returns `node_api_ok` if the API succeeded. If a non-number `node_api_value` +is passed in it returns `node_api_number_expected`. + +This API returns the C primitive equivalent of the given `node_api_value` as a +`uint32_t`. + +### Functions to get global instances +#### node_api_get_boolean + + +```c +node_api_status +node_api_get_boolean(node_api_env env, bool value, node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The value of the boolean to retrieve. +* `[out] result`: `node_api_value` representing JavaScript `Boolean` singleton + to retrieve. + +Returns `node_api_ok` if the API succeeded. + +This API is used to return the JavaScript singleton object that is used to +represent the given boolean value. + +#### node_api_get_global + + +```c +node_api_status node_api_get_global(node_api_env env, node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] result`: `node_api_value` representing JavaScript `global` object. + +Returns `node_api_ok` if the API succeeded. + +This API returns the `global` object. + +#### node_api_get_null + + +```c +node_api_status node_api_get_null(node_api_env env, node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] result`: `node_api_value` representing JavaScript `null` object. + +Returns `node_api_ok` if the API succeeded. + +This API returns the `null` object. + +#### node_api_get_undefined + + +```c +node_api_status +node_api_get_undefined(node_api_env env, node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] result`: `node_api_value` representing JavaScript Undefined value. + +Returns `node_api_ok` if the API succeeded. + +This API returns the Undefined object. + +## Working with JavaScript values and abstract operations + +The Node.js API exposes a set of APIs to perform some abstract operations on +JavaScript values. Some of these operations are documented under [Section 7][] +of the [ECMAScript Language Specification][]. + +These APIs support doing one of the following: + +1. Coerce JavaScript values to specific JavaScript types (such as `Number` or + `String`). +2. Check the type of a JavaScript value. +3. Check for equality between two JavaScript values. + +### node_api_coerce_to_bool + + +```c +node_api_status node_api_coerce_to_bool(node_api_env env, + node_api_value value, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value to coerce. +* `[out] result`: `node_api_value` representing the coerced JavaScript +`Boolean`. + +Returns `node_api_ok` if the API succeeded. + +This API implements the abstract operation `ToBoolean()` as defined in +[Section 7.1.2][] of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in `Object`. + +### node_api_coerce_to_number + + +```c +node_api_status node_api_coerce_to_number(node_api_env env, + node_api_value value, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value to coerce. +* `[out] result`: `node_api_value` representing the coerced JavaScript + `Number`. + +Returns `node_api_ok` if the API succeeded. + +This API implements the abstract operation `ToNumber()` as defined in +[Section 7.1.3][] of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in `Object`. + +### node_api_coerce_to_object + + +```c +node_api_status node_api_coerce_to_object(node_api_env env, + node_api_value value, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value to coerce. +* `[out] result`: `node_api_value` representing the coerced JavaScript + `Object`. + +Returns `node_api_ok` if the API succeeded. + +This API implements the abstract operation `ToObject()` as defined in +[Section 7.1.13][] of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in `Object`. + +### node_api_coerce_to_string + + +```c +node_api_status node_api_coerce_to_string(node_api_env env, + node_api_value value, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value to coerce. +* `[out] result`: `node_api_value` representing the coerced JavaScript + `String`. + +Returns `node_api_ok` if the API succeeded. + +This API implements the abstract operation `ToString()` as defined in +[Section 7.1.13][] of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in `Object`. + +### node_api_typeof + + +```c +node_api_status node_api_typeof(node_api_env env, + node_api_value value, + node_api_valuetype* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value whose type to query. +* `[out] result`: The type of the JavaScript value. + +Returns `node_api_ok` if the API succeeded. + +* `node_api_invalid_arg` if the type of `value` is not a known ECMAScript type + and `value` is not an External value. + +This API represents behavior similar to invoking the `typeof` Operator on +the object as defined in [Section 12.5.5][] of the ECMAScript Language +Specification. However, there are some differences: + +1. It has support for detecting an External value. +2. It detects `null` as a separate type, while ECMAScript `typeof` would detect + `object`. + +If `value` has a type that is invalid, an error is returned. + +### node_api_instanceof + + +```c +node_api_status node_api_instanceof(node_api_env env, + node_api_value object, + node_api_value constructor, + bool* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] object`: The JavaScript value to check. +* `[in] constructor`: The JavaScript function object of the constructor + function to check against. +* `[out] result`: Boolean that is set to true if + `object instanceof constructor` is true. + +Returns `node_api_ok` if the API succeeded. + +This API represents invoking the `instanceof` Operator on the object as +defined in [Section 12.10.4][] of the ECMAScript Language Specification. + +### node_api_is_array + + +```c +node_api_status +node_api_is_array(node_api_env env, node_api_value value, bool* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value to check. +* `[out] result`: Whether the given object is an array. + +Returns `node_api_ok` if the API succeeded. + +This API represents invoking the `IsArray` operation on the object +as defined in [Section 7.2.2][] of the ECMAScript Language Specification. + +### node_api_is_arraybuffer + + +```c +node_api_status +node_api_is_arraybuffer(node_api_env env, node_api_value value, bool* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value to check. +* `[out] result`: Whether the given object is an `ArrayBuffer`. + +Returns `node_api_ok` if the API succeeded. + +This API checks if the `Object` passed in is an array buffer. + +### node_api_is_buffer + + +```c +node_api_status +node_api_is_buffer(node_api_env env, node_api_value value, bool* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value to check. +* `[out] result`: Whether the given `node_api_value` represents a + `node::Buffer` object. + +Returns `node_api_ok` if the API succeeded. + +This API checks if the `Object` passed in is a buffer. + +### node_api_is_date + + +```c +node_api_status +node_api_is_date(node_api_env env, node_api_value value, bool* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value to check. +* `[out] result`: Whether the given `node_api_value` represents a JavaScript + `Date` object. + +Returns `node_api_ok` if the API succeeded. + +This API checks if the `Object` passed in is a date. + +### node_api_is_error + + +```c +node_api_status +node_api_is_error(node_api_env env, node_api_value value, bool* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value to check. +* `[out] result`: Whether the given `node_api_value` represents an `Error` + object. + +Returns `node_api_ok` if the API succeeded. + +This API checks if the `Object` passed in is an `Error`. + +### node_api_is_typedarray + + +```c +node_api_status +node_api_is_typedarray(node_api_env env, node_api_value value, bool* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value to check. +* `[out] result`: Whether the given `node_api_value` represents a `TypedArray`. + +Returns `node_api_ok` if the API succeeded. + +This API checks if the `Object` passed in is a typed array. + +### node_api_is_dataview + + +```c +node_api_status +node_api_is_dataview(node_api_env env, node_api_value value, bool* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The JavaScript value to check. +* `[out] result`: Whether the given `node_api_value` represents a `DataView`. + +Returns `node_api_ok` if the API succeeded. + +This API checks if the `Object` passed in is a `DataView`. + +### node_api_strict_equals + + +```c +node_api_status node_api_strict_equals(node_api_env env, + node_api_value lhs, + node_api_value rhs, + bool* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] lhs`: The JavaScript value to check. +* `[in] rhs`: The JavaScript value to check against. +* `[out] result`: Whether the two `node_api_value` objects are equal. + +Returns `node_api_ok` if the API succeeded. + +This API represents the invocation of the Strict Equality algorithm as +defined in [Section 7.2.14][] of the ECMAScript Language Specification. + +### node_api_detach_arraybuffer + + +```c +node_api_status node_api_detach_arraybuffer(node_api_env env, + node_api_value arraybuffer) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] arraybuffer`: The JavaScript `ArrayBuffer` to be detached. + +Returns `node_api_ok` if the API succeeded. If a non-detachable `ArrayBuffer` +is passed in it returns `node_api_detachable_arraybuffer_expected`. + +Generally, an `ArrayBuffer` is non-detachable if it has been detached before. +The engine may impose additional conditions on whether an `ArrayBuffer` is +detachable. For example, V8 requires that the `ArrayBuffer` be external, +that is, created with [`node_api_create_external_arraybuffer`][]. + +This API represents the invocation of the `ArrayBuffer` detach operation as +defined in [Section 24.1.1.3][] of the ECMAScript Language Specification. + +### node_api_is_detached_arraybuffer + + +```c +node_api_status node_api_is_detached_arraybuffer(node_api_env env, + node_api_value arraybuffer, + bool* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] arraybuffer`: The JavaScript `ArrayBuffer` to be checked. +* `[out] result`: Whether the `arraybuffer` is detached. + +Returns `node_api_ok` if the API succeeded. + +The `ArrayBuffer` is considered detached if its internal data is `null`. + +This API represents the invocation of the `ArrayBuffer` `IsDetachedBuffer` +operation as defined in [Section 24.1.1.2][] of the ECMAScript Language +Specification. + +## Working with JavaScript properties + +The Node.js API exposes a set of APIs to get and set properties on JavaScript +objects. Some of these types are documented under [Section 7][] of the +[ECMAScript Language Specification][]. + +Properties in JavaScript are represented as a tuple of a key and a value. +Fundamentally, all property keys in the Node.js API can be represented in one +of the following forms: + +* Named: a simple UTF8-encoded string +* Integer-Indexed: an index value represented by `uint32_t` +* JavaScript value: these are represented in the Node.js API by + `node_api_value`. This can be a `node_api_value` representing a `String`, + `Number`, or `Symbol`. + +Node.js API values are represented by the type `node_api_value`. +Any Node.js API call that requires a JavaScript value takes in a +`node_api_value`. However, it's the caller's responsibility to make sure that +the `node_api_value` in question is of the JavaScript type expected by the API. + +The APIs documented in this section provide a simple interface to +get and set properties on arbitrary JavaScript objects represented by +`node_api_value`. + +For instance, consider the following JavaScript code snippet: + +```js +const obj = {}; +obj.myProp = 123; +``` + +The equivalent can be done using Node.js API values with the following snippet: + +```c +node_api_status status = node_api_generic_failure; + +// const obj = {} +node_api_value obj, value; +status = node_api_create_object(env, &obj); +if (status != node_api_ok) return status; + +// Create a node_api_value for 123 +status = node_api_create_int32(env, 123, &value); +if (status != node_api_ok) return status; + +// obj.myProp = 123 +status = node_api_set_named_property(env, obj, "myProp", value); +if (status != node_api_ok) return status; +``` + +Indexed properties can be set in a similar manner. Consider the following +JavaScript snippet: + +```js +const arr = []; +arr[123] = 'hello'; +``` + +The equivalent can be done using Node.js API values with the following snippet: + +```c +node_api_status status = node_api_generic_failure; + +// const arr = []; +node_api_value arr, value; +status = node_api_create_array(env, &arr); +if (status != node_api_ok) return status; + +// Create a node_api_value for 'hello' +status = + node_api_create_string_utf8(env, "hello", NODE_API_AUTO_LENGTH, &value); +if (status != node_api_ok) return status; + +// arr[123] = 'hello'; +status = node_api_set_element(env, arr, 123, value); +if (status != node_api_ok) return status; +``` + +Properties can be retrieved using the APIs described in this section. +Consider the following JavaScript snippet: + +```js +const arr = []; +const value = arr[123]; +``` + +The following is the approximate equivalent of the Node.js API counterpart: + +```c +node_api_status status = node_api_generic_failure; + +// const arr = [] +node_api_value arr, value; +status = node_api_create_array(env, &arr); +if (status != node_api_ok) return status; + +// const value = arr[123] +status = node_api_get_element(env, arr, 123, &value); +if (status != node_api_ok) return status; +``` + +Finally, multiple properties can also be defined on an object for performance +reasons. Consider the following JavaScript: + +```js +const obj = {}; +Object.defineProperties(obj, { + 'foo': { value: 123, writable: true, configurable: true, enumerable: true }, + 'bar': { value: 456, writable: true, configurable: true, enumerable: true } +}); +``` + +The following is the approximate equivalent of the Node.js API counterpart: + +```c +node_api_status status = node_api_status_generic_failure; + +// const obj = {}; +node_api_value obj; +status = node_api_create_object(env, &obj); +if (status != node_api_ok) return status; + +// Create node_api_values for 123 and 456 +node_api_value fooValue, barValue; +status = node_api_create_int32(env, 123, &fooValue); +if (status != node_api_ok) return status; +status = node_api_create_int32(env, 456, &barValue); +if (status != node_api_ok) return status; + +// Set the properties +node_api_property_descriptor descriptors[] = { + { "foo", NULL, NULL, NULL, NULL, fooValue, + node_api_writable | node_api_configurable, NULL }, + { "bar", NULL, NULL, NULL, NULL, barValue, + node_api_writable | node_api_configurable, NULL } +} +status = node_api_define_properties(env, + obj, + sizeof(descriptors) / sizeof(descriptors[0]), + descriptors); +if (status != node_api_ok) return status; +``` + +### Structures +#### node_api_property_attributes + + +```c +typedef enum { + node_api_default = 0, + node_api_writable = 1 << 0, + node_api_enumerable = 1 << 1, + node_api_configurable = 1 << 2, + + // Used with node_api_define_class to distinguish static properties + // from instance properties. Ignored by node_api_define_properties. + node_api_static = 1 << 10, + + // Default for class methods. + node_api_default_method = node_api_writable | node_api_configurable, + + // Default for object properties, like in JS obj[prop]. + node_api_default_property = node_api_writable | + node_api_enumerable | + node_api_configurable, +} node_api_property_attributes; +``` + +`node_api_property_attributes` are flags used to control the behavior of +properties set on a JavaScript object. Other than `node_api_static` they +correspond to the attributes listed in [Section 6.1.7.1][] of the +[ECMAScript Language Specification][]. They can be one or more of the following +bitflags: + +* `node_api_default`: No explicit attributes are set on the property. By + default, a property is read only, not enumerable and not configurable. +* `node_api_writable`: The property is writable. +* `node_api_enumerable`: The property is enumerable. +* `node_api_configurable`: The property is configurable as defined in + [Section 6.1.7.1][] of the [ECMAScript Language Specification][]. +* `node_api_static`: The property will be defined as a static property on a + class as opposed to an instance property, which is the default. This is used + only by [`node_api_define_class`][]. It is ignored by + `node_api_define_properties`. +* `node_api_default_method`: Like a method in a JS class, the property is + configurable and writeable, but not enumerable. +* `node_api_default_property`: Like a property set via assignment in + JavaScript, the property is writable, enumerable, and configurable. + +#### node_api_property_descriptor + +```c +typedef struct { + // One of utf8name or name should be NULL. + const char* utf8name; + node_api_value name; + + node_api_callback method; + node_api_callback getter; + node_api_callback setter; + node_api_value value; + + node_api_property_attributes attributes; + void* data; +} node_api_property_descriptor; +``` + +* `utf8name`: Optional `String` describing the key for the property, + encoded as UTF8. One of `utf8name` or `name` must be provided for the + property. +* `name`: Optional `node_api_value` that points to a JavaScript string or + symbol to be used as the key for the property. One of `utf8name` or `name` + must be provided for the property. +* `value`: The value that's retrieved by a get access of the property if the + property is a data property. If this is passed in, set `getter`, `setter`, + `method` and `data` to `NULL` (since these members won't be used). +* `getter`: A function to call when a get access of the property is performed. + If this is passed in, set `value` and `method` to `NULL` (since these members + won't be used). The given function is called implicitly by the runtime when + the property is accessed from JavaScript code (or if a get on the property is + performed using a Node.js API call). [`node_api_callback`][] provides more + details. +* `setter`: A function to call when a set access of the property is performed. + If this is passed in, set `value` and `method` to `NULL` (since these members + won't be used). The given function is called implicitly by the runtime when + the property is set from JavaScript code (or if a set on the property is + performed using a Node.js API call). [`node_api_callback`][] provides more + details. +* `method`: Set this to make the property descriptor object's `value` + property to be a JavaScript function represented by `method`. If this is + passed in, set `value`, `getter` and `setter` to `NULL` (since these members + won't be used). [`node_api_callback`][] provides more details. +* `attributes`: The attributes associated with the particular property. See + [`node_api_property_attributes`][]. +* `data`: The callback data passed into `method`, `getter` and `setter` if this + function is invoked. + +### Functions +#### node_api_get_property_names + + +```c +node_api_status node_api_get_property_names(node_api_env env, + node_api_value object, + node_api_value* result); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object from which to retrieve the properties. +* `[out] result`: A `node_api_value` representing an array of JavaScript values + that represent the property names of the object. The API can be used to + iterate over `result` using [`node_api_get_array_length`][] + and [`node_api_get_element`][]. + +Returns `node_api_ok` if the API succeeded. + +This API returns the names of the enumerable properties of `object` as an array +of strings. The properties of `object` whose key is a symbol will not be +included. + +#### node_api_get_all_property_names + + +```c +node_api_status +node_api_get_all_property_names(node_api_env env, + node_api_value object, + node_api_key_collection_mode key_mode, + node_api_key_filter key_filter, + node_api_key_conversion key_conversion, + node_api_value* result); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object from which to retrieve the properties. +* `[in] key_mode`: Whether to retrieve prototype properties as well. +* `[in] key_filter`: Which properties to retrieve + (enumerable/readable/writable). +* `[in] key_conversion`: Whether to convert numbered property keys to strings. +* `[out] result`: A `node_api_value` representing an array of JavaScript values + that represent the property names of the object. + [`node_api_get_array_length`][] and [`node_api_get_element`][] can be used to + iterate over `result`. + +Returns `node_api_ok` if the API succeeded. + +This API returns an array containing the names of the available properties +of this object. + +#### node_api_set_property + + +```c +node_api_status node_api_set_property(node_api_env env, + node_api_value object, + node_api_value key, + node_api_value value); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object on which to set the property. +* `[in] key`: The name of the property to set. +* `[in] value`: The property value. + +Returns `node_api_ok` if the API succeeded. + +This API set a property on the `Object` passed in. + +#### node_api_get_property + + +```c +node_api_status node_api_get_property(node_api_env env, + node_api_value object, + node_api_value key, + node_api_value* result); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object from which to retrieve the property. +* `[in] key`: The name of the property to retrieve. +* `[out] result`: The value of the property. + +Returns `node_api_ok` if the API succeeded. + +This API gets the requested property from the `Object` passed in. + +#### node_api_has_property + + +```c +node_api_status node_api_has_property(node_api_env env, + node_api_value object, + node_api_value key, + bool* result); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object to query. +* `[in] key`: The name of the property whose existence to check. +* `[out] result`: Whether the property exists on the object or not. + +Returns `node_api_ok` if the API succeeded. + +This API checks if the `Object` passed in has the named property. + +#### node_api_delete_property + + +```c +node_api_status node_api_delete_property(node_api_env env, + node_api_value object, + node_api_value key, + bool* result); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object to query. +* `[in] key`: The name of the property to delete. +* `[out] result`: Whether the property deletion succeeded or not. `result` can + optionally be ignored by passing `NULL`. + +Returns `node_api_ok` if the API succeeded. + +This API attempts to delete the `key` own property from `object`. + +#### node_api_has_own_property + + +```c +node_api_status node_api_has_own_property(node_api_env env, + node_api_value object, + node_api_value key, + bool* result); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object to query. +* `[in] key`: The name of the own property whose existence to check. +* `[out] result`: Whether the own property exists on the object or not. + +Returns `node_api_ok` if the API succeeded. + +This API checks if the `Object` passed in has the named own property. `key` +must be a string or a `Symbol`, or an error will be thrown. The Node.js API +will not perform any conversion between data types. + +#### node_api_set_named_property + + +```c +node_api_status node_api_set_named_property(node_api_env env, + node_api_value object, + const char* utf8Name, + node_api_value value); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object on which to set the property. +* `[in] utf8Name`: The name of the property to set. +* `[in] value`: The property value. + +Returns `node_api_ok` if the API succeeded. + +This method is equivalent to calling [`node_api_set_property`][] with a +`node_api_value` created from the string passed in as `utf8Name`. + +#### node_api_get_named_property + + +```c +node_api_status node_api_get_named_property(node_api_env env, + node_api_value object, + const char* utf8Name, + node_api_value* result); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object from which to retrieve the property. +* `[in] utf8Name`: The name of the property to get. +* `[out] result`: The value of the property. + +Returns `node_api_ok` if the API succeeded. + +This method is equivalent to calling [`node_api_get_property`][] with a +`node_api_value` created from the string passed in as `utf8Name`. + +#### node_api_has_named_property + + +```c +node_api_status node_api_has_named_property(node_api_env env, + node_api_value object, + const char* utf8Name, + bool* result); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object to query. +* `[in] utf8Name`: The name of the property whose existence to check. +* `[out] result`: Whether the property exists on the object or not. + +Returns `node_api_ok` if the API succeeded. + +This method is equivalent to calling [`node_api_has_property`][] with a +`node_api_value` created from the string passed in as `utf8Name`. + +#### node_api_set_element + + +```c +node_api_status node_api_set_element(node_api_env env, + node_api_value object, + uint32_t index, + node_api_value value); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object from which to set the properties. +* `[in] index`: The index of the property to set. +* `[in] value`: The property value. + +Returns `node_api_ok` if the API succeeded. + +This API sets and element on the `Object` passed in. + +#### node_api_get_element + + +```c +node_api_status node_api_get_element(node_api_env env, + node_api_value object, + uint32_t index, + node_api_value* result); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object from which to retrieve the property. +* `[in] index`: The index of the property to get. +* `[out] result`: The value of the property. + +Returns `node_api_ok` if the API succeeded. + +This API gets the element at the requested index. + +#### node_api_has_element + + +```c +node_api_status node_api_has_element(node_api_env env, + node_api_value object, + uint32_t index, + bool* result); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object to query. +* `[in] index`: The index of the property whose existence to check. +* `[out] result`: Whether the property exists on the object or not. + +Returns `node_api_ok` if the API succeeded. + +This API returns if the `Object` passed in has an element at the +requested index. + +#### node_api_delete_element + + +```c +node_api_status node_api_delete_element(node_api_env env, + node_api_value object, + uint32_t index, + bool* result); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object to query. +* `[in] index`: The index of the property to delete. +* `[out] result`: Whether the element deletion succeeded or not. `result` can + optionally be ignored by passing `NULL`. + +Returns `node_api_ok` if the API succeeded. + +This API attempts to delete the specified `index` from `object`. + +#### node_api_define_properties + + +```c +node_api_status +node_api_define_properties(node_api_env env, + node_api_value object, + size_t property_count, + const node_api_property_descriptor* properties); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object from which to retrieve the properties. +* `[in] property_count`: The number of elements in the `properties` array. +* `[in] properties`: The array of property descriptors. + +Returns `node_api_ok` if the API succeeded. + +This method allows the efficient definition of multiple properties on a given +object. The properties are defined using property descriptors (see +[`node_api_property_descriptor`][]). Given an array of such property +descriptors, this API will set the properties on the object one at a time, as +defined by `DefineOwnProperty()` (described in [Section 9.1.6][] of the +ECMA-262 specification). + +#### node_api_object_freeze + + +> Stability: 1 - Experimental + +```c +node_api_status node_api_object_freeze(node_api_env env, + node_api_value object); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object to freeze. + +Returns `node_api_ok` if the API succeeded. + +This method freezes a given object. This prevents new properties from +being added to it, existing properties from being removed, prevents +changing the enumerability, configurability, or writability of existing +properties, and prevents the values of existing properties from being changed. +It also prevents the object's prototype from being changed. This is described +in [Section 19.1.2.6](https://tc39.es/ecma262/#sec-object.freeze) of the +ECMA-262 specification. + +#### node_api_object_seal + + +> Stability: 1 - Experimental + +```c +node_api_status node_api_object_seal(node_api_env env, + node_api_value object); +``` + +* `[in] env`: The environment that the Node.js API call is invoked under. +* `[in] object`: The object to seal. + +Returns `node_api_ok` if the API succeeded. + +This method seals a given object. This prevents new properties from being +added to it, as well as marking all existing properties as non-configurable. +This is described in +[Section 19.1.2.20](https://tc39.es/ecma262/#sec-object.seal) of the ECMA-262 +specification. + +## Working with JavaScript functions + +The Node.js API provides a set of APIs that allow JavaScript code to +call back into native code. Node.js APIs that support calling back +into native code take in a callback functions represented by +the `node_api_callback` type. When the JavaScript VM calls back to +native code, the `node_api_callback` function provided is invoked. The APIs +documented in this section allow the callback function to do the +following: + +* Get information about the context in which the callback was invoked. +* Get the arguments passed into the callback. +* Return a `node_api_value` back from the callback. + +Additionally, the Node.js API provides a set of functions which allow calling +JavaScript functions from native code. One can either call a function +like a regular JavaScript function call, or as a constructor +function. + +Any non-`NULL` data which is passed to this API via the `data` field of the +`node_api_property_descriptor` items can be associated with `object` and freed +whenever `object` is garbage-collected by passing both `object` and the data to +[`node_api_add_finalizer`][]. + +### node_api_call_function + + +```c +NODE_API_EXTERN node_api_status +node_api_call_function(node_api_env env, + node_api_value recv, + node_api_value func, + size_t argc, + const node_api_value* argv, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] recv`: The `this` object passed to the called function. +* `[in] func`: `node_api_value` representing the JavaScript function to be + invoked. +* `[in] argc`: The count of elements in the `argv` array. +* `[in] argv`: Array of `node_api_values` representing JavaScript values passed + in as arguments to the function. +* `[out] result`: `node_api_value` representing the JavaScript object returned. + +Returns `node_api_ok` if the API succeeded. + +This method allows a JavaScript function object to be called from a native +add-on. This is the primary mechanism of calling back *from* the add-on's +native code *into* JavaScript. For the special case of calling into JavaScript +after an async operation, see [`node_api_make_callback`][]. + +A sample use case might look as follows. Consider the following JavaScript +snippet: + +```js +function AddTwo(num) { + return num + 2; +} +``` + +Then, the above function can be invoked from a native add-on using the +following code: + +```c +// Get the function named "AddTwo" on the global object +node_api_value global, add_two, arg; +node_api_status status = node_api_get_global(env, &global); +if (status != node_api_ok) return; + +status = node_api_get_named_property(env, global, "AddTwo", &add_two); +if (status != node_api_ok) return; + +// const arg = 1337 +status = node_api_create_int32(env, 1337, &arg); +if (status != node_api_ok) return; + +node_api_value* argv = &arg; +size_t argc = 1; + +// AddTwo(arg); +node_api_value return_val; +status = node_api_call_function(env, global, add_two, argc, argv, &return_val); +if (status != node_api_ok) return; + +// Convert the result back to a native type +int32_t result; +status = node_api_get_value_int32(env, return_val, &result); +if (status != node_api_ok) return; +``` + +### node_api_create_function + + +```c +node_api_status node_api_create_function(node_api_env env, + const char* utf8name, + size_t length, + node_api_callback cb, + void* data, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] utf8Name`: The name of the function encoded as UTF8. This is visible + within JavaScript as the new function object's `name` property. +* `[in] length`: The length of the `utf8name` in bytes, or + `NODE_API_AUTO_LENGTH` if it is null-terminated. +* `[in] cb`: The native function which should be called when this function + object is invoked. [`node_api_callback`][] provides more details. +* `[in] data`: User-provided data context. This will be passed back into the + function when invoked later. +* `[out] result`: `node_api_value` representing the JavaScript function object + for the newly created function. + +Returns `node_api_ok` if the API succeeded. + +This API allows an add-on author to create a function object in native code. +This is the primary mechanism to allow calling *into* the add-on's native code +*from* JavaScript. + +The newly created function is not automatically visible from script after this +call. Instead, a property must be explicitly set on any object that is visible +to JavaScript, in order for the function to be accessible from script. + +In order to expose a function as part of the +add-on's module exports, set the newly created function on the exports +object. A sample module might look as follows: + +```c +node_api_value SayHello(node_api_env env, node_api_callback_info info) { + printf("Hello\n"); + return NULL; +} + +node_api_value Init(node_api_env env, node_api_value exports) { + node_api_status status; + + node_api_value fn; + status = node_api_create_function(env, NULL, 0, SayHello, NULL, &fn); + if (status != node_api_ok) return NULL; + + status = node_api_set_named_property(env, exports, "sayHello", fn); + if (status != node_api_ok) return NULL; + + return exports; +} + +NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) +``` + +Given the above code, the add-on can be used from JavaScript as follows: + +```js +const myaddon = require('./addon'); +myaddon.sayHello(); +``` + +The string passed to `require()` is the name of the target in `binding.gyp` +responsible for creating the `.node` file. + +Any non-`NULL` data which is passed to this API via the `data` parameter can +be associated with the resulting JavaScript function (which is returned in the +`result` parameter) and freed whenever the function is garbage-collected by +passing both the JavaScript function and the data to +[`node_api_add_finalizer`][]. + +JavaScript `Function`s are described in [Section 19.2][] of the ECMAScript +Language Specification. + +### node_api_get_cb_info + + +```c +node_api_status node_api_get_cb_info(node_api_env env, + node_api_callback_info cbinfo, + size_t* argc, + node_api_value* argv, + node_api_value* thisArg, + void** data) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] cbinfo`: The callback info passed into the callback function. +* `[in-out] argc`: Specifies the length of the provided `argv` array and + receives the actual count of arguments. +* `[out] argv`: Buffer to which the `node_api_value` representing the arguments + are copied. If there are more arguments than the provided count, only the + requested number of arguments are copied. If there are fewer arguments + provided than claimed, the rest of `argv` is filled with `node_api_value` + values that represent `undefined`. +* `[out] this`: Receives the JavaScript `this` argument for the call. +* `[out] data`: Receives the data pointer for the callback. + +Returns `node_api_ok` if the API succeeded. + +This method is used within a callback function to retrieve details about the +call like the arguments and the `this` pointer from a given callback info. + +### node_api_get_new_target + + +```c +node_api_status node_api_get_new_target(node_api_env env, + node_api_callback_info cbinfo, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] cbinfo`: The callback info passed into the callback function. +* `[out] result`: The `new.target` of the constructor call. + +Returns `node_api_ok` if the API succeeded. + +This API returns the `new.target` of the constructor call. If the current +callback is not a constructor call, the result is `NULL`. + +### node_api_new_instance + + +```c +node_api_status node_api_new_instance(node_api_env env, + node_api_value cons, + size_t argc, + node_api_value* argv, + node_api_value* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] cons`: `node_api_value` representing the JavaScript function to be + invoked as a constructor. +* `[in] argc`: The count of elements in the `argv` array. +* `[in] argv`: Array of JavaScript values as `node_api_value` representing the + arguments to the constructor. +* `[out] result`: `node_api_value` representing the JavaScript object returned, + which in this case is the constructed object. + +This method is used to instantiate a new JavaScript value using a given +`node_api_value` that represents the constructor for the object. For example, +consider the following snippet: + +```js +function MyObject(param) { + this.param = param; +} + +const arg = 'hello'; +const value = new MyObject(arg); +``` + +The following can be approximated in the Node.js API using the following +snippet: + +```c +// Get the constructor function MyObject +node_api_value global, constructor, arg, value; +node_api_status status = node_api_get_global(env, &global); +if (status != node_api_ok) return; + +status = node_api_get_named_property(env, global, "MyObject", &constructor); +if (status != node_api_ok) return; + +// const arg = "hello" +status = node_api_create_string_utf8(env, "hello", NODE_API_AUTO_LENGTH, &arg); +if (status != node_api_ok) return; + +node_api_value* argv = &arg; +size_t argc = 1; + +// const value = new MyObject(arg) +status = node_api_new_instance(env, constructor, argc, argv, &value); +``` + +Returns `node_api_ok` if the API succeeded. + +## Object wrap + +The Node.js API offers a way to "wrap" C++ classes and instances so that the +class constructor and methods can be called from JavaScript. + +1. The [`node_api_define_class`][] API defines a JavaScript class with + constructor, static properties and methods, and instance properties and + methods that correspond to the C++ class. +2. When JavaScript code invokes the constructor, the constructor callback + uses [`node_api_wrap`][] to wrap a new C++ instance in a JavaScript object, + then returns the wrapper object. +3. When JavaScript code invokes a method or property accessor on the class, + the corresponding `node_api_callback` C++ function is invoked. For an + instance callback, [`node_api_unwrap`][] obtains the C++ instance that is + the target of the call. + +For wrapped objects it may be difficult to distinguish between a function +called on a class prototype and a function called on an instance of a class. +A common pattern used to address this problem is to save a persistent +reference to the class constructor for later `instanceof` checks. + +```c +node_api_value MyClass_constructor = NULL; +status = node_api_get_reference_value(env, + MyClass::es_constructor, + &MyClass_constructor); +assert(node_api_ok == status); +bool is_instance = false; +status = node_api_instanceof(env, es_this, MyClass_constructor, &is_instance); +assert(node_api_ok == status); +if (is_instance) { + // node_api_unwrap() ... +} else { + // otherwise... +} +``` + +The reference must be freed once it is no longer needed. + +There are occasions where `node_api_instanceof()` is insufficient for ensuring +that a JavaScript object is a wrapper for a certain native type. This is the +case especially when wrapped JavaScript objects are passed back into the addon +via static methods rather than as the `this` value of prototype methods. In +such cases there is a chance that they may be unwrapped incorrectly. + +```js +const myAddon = require('./build/Release/my_addon.node'); + +// `openDatabase()` returns a JavaScript object that wraps a native database +// handle. +const dbHandle = myAddon.openDatabase(); + +// `query()` returns a JavaScript object that wraps a native query handle. +const queryHandle = myAddon.query(dbHandle, 'Gimme ALL the things!'); + +// There is an accidental error in the line below. The first parameter to +// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not +// the query handle (`query`), so the correct condition for the while-loop +// should be +// +// myAddon.queryHasRecords(dbHandle, queryHandle) +// +while (myAddon.queryHasRecords(queryHandle, dbHandle)) { + // retrieve records +} +``` + +In the above example `myAddon.queryHasRecords()` is a method that accepts two +arguments. The first is a database handle and the second is a query handle. +Internally, it unwraps the first argument and casts the resulting pointer to a +native database handle. It then unwraps the second argument and casts the +resulting pointer to a query handle. If the arguments are passed in the wrong +order, the casts will work, however, there is a good chance that the underlying +database operation will fail, or will even cause an invalid memory access. + +To ensure that the pointer retrieved from the first argument is indeed a +pointer to a database handle and, similarly, that the pointer retrieved from +the second argument is indeed a pointer to a query handle, the implementation +of `queryHasRecords()` has to perform a type validation. Retaining the +JavaScript class constructor from which the database handle was instantiated +and the constructor from which the query handle was instantiated in +`node_api_ref`s can help, because `node_api_instanceof()` can then be used to +ensure that the instances passed into `queryHashRecords()` are indeed of the +correct type. + +Unfortunately, `node_api_instanceof()` does not protect against prototype +manipulation. For example, the prototype of the database handle instance can be +set to the prototype of the constructor for query handle instances. In this +case, the database handle instance can appear as a query handle instance, and +it will pass the `node_api_instanceof()` test for a query handle instance, +while still containing a pointer to a database handle. + +To this end, the Node.js API provides type-tagging capabilities. + +A type tag is a 128-bit integer unique to the addon. The Node.js API provides +the `node_api_type_tag` structure for storing a type tag. When such a value is +passed along with a JavaScript object stored in a `node_api_value` to +`node_api_type_tag_object()`, the JavaScript object will be "marked" with the +type tag. The "mark" is invisible on the JavaScript side. When a JavaScript +object arrives into a native binding, `node_api_check_object_type_tag()` can be +used along with the original type tag to determine whether the JavaScript +object was previously "marked" with the type tag. This creates a type-checking +capability of a higher fidelity than `node_api_instanceof()` can provide, +because such type-tagging survives prototype manipulation and addon +unloading/reloading. + +Continuing the above example, the following skeleton addon implementation +illustrates the use of `node_api_type_tag_object()` and +`node_api_check_object_type_tag()`. + +```c +// This value is the type tag for a database handle. The command +// +// uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\1, 0x\2/' +// +// can be used to obtain the two values with which to initialize the structure. +static const node_api_type_tag DatabaseHandleTypeTag = { + 0x1edf75a38336451d, 0xa5ed9ce2e4c00c38 +}; + +// This value is the type tag for a query handle. +static const node_api_type_tag QueryHandleTypeTag = { + 0x9c73317f9fad44a3, 0x93c3920bf3b0ad6a +}; + +static node_api_value +openDatabase(node_api_env env, node_api_callback_info info) { + node_api_status status; + node_api_value result; + + // Perform the underlying action which results in a database handle. + DatabaseHandle* dbHandle = open_database(); + + // Create a new, empty JS object. + status = node_api_create_object(env, &result); + if (status != node_api_ok) return NULL; + + // Tag the object to indicate that it holds a pointer to a `DatabaseHandle`. + status = node_api_type_tag_object(env, result, &DatabaseHandleTypeTag); + if (status != node_api_ok) return NULL; + + // Store the pointer to the `DatabaseHandle` structure inside the JS object. + status = node_api_wrap(env, result, dbHandle, NULL, NULL, NULL); + if (status != node_api_ok) return NULL; + + return result; +} + +// Later when we receive a JavaScript object purporting to be a database handle +// we can use `node_api_check_object_type_tag()` to ensure that it is indeed +// such a handle. + +static node_api_value +query(node_api_env env, node_api_callback_info info) { + node_api_status status; + size_t argc = 2; + node_api_value argv[2]; + bool is_db_handle; + + status = node_api_get_cb_info(env, info, &argc, argv, NULL, NULL); + if (status != node_api_ok) return NULL; + + // Check that the object passed as the first parameter has the previously + // applied tag. + status = node_api_check_object_type_tag(env, + argv[0], + &DatabaseHandleTypeTag, + &is_db_handle); + if (status != node_api_ok) return NULL; + + // Throw a `TypeError` if it doesn't. + if (!is_db_handle) { + // Throw a TypeError. + return NULL; + } +} +``` + +### node_api_define_class + + +```c +node_api_status +node_api_define_class(node_api_env env, + const char* utf8name, + size_t length, + node_api_callback constructor, + void* data, + size_t property_count, + const node_api_property_descriptor* properties, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] utf8name`: Name of the JavaScript constructor function; When wrapping a + C++ class, we recommend for clarity that this name be the same as that of + the C++ class. +* `[in] length`: The length of the `utf8name` in bytes, or + `NODE_API_AUTO_LENGTH` if it is null-terminated. +* `[in] constructor`: Callback function that handles constructing instances + of the class. When wrapping a C++ class, this method must be a static member + with the [`node_api_callback`][] signature. A C++ class constructor cannot be + used. [`node_api_callback`][] provides more details. +* `[in] data`: Optional data to be passed to the constructor callback as + the `data` property of the callback info. +* `[in] property_count`: Number of items in the `properties` array argument. +* `[in] properties`: Array of property descriptors describing static and + instance data properties, accessors, and methods on the class + See `node_api_property_descriptor`. +* `[out] result`: A `node_api_value` representing the constructor function for + the class. + +Returns `node_api_ok` if the API succeeded. + +Defines a JavaScript class, including: + +* A JavaScript constructor function that has the class name. When wrapping a + corresponding C++ class, the callback passed via `constructor` can be used to + instantiate a new C++ class instance, which can then be placed inside the + JavaScript object instance being constructed using [`node_api_wrap`][]. +* Properties on the constructor function whose implementation can call + corresponding _static_ data properties, accessors, and methods of the C++ + class (defined by property descriptors with the `node_api_static` attribute). +* Properties on the constructor function's `prototype` object. When wrapping a + C++ class, _non-static_ data properties, accessors, and methods of the C++ + class can be called from the static functions given in the property + descriptors without the `node_api_static` attribute after retrieving the C++ + class instance placed inside the JavaScript object instance by using + [`node_api_unwrap`][]. + +When wrapping a C++ class, the C++ constructor callback passed via +`constructor` should be a static method on the class that calls the actual +class constructor, then wraps the new C++ instance in a JavaScript object, and +returns the wrapper object. See [`node_api_wrap`][] for details. + +The JavaScript constructor function returned from [`node_api_define_class`][] +is often saved and used later to construct new instances of the class from +native code, and/or to check whether provided values are instances of the +class. In that case, to prevent the function value from being +garbage-collected, a strong persistent reference to it can be created using +[`node_api_create_reference`][], ensuring that the reference count is +kept >= 1. + +Any non-`NULL` data which is passed to this API via the `data` parameter or via +the `data` field of the `node_api_property_descriptor` array items can be +associated with the resulting JavaScript constructor (which is returned in the +`result` parameter) and freed whenever the class is garbage-collected by +passing both the JavaScript function and the data to +[`node_api_add_finalizer`][]. + +### node_api_wrap + + +```c +node_api_status node_api_wrap(node_api_env env, + node_api_value js_object, + void* native_object, + node_api_finalize finalize_cb, + void* finalize_hint, + node_api_ref* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] js_object`: The JavaScript object that will be the wrapper for the + native object. +* `[in] native_object`: The native instance that will be wrapped in the + JavaScript object. +* `[in] finalize_cb`: Optional native callback that can be used to free the + native instance when the JavaScript object is ready for garbage-collection. + [`node_api_finalize`][] provides more details. +* `[in] finalize_hint`: Optional contextual hint that is passed to the + finalize callback. +* `[out] result`: Optional reference to the wrapped object. + +Returns `node_api_ok` if the API succeeded. + +Wraps a native instance in a JavaScript object. The native instance can be +retrieved later using `node_api_unwrap()`. + +When JavaScript code invokes a constructor for a class that was defined using +`node_api_define_class()`, the `node_api_callback` for the constructor is +invoked. After constructing an instance of the native class, the callback must +then call `node_api_wrap()` to wrap the newly constructed instance in the +already-created JavaScript object that is the `this` argument to the +constructor callback. (That `this` object was created from the constructor +function's `prototype`, so it already has definitions of all the instance +properties and methods.) + +Typically when wrapping a class instance, a finalize callback should be +provided that simply deletes the native instance that is received as the `data` +argument to the finalize callback. + +The optional returned reference is initially a weak reference, meaning it +has a reference count of 0. Typically this reference count would be incremented +temporarily during async operations that require the instance to remain valid. + +*Caution*: The optional returned reference (if obtained) should be deleted via +[`node_api_delete_reference`][] ONLY in response to the finalize callback +invocation. If it is deleted before then, then the finalize callback may never +be invoked. Therefore, when obtaining a reference a finalize callback is also +required in order to enable correct disposal of the reference. + +Calling `node_api_wrap()` a second time on an object will return an error. To +associate another native instance with the object, use `node_api_remove_wrap()` +first. + +### node_api_unwrap + + +```c +node_api_status node_api_unwrap(node_api_env env, + node_api_value js_object, + void** result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] js_object`: The object associated with the native instance. +* `[out] result`: Pointer to the wrapped native instance. + +Returns `node_api_ok` if the API succeeded. + +Retrieves a native instance that was previously wrapped in a JavaScript +object using `node_api_wrap()`. + +When JavaScript code invokes a method or property accessor on the class, the +corresponding `node_api_callback` is invoked. If the callback is for an +instance method or accessor, then the `this` argument to the callback is the +wrapper object; the wrapped C++ instance that is the target of the call can be +obtained then by calling `node_api_unwrap()` on the wrapper object. + +### node_api_remove_wrap + + +```c +node_api_status node_api_remove_wrap(node_api_env env, + node_api_value js_object, + void** result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] js_object`: The object associated with the native instance. +* `[out] result`: Pointer to the wrapped native instance. + +Returns `node_api_ok` if the API succeeded. + +Retrieves a native instance that was previously wrapped in the JavaScript +object `js_object` using `node_api_wrap()` and removes the wrapping. If a +finalize callback was associated with the wrapping, it will no longer be called +when the JavaScript object becomes garbage-collected. + +### node_api_type_tag_object + + +> Stability: 1 - Experimental + +```c +node_api_status node_api_type_tag_object(node_api_env env, + node_api_value js_object, + const node_api_type_tag* type_tag); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] js_object`: The JavaScript object to be marked. +* `[in] type_tag`: The tag with which the object is to be marked. + +Returns `node_api_ok` if the API succeeded. + +Associates the value of the `type_tag` pointer with the JavaScript object. +`node_api_check_object_type_tag()` can then be used to compare the tag that was +attached to the object with one owned by the addon to ensure that the object +has the right type. + +If the object already has an associated type tag, this API will return +`node_api_invalid_arg`. + +### node_api_check_object_type_tag + + +> Stability: 1 - Experimental + +```c +node_api_status +node_api_check_object_type_tag(node_api_env env, + node_api_value js_object, + const node_api_type_tag* type_tag, + bool* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] js_object`: The JavaScript object whose type tag to examine. +* `[in] type_tag`: The tag with which to compare any tag found on the object. +* `[out] result`: Whether the type tag given matched the type tag on the + object. `false` is also returned if no type tag was found on the object. + +Returns `node_api_ok` if the API succeeded. + +Compares the pointer given as `type_tag` with any that can be found on +`js_object`. If no tag is found on `js_object` or, if a tag is found but it +does not match `type_tag`, then `result` is set to `false`. If a tag is found +and it matches `type_tag`, then `result` is set to `true`. + +### node_api_add_finalizer + + + +```c +node_api_status node_api_add_finalizer(node_api_env env, + node_api_value js_object, + void* native_object, + node_api_finalize finalize_cb, + void* finalize_hint, + node_api_ref* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] js_object`: The JavaScript object to which the native data will be + attached. +* `[in] native_object`: The native data that will be attached to the JavaScript + object. +* `[in] finalize_cb`: Native callback that will be used to free the + native data when the JavaScript object is ready for garbage-collection. + [`node_api_finalize`][] provides more details. +* `[in] finalize_hint`: Optional contextual hint that is passed to the + finalize callback. +* `[out] result`: Optional reference to the JavaScript object. + +Returns `node_api_ok` if the API succeeded. + +Adds a `node_api_finalize` callback which will be called when the JavaScript +object in `js_object` is ready for garbage collection. This API is similar to +`node_api_wrap()` except that: + +* the native data cannot be retrieved later using `node_api_unwrap()`, +* nor can it be removed later using `node_api_remove_wrap()`, and +* the API can be called multiple times with different data items in order to + attach each of them to the JavaScript object, and +* the object manipulated by the API can be used with `node_api_wrap()`. + +*Caution*: The optional returned reference (if obtained) should be deleted via +[`node_api_delete_reference`][] ONLY in response to the finalize callback +invocation. If it is deleted before then, then the finalize callback may never +be invoked. Therefore, when obtaining a reference a finalize callback is also +required in order to enable correct disposal of the reference. + +## Simple asynchronous operations + +Addon modules often need to leverage async helpers from libuv as part of their +implementation. This allows them to schedule work to be executed asynchronously +so that their methods can return in advance of the work being completed. This +allows them to avoid blocking overall execution of the Node.js application. + +The Node.js API provides an ABI-stable interface for these +supporting functions which covers the most common asynchronous use cases. + +The Node.js API defines the `node_api_async_work` structure which is used to +manage asynchronous workers. Instances are created/deleted with +[`node_api_create_async_work`][] and [`node_api_delete_async_work`][]. + +The `execute` and `complete` callbacks are functions that will be +invoked when the executor is ready to execute and when it completes its +task respectively. + +The `execute` function should avoid making any Node.js API calls +that could result in the execution of JavaScript or interaction with +JavaScript objects. Most often, any code that needs to make Node.js API +calls should be made in `complete` callback instead. +Avoid using the `node_api_env` parameter in the execute callback as +it will likely execute JavaScript. + +These functions implement the following interfaces: + +```c +typedef void (*node_api_async_execute_callback)(node_api_env env, + void* data); +typedef void (*node_api_async_complete_callback)(node_api_env env, + node_api_status status, + void* data); +``` + +When these methods are invoked, the `data` parameter passed will be the +addon-provided `void*` data that was passed into the +`node_api_create_async_work` call. + +Once created the async worker can be queued +for execution using the [`node_api_queue_async_work`][] function: + +```c +node_api_status node_api_queue_async_work(node_api_env env, + node_api_async_work work); +``` + +[`node_api_cancel_async_work`][] can be used if the work needs +to be cancelled before the work has started execution. + +After calling [`node_api_cancel_async_work`][], the `complete` callback +will be invoked with a status value of `node_api_cancelled`. +The work should not be deleted before the `complete` +callback invocation, even when it was cancelled. + +### node_api_create_async_work + + +```c +node_api_status +node_api_create_async_work(node_api_env env, + node_api_value async_resource, + node_api_value async_resource_name, + node_api_async_execute_callback execute, + node_api_async_complete_callback complete, + void* data, + node_api_async_work* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] async_resource`: An optional object associated with the async work + that will be passed to possible `async_hooks` [`init` hooks][]. +* `[in] async_resource_name`: Identifier for the kind of resource that is being + provided for diagnostic information exposed by the `async_hooks` API. +* `[in] execute`: The native function which should be called to execute the + logic asynchronously. The given function is called from a worker pool thread + and can execute in parallel with the main event loop thread. +* `[in] complete`: The native function which will be called when the + asynchronous logic is completed or is cancelled. The given function is called + from the main event loop thread. [`node_api_async_complete_callback`][] + provides more details. +* `[in] data`: User-provided data context. This will be passed back into the + execute and complete functions. +* `[out] result`: `node_api_async_work*` which is the handle to the newly + created async work. + +Returns `node_api_ok` if the API succeeded. + +This API allocates a work object that is used to execute logic asynchronously. +It should be freed using [`node_api_delete_async_work`][] once the work is no +longer required. + +`async_resource_name` should be a null-terminated, UTF-8-encoded string. + +The `async_resource_name` identifier is provided by the user and should be +representative of the type of async work being performed. It is also +recommended to apply namespacing to the identifier, e.g. by including the +module name. See the [`async_hooks` documentation][async_hooks `type`] for more +information. + +### node_api_delete_async_work + + +```c +node_api_status node_api_delete_async_work(node_api_env env, + node_api_async_work work); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] work`: The handle returned by the call to `node_api_create_async_work`. + +Returns `node_api_ok` if the API succeeded. + +This API frees a previously allocated work object. + +This API can be called even if there is a pending JavaScript exception. + +### node_api_queue_async_work + + +```c +node_api_status node_api_queue_async_work(node_api_env env, + node_api_async_work work); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] work`: The handle returned by the call to `node_api_create_async_work`. + +Returns `node_api_ok` if the API succeeded. + +This API requests that the previously allocated work be scheduled +for execution. Once it returns successfully, this API must not be called again +with the same `node_api_async_work` item or the result will be undefined. + +### node_api_cancel_async_work + + +```c +node_api_status node_api_cancel_async_work(node_api_env env, + node_api_async_work work); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] work`: The handle returned by the call to `node_api_create_async_work`. + +Returns `node_api_ok` if the API succeeded. + +This API cancels queued work if it has not yet +been started. If it has already started executing, it cannot be +cancelled and `node_api_generic_failure` will be returned. If successful, +the `complete` callback will be invoked with a status value of +`node_api_cancelled`. The work should not be deleted before the `complete` +callback invocation, even if it has been successfully cancelled. + +This API can be called even if there is a pending JavaScript exception. + +## Custom asynchronous operations + +The simple asynchronous work APIs above may not be appropriate for every +scenario. When using any other asynchronous mechanism, the following APIs +are necessary to ensure an asynchronous operation is properly tracked by +the runtime. + +### node_api_async_init + + +```c +node_api_status node_api_async_init(node_api_env env, + node_api_value async_resource, + node_api_value async_resource_name, + node_api_async_context* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] async_resource`: Object associated with the async work + that will be passed to possible `async_hooks` [`init` hooks][] and can be + accessed by [`async_hooks.executionAsyncResource()`][]. +* `[in] async_resource_name`: Identifier for the kind of resource that is being + provided for diagnostic information exposed by the `async_hooks` API. +* `[out] result`: The initialized async context. + +Returns `node_api_ok` if the API succeeded. + +The `async_resource` object needs to be kept alive until +[`node_api_async_destroy`][] to keep `async_hooks` related API acts correctly. +In order to retain ABI compatibility with previous versions, +`node_api_async_context`s are not maintaining the strong reference to the +`async_resource` objects to avoid introducing causing memory leaks. However, if +the `async_resource` is garbage collected by JavaScript engine before the +`node_api_async_context` was destroyed by `node_api_async_destroy`, calling +`node_api_async_context` related APIs like [`node_api_open_callback_scope`][] +and [`node_api_make_callback`][] can cause problems like loss of async context +when using the `AsyncLocalStoage` API. + +In order to retain ABI compatibility with previous versions, passing `NULL` +for `async_resource` does not result in an error. However, this is not +recommended as this will result poor results with `async_hooks` +[`init` hooks][] and `async_hooks.executionAsyncResource()` as the resource is +now required by the underlying `async_hooks` implementation in order to provide +the linkage between async callbacks. + +### node_api_async_destroy + + +```c +node_api_status node_api_async_destroy(node_api_env env, + node_api_async_context async_context); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] async_context`: The async context to be destroyed. + +Returns `node_api_ok` if the API succeeded. + +This API can be called even if there is a pending JavaScript exception. + +### node_api_make_callback + + +```c +NODE_API_EXTERN node_api_status +node_api_make_callback(node_api_env env, + node_api_async_context async_context, + node_api_value recv, + node_api_value func, + size_t argc, + const node_api_value* argv, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] async_context`: Context for the async operation that is + invoking the callback. This should normally be a value previously + obtained from [`node_api_async_init`][]. + In order to retain ABI compatibility with previous versions, passing `NULL` + for `async_context` does not result in an error. However, this results + in incorrect operation of async hooks. Potential issues include loss of + async context when using the `AsyncLocalStorage` API. +* `[in] recv`: The `this` object passed to the called function. +* `[in] func`: `node_api_value` representing the JavaScript function to be + invoked. +* `[in] argc`: The count of elements in the `argv` array. +* `[in] argv`: Array of JavaScript values as `node_api_value` representing the + arguments to the function. +* `[out] result`: `node_api_value` representing the JavaScript object returned. + +Returns `node_api_ok` if the API succeeded. + +This method allows a JavaScript function object to be called from a native +add-on. This API is similar to `node_api_call_function`. However, it is used to +call *from* native code back *into* JavaScript *after* returning from an async +operation (when there is no other script on the stack). It is a fairly simple +wrapper around `node::MakeCallback`. + +Note it is *not* necessary to use `node_api_make_callback` from within a +`node_api_async_complete_callback`; in that situation the callback's async +context has already been set up, so a direct call to `node_api_call_function` +is sufficient and appropriate. Use of the `node_api_make_callback` function +may be required when implementing custom async behavior that does not use +`node_api_create_async_work`. + +Any `process.nextTick`s or Promises scheduled on the microtask queue by +JavaScript during the callback are ran before returning back to C/C++. + +### node_api_open_callback_scope + + +```c +NODE_API_EXTERN node_api_status +node_api_open_callback_scope(node_api_env env, + node_api_value resource_object, + node_api_async_context context, + node_api_callback_scope* result) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] resource_object`: An object associated with the async work + that will be passed to possible `async_hooks` [`init` hooks][]. This + parameter has been deprecated and is ignored at runtime. Use the + `async_resource` parameter in [`node_api_async_init`][] instead. +* `[in] context`: Context for the async operation that is invoking the + callback. + This should be a value previously obtained from [`node_api_async_init`][]. +* `[out] result`: The newly created scope. + +There are cases (for example, resolving promises) where it is +necessary to have the equivalent of the scope associated with a callback +in place when making certain Node.js API calls. If there is no other script on +the stack the [`node_api_open_callback_scope`][] and +[`node_api_close_callback_scope`][] functions can be used to open/close +the required scope. + +### node_api_close_callback_scope + + +```c +NODE_API_EXTERN node_api_status +node_api_close_callback_scope(node_api_env env, node_api_callback_scope scope) +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] scope`: The scope to be closed. + +This API can be called even if there is a pending JavaScript exception. + +## Version management + +### node_api_get_node_version + + +```c +typedef struct { + uint32_t major; + uint32_t minor; + uint32_t patch; + const char* release; +} node_api_node_version; + +node_api_status +node_api_get_node_version(node_api_env env, + const node_api_node_version** version); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] version`: A pointer to version information for Node.js itself. + +Returns `node_api_ok` if the API succeeded. + +This function fills the `version` struct with the major, minor, and patch +version of Node.js that is currently running, and the `release` field with the +value of [`process.release.name`][`process.release`]. + +The returned buffer is statically allocated and does not need to be freed. + +### node_api_get_version + + +```c +node_api_status node_api_get_version(node_api_env env, + uint32_t* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] result`: The highest version of the Node.js API supported. + +Returns `node_api_ok` if the API succeeded. + +This API returns the highest Node.js API version supported by the +Node.js runtime. The Node.js API is planned to be additive such that +newer releases of Node.js may support additional API functions. +In order to allow an addon to use a newer function when running with +versions of Node.js that support it, while providing +fallback behavior when running with Node.js versions that don't +support it: + +* Call `node_api_get_version()` to determine if the API is available. +* If available, dynamically load a pointer to the function using `uv_dlsym()`. +* Use the dynamically loaded pointer to invoke the function. +* If the function is not available, provide an alternate implementation + that does not use the function. + +## Memory management + +### node_api_adjust_external_memory + + +```c +NODE_API_EXTERN node_api_status +node_api_adjust_external_memory(node_api_env env, + int64_t change_in_bytes, + int64_t* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] change_in_bytes`: The change in externally allocated memory that is + kept alive by JavaScript objects. +* `[out] result`: The adjusted value + +Returns `node_api_ok` if the API succeeded. + +This function gives V8 an indication of the amount of externally allocated +memory that is kept alive by JavaScript objects (i.e. a JavaScript object +that points to its own memory allocated by a native module). Registering +externally allocated memory will trigger global garbage collections more +often than it would otherwise. + +## Promises + +The Node.js API provides facilities for creating `Promise` objects as described +in [Section 25.4][] of the ECMA specification. It implements promises as a pair +of objects. When a promise is created by `node_api_create_promise()`, a +"deferred" object is created and returned alongside the `Promise`. The deferred +object is bound to the created `Promise` and is the only means to resolve or +reject the `Promise` using `node_api_resolve_deferred()` or +`node_api_reject_deferred()`. The deferred object that is created by +`node_api_create_promise()` is freed by `node_api_resolve_deferred()` or +`node_api_reject_deferred()`. The `Promise` object may be returned to +JavaScript where it can be used in the usual fashion. + +For example, to create a promise and pass it to an asynchronous worker: + +```c +node_api_deferred deferred; +node_api_value promise; +node_api_status status; + +// Create the promise. +status = node_api_create_promise(env, &deferred, &promise); +if (status != node_api_ok) return NULL; + +// Pass the deferred to a function that performs an asynchronous action. +do_something_asynchronous(deferred); + +// Return the promise to JS +return promise; +``` + +The above function `do_something_asynchronous()` would perform its asynchronous +action and then it would resolve or reject the deferred, thereby concluding the +promise and freeing the deferred: + +```c +node_api_deferred deferred; +node_api_value undefined; +node_api_status status; + +// Create a value with which to conclude the deferred. +status = node_api_get_undefined(env, &undefined); +if (status != node_api_ok) return NULL; + +// Resolve or reject the promise associated with the deferred depending on +// whether the asynchronous action succeeded. +if (asynchronous_action_succeeded) { + status = node_api_resolve_deferred(env, deferred, undefined); +} else { + status = node_api_reject_deferred(env, deferred, undefined); +} +if (status != node_api_ok) return NULL; + +// At this point the deferred has been freed, so we should assign NULL to it. +deferred = NULL; +``` + +### node_api_create_promise + + +```c +node_api_status node_api_create_promise(node_api_env env, + node_api_deferred* deferred, + node_api_value* promise); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] deferred`: A newly created deferred object which can later be passed + to `node_api_resolve_deferred()` or `node_api_reject_deferred()` to resolve + resp. reject the associated promise. +* `[out] promise`: The JavaScript promise associated with the deferred object. + +Returns `node_api_ok` if the API succeeded. + +This API creates a deferred object and a JavaScript promise. + +### node_api_resolve_deferred + + +```c +node_api_status node_api_resolve_deferred(node_api_env env, + node_api_deferred deferred, + node_api_value resolution); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] deferred`: The deferred object whose associated promise to resolve. +* `[in] resolution`: The value with which to resolve the promise. + +This API resolves a JavaScript promise by way of the deferred object +with which it is associated. Thus, it can only be used to resolve JavaScript +promises for which the corresponding deferred object is available. This +effectively means that the promise must have been created using +`node_api_create_promise()` and the deferred object returned from that call +must have been retained in order to be passed to this API. + +The deferred object is freed upon successful completion. + +### node_api_reject_deferred + + +```c +node_api_status node_api_reject_deferred(node_api_env env, + node_api_deferred deferred, + node_api_value rejection); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] deferred`: The deferred object whose associated promise to resolve. +* `[in] rejection`: The value with which to reject the promise. + +This API rejects a JavaScript promise by way of the deferred object +with which it is associated. Thus, it can only be used to reject JavaScript +promises for which the corresponding deferred object is available. This +effectively means that the promise must have been created using +`node_api_create_promise()` and the deferred object returned from that call +must have been retained in order to be passed to this API. + +The deferred object is freed upon successful completion. + +### node_api_is_promise + + +```c +node_api_status node_api_is_promise(node_api_env env, + node_api_value value, + bool* is_promise); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] value`: The value to examine +* `[out] is_promise`: Flag indicating whether `promise` is a native promise + object (that is, a promise object created by the underlying engine). + +## Script execution + +The Node.js API provides an API for executing a string containing JavaScript +using the underlying JavaScript engine. + +### node_api_run_script + + +```c +NODE_API_EXTERN node_api_status node_api_run_script(node_api_env env, + node_api_value script, + node_api_value* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] script`: A JavaScript string containing the script to execute. +* `[out] result`: The value resulting from having executed the script. + +This function executes a string of JavaScript code and returns its result with +the following caveats: + +* Unlike `eval`, this function does not allow the script to access the current + lexical scope, and therefore also does not allow to access the + [module scope][], meaning that pseudo-globals such as `require` will not be + available. +* The script can access the [global scope][]. Function and `var` declarations + in the script will be added to the [`global`][] object. Variable declarations + made using `let` and `const` will be visible globally, but will not be added + to the [`global`][] object. +* The value of `this` is [`global`][] within the script. + +## libuv event loop + +The Node.js API provides a function for getting the current event loop +associated with a specific `node_api_env`. + +### node_api_get_uv_event_loop + + +```c +NODE_API_EXTERN node_api_status +node_api_get_uv_event_loop(node_api_env env, struct uv_loop_s** loop); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] loop`: The current libuv loop instance. + +## Asynchronous thread-safe function calls + +JavaScript functions can normally only be called from a native addon's main +thread. If an addon creates additional threads, then the Node.js API functions +that require a `node_api_env`, `node_api_value`, or `node_api_ref` must not be +called from those threads. + +When an addon has additional threads and JavaScript functions need to be +invoked based on the processing completed by those threads, those threads must +communicate with the addon's main thread so that the main thread can invoke the +JavaScript function on their behalf. The thread-safe function APIs provide an +easy way to do this. + +These APIs provide the type `node_api_threadsafe_function` as well as APIs to +create, destroy, and call objects of this type. +`node_api_create_threadsafe_function()` creates a persistent reference to a +`node_api_value` that holds a JavaScript function which can be called from +multiple threads. The calls happen asynchronously. This means that values with +which the JavaScript callback is to be called will be placed in a queue, and, +for each value in the queue, a call will eventually be made to the JavaScript +function. + +Upon creation of a `node_api_threadsafe_function` a `node_api_finalize` +callback can be provided. This callback will be invoked on the main thread when +the thread-safe function is about to be destroyed. It receives the context and +the finalize data given during construction, and provides an opportunity for +cleaning up after the threads e.g. by calling `uv_thread_join()`. **Aside from +the main loop thread, no threads should be using the thread-safe function after +the finalize callback completes.** + +The `context` given during the call to `node_api_create_threadsafe_function()` +can be retrieved from any thread with a call to +`node_api_get_threadsafe_function_context()`. + +### Calling a thread-safe function + +`node_api_call_threadsafe_function()` can be used for initiating a call into +JavaScript. `node_api_call_threadsafe_function()` accepts a parameter which +controls whether the API behaves blockingly. If set to +`node_api_tsfn_nonblocking`, the API behaves non-blockingly, returning +`node_api_queue_full` if the queue was full, preventing data from being +successfully added to the queue. If set to `node_api_tsfn_blocking`, the API +blocks until space becomes available in the queue. +`node_api_call_threadsafe_function()` never blocks if the thread-safe function +was created with a maximum queue size of 0. + +`node_api_call_threadsafe_function()` should not be called with +`node_api_tsfn_blocking` from a JavaScript thread, because, if the queue is +full, it may cause the JavaScript thread to deadlock. + +The actual call into JavaScript is controlled by the callback given via the +`call_js_cb` parameter. `call_js_cb` is invoked on the main thread once for +each value that was placed into the queue by a successful call to +`node_api_call_threadsafe_function()`. If such a callback is not given, a +default callback will be used, and the resulting JavaScript call will have no +arguments. The `call_js_cb` callback receives the JavaScript function to call +as a `node_api_value` in its parameters, as well as the `void*` context pointer +used when creating the `node_api_threadsafe_function`, and the next data +pointer that was created by one of the secondary threads. The callback can then +use an API such as `node_api_call_function()` to call into JavaScript. + +The callback may also be invoked with `env` and `call_js_cb` both set to `NULL` +to indicate that calls into JavaScript are no longer possible, while items +remain in the queue that may need to be freed. This normally occurs when the +Node.js process exits while there is a thread-safe function still active. + +It is not necessary to call into JavaScript via `node_api_make_callback()` +because the Node.js API runs `call_js_cb` in a context appropriate for +callbacks. + +### Reference counting of thread-safe functions + +Threads can be added to and removed from a `node_api_threadsafe_function` +object during its existence. Thus, in addition to specifying an initial number +of threads upon creation, `node_api_acquire_threadsafe_function` can be called +to indicate that a new thread will start making use of the thread-safe +function. Similarly, `node_api_release_threadsafe_function` can be called to +indicate that an existing thread will stop making use of the thread-safe +function. + +`node_api_threadsafe_function` objects are destroyed when every thread which +uses the object has called `node_api_release_threadsafe_function()` or has +received a return status of `node_api_closing` in response to a call to +`node_api_call_threadsafe_function`. The queue is emptied before the +`node_api_threadsafe_function` is destroyed. +`node_api_release_threadsafe_function()` should be the last API call made in +conjunction with a given `node_api_threadsafe_function`, because after the call +completes, there is no guarantee that the `node_api_threadsafe_function` is +still allocated. For the same reason, do not use a thread-safe function +after receiving a return value of `node_api_closing` in response to a call to +`node_api_call_threadsafe_function`. Data associated with the +`node_api_threadsafe_function` can be freed in its `node_api_finalize` callback +which was passed to `node_api_create_threadsafe_function()`. The parameter +`initial_thread_count` of `node_api_create_threadsafe_function` marks the +initial number of aquisitions of the thread-safe functions, instead of calling +`node_api_acquire_threadsafe_function` multiple times at creation. + +Once the number of threads making use of a `node_api_threadsafe_function` +reaches zero, no further threads can start making use of it by calling +`node_api_acquire_threadsafe_function()`. In fact, all subsequent API calls +associated with it, except `node_api_release_threadsafe_function()`, will +return an error value of `node_api_closing`. + +The thread-safe function can be "aborted" by giving a value of +`node_api_tsfn_abort` to `node_api_release_threadsafe_function()`. This will +cause all subsequent APIs associated with the thread-safe function except +`node_api_release_threadsafe_function()` to return `node_api_closing` even +before its reference count reaches zero. In particular, +`node_api_call_threadsafe_function()` will return `node_api_closing`, thus +informing the threads that it is no longer possible to make asynchronous calls +to the thread-safe function. This can be used as a criterion for terminating +the thread. **Upon receiving a return value of `node_api_closing` from +`node_api_call_threadsafe_function()` a thread must not use the thread-safe +function anymore because it is no longer guaranteed to be allocated.** + +### Deciding whether to keep the process running + +Similarly to libuv handles, thread-safe functions can be "referenced" and +"unreferenced". A "referenced" thread-safe function will cause the event loop +on the thread on which it is created to remain alive until the thread-safe +function is destroyed. In contrast, an "unreferenced" thread-safe function will +not prevent the event loop from exiting. The APIs +`node_api_ref_threadsafe_function` and `node_api_unref_threadsafe_function` +exist for this purpose. + +Neither does `node_api_unref_threadsafe_function` mark the thread-safe +functions as able to be destroyed nor does `node_api_ref_threadsafe_function` +prevent it from being destroyed. + +### node_api_create_threadsafe_function + + + +```c +NODE_API_EXTERN node_api_status +node_api_create_threadsafe_function(node_api_env env, + node_api_value func, + node_api_value async_resource, + node_api_value async_resource_name, + size_t max_queue_size, + size_t initial_thread_count, + void* thread_finalize_data, + node_api_finalize thread_finalize_cb, + void* context, + node_api_threadsafe_function_call_js call_js_cb, + node_api_threadsafe_function* result); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] func`: An optional JavaScript function to call from another thread. It + must be provided if `NULL` is passed to `call_js_cb`. +* `[in] async_resource`: An optional object associated with the async work that + will be passed to possible `async_hooks` [`init` hooks][]. +* `[in] async_resource_name`: A JavaScript string to provide an identifier for + the kind of resource that is being provided for diagnostic information + exposed by the `async_hooks` API. +* `[in] max_queue_size`: Maximum size of the queue. `0` for no limit. +* `[in] initial_thread_count`: The initial number of acquisitions, i.e. the + initial number of threads, including the main thread, which will be making + use of this function. +* `[in] thread_finalize_data`: Optional data to be passed to + `thread_finalize_cb`. +* `[in] thread_finalize_cb`: Optional function to call when the + `node_api_threadsafe_function` is being destroyed. +* `[in] context`: Optional data to attach to the resulting + `node_api_threadsafe_function`. +* `[in] call_js_cb`: Optional callback which calls the JavaScript function in + response to a call on a different thread. This callback will be called on the + main thread. If not given, the JavaScript function will be called with no + parameters and with `undefined` as its `this` value. + [`node_api_threadsafe_function_call_js`][] provides more details. +* `[out] result`: The asynchronous thread-safe JavaScript function. + +### node_api_get_threadsafe_function_context + + + +```c +NODE_API_EXTERN node_api_status +node_api_get_threadsafe_function_context(node_api_threadsafe_function func, + void** result); +``` + +* `[in] func`: The thread-safe function for which to retrieve the context. +* `[out] result`: The location where to store the context. + +This API may be called from any thread which makes use of `func`. + +### node_api_call_threadsafe_function + + + +```c +NODE_API_EXTERN node_api_status +node_api_call_threadsafe_function(node_api_threadsafe_function func, + void* data, + node_api_threadsafe_function_call_mode is_blocking); +``` + +* `[in] func`: The asynchronous thread-safe JavaScript function to invoke. +* `[in] data`: Data to send into JavaScript via the callback `call_js_cb` + provided during the creation of the thread-safe JavaScript function. +* `[in] is_blocking`: Flag whose value can be either `node_api_tsfn_blocking` + to indicate that the call should block if the queue is full or + `node_api_tsfn_nonblocking` to indicate that the call should return + immediately with a status of `node_api_queue_full` whenever the queue is + full. + +This API should not be called with `node_api_tsfn_blocking` from a JavaScript +thread, because, if the queue is full, it may cause the JavaScript thread to +deadlock. + +This API will return `node_api_closing` if +`node_api_release_threadsafe_function()` was called with `abort` set to +`node_api_tsfn_abort` from any thread. The value is only added to the queue if +the API returns `node_api_ok`. + +This API may be called from any thread which makes use of `func`. + +### node_api_acquire_threadsafe_function + + + +```c +NODE_API_EXTERN node_api_status +node_api_acquire_threadsafe_function(node_api_threadsafe_function func); +``` + +* `[in] func`: The asynchronous thread-safe JavaScript function to start making + use of. + +A thread should call this API before passing `func` to any other thread-safe +function APIs to indicate that it will be making use of `func`. This prevents +`func` from being destroyed when all other threads have stopped making use of +it. + +This API may be called from any thread which will start making use of `func`. + +### node_api_release_threadsafe_function + + + +```c +NODE_API_EXTERN node_api_status +node_api_release_threadsafe_function(node_api_threadsafe_function func, + node_api_threadsafe_function_release_mode mode); +``` + +* `[in] func`: The asynchronous thread-safe JavaScript function whose reference + count to decrement. +* `[in] mode`: Flag whose value can be either `node_api_tsfn_release` to + indicate that the current thread will make no further calls to the + thread-safe function, or `node_api_tsfn_abort` to indicate that in addition + to the current thread, no other thread should make any further calls to the + thread-safe function. If set to `node_api_tsfn_abort`, further calls to + `node_api_call_threadsafe_function()` will return `node_api_closing`, and no + further values will be placed in the queue. + +A thread should call this API when it stops making use of `func`. Passing +`func` to any thread-safe APIs after having called this API has undefined +results, as `func` may have been destroyed. + +This API may be called from any thread which will stop making use of `func`. + +### node_api_ref_threadsafe_function + + + +```c +NODE_API_EXTERN node_api_status +node_api_ref_threadsafe_function(node_api_env env, + node_api_threadsafe_function func); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] func`: The thread-safe function to reference. + +This API is used to indicate that the event loop running on the main thread +should not exit until `func` has been destroyed. Similar to [`uv_ref`][] it is +also idempotent. + +Neither does `node_api_unref_threadsafe_function` mark the thread-safe +functions as able to be destroyed nor does `node_api_ref_threadsafe_function` +prevent it from being destroyed. `node_api_acquire_threadsafe_function` and +`node_api_release_threadsafe_function` are available for that purpose. + +This API may only be called from the main thread. + +### node_api_unref_threadsafe_function + + + +```c +NODE_API_EXTERN node_api_status +node_api_unref_threadsafe_function(node_api_env env, + node_api_threadsafe_function func); +``` + +* `[in] env`: The environment that the API is invoked under. +* `[in] func`: The thread-safe function to unreference. + +This API is used to indicate that the event loop running on the main thread +may exit before `func` is destroyed. Similar to [`uv_unref`][] it is also +idempotent. + +This API may only be called from the main thread. + +[ABI Stability]: https://nodejs.org/en/docs/guides/abi-stability/ +[AppVeyor]: https://www.appveyor.com +[C++ Addons]: addons.md +[CMake]: https://cmake.org +[CMake.js]: https://github.com/cmake-js/cmake-js +[ECMAScript Language Specification]: https://tc39.github.io/ecma262/ +[Error handling]: #node_api_error_handling +[GCC]: https://gcc.gnu.org +[GYP]: https://gyp.gsrc.io +[GitHub releases]: https://help.github.com/en/github/administering-a-repository/about-releases +[LLVM]: https://llvm.org +[Native Abstractions for Node.js]: https://github.com/nodejs/nan +[Object lifetime management]: #node_api_object_lifetime_management +[Object wrap]: #node_api_object_wrap +[Section 12.10.4]: https://tc39.github.io/ecma262/#sec-instanceofoperator +[Section 12.5.5]: https://tc39.github.io/ecma262/#sec-typeof-operator +[Section 19.2]: https://tc39.github.io/ecma262/#sec-function-objects +[Section 19.4]: https://tc39.github.io/ecma262/#sec-symbol-objects +[Section 20.3]: https://tc39.github.io/ecma262/#sec-date-objects +[Section 22.1]: https://tc39.github.io/ecma262/#sec-array-objects +[Section 22.1.4.1]: https://tc39.github.io/ecma262/#sec-properties-of-array-instances-length +[Section 22.2]: https://tc39.github.io/ecma262/#sec-typedarray-objects +[Section 24.1]: https://tc39.github.io/ecma262/#sec-arraybuffer-objects +[Section 24.1.1.2]: https://tc39.es/ecma262/#sec-isdetachedbuffer +[Section 24.1.1.3]: https://tc39.es/ecma262/#sec-detacharraybuffer +[Section 24.3]: https://tc39.github.io/ecma262/#sec-dataview-objects +[Section 25.4]: https://tc39.github.io/ecma262/#sec-promise-objects +[Section 6]: https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values +[Section 6.1]: https://tc39.github.io/ecma262/#sec-ecmascript-language-types +[Section 6.1.4]: https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type +[Section 6.1.6]: https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type +[Section 6.1.7]: https://tc39.github.io/ecma262/#sec-object-type +[Section 6.1.7.1]: https://tc39.github.io/ecma262/#table-2 +[Section 7]: https://tc39.github.io/ecma262/#sec-abstract-operations +[Section 7.1.13]: https://tc39.github.io/ecma262/#sec-toobject +[Section 7.1.2]: https://tc39.github.io/ecma262/#sec-toboolean +[Section 7.1.3]: https://tc39.github.io/ecma262/#sec-tonumber +[Section 7.2.14]: https://tc39.github.io/ecma262/#sec-strict-equality-comparison +[Section 7.2.2]: https://tc39.github.io/ecma262/#sec-isarray +[Section 8.7]: https://tc39.es/ecma262/#sec-agents +[Section 9.1.6]: https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-defineownproperty-p-desc +[Travis CI]: https://travis-ci.org +[Visual Studio]: https://visualstudio.microsoft.com +[Working with JavaScript properties]: #node_api_working_with_javascript_properties +[Xcode]: https://developer.apple.com/xcode/ +[`Number.MAX_SAFE_INTEGER`]: https://tc39.github.io/ecma262/#sec-number.max_safe_integer +[`Number.MIN_SAFE_INTEGER`]: https://tc39.github.io/ecma262/#sec-number.min_safe_integer +[`Worker`]: worker_threads.md#worker_threads_class_worker +[`async_hooks.executionAsyncResource()`]: async_hooks.md#async_hooks_async_hooks_executionasyncresource +[`global`]: globals.md#globals_global +[`init` hooks]: async_hooks.md#async_hooks_init_asyncid_type_triggerasyncid_resource +[`node_api_add_async_cleanup_hook`]: #node_api_node_api_add_async_cleanup_hook +[`node_api_add_env_cleanup_hook`]: #node_api_node_api_add_env_cleanup_hook +[`node_api_add_finalizer`]: #node_api_node_api_add_finalizer +[`node_api_async_cleanup_hook`]: #node_api_node_api_async_cleanup_hook +[`node_api_async_complete_callback`]: #node_api_node_api_async_complete_callback +[`node_api_async_destroy`]: #node_api_node_api_async_destroy +[`node_api_async_init`]: #node_api_node_api_async_init +[`node_api_callback`]: #node_api_node_api_callback +[`node_api_cancel_async_work`]: #node_api_node_api_cancel_async_work +[`node_api_close_callback_scope`]: #node_api_node_api_close_callback_scope +[`node_api_close_escapable_handle_scope`]: #node_api_node_api_close_escapable_handle_scope +[`node_api_close_handle_scope`]: #node_api_node_api_close_handle_scope +[`node_api_create_async_work`]: #node_api_node_api_create_async_work +[`node_api_create_error`]: #node_api_node_api_create_error +[`node_api_create_external_arraybuffer`]: #node_api_node_api_create_external_arraybuffer +[`node_api_create_range_error`]: #node_api_node_api_create_range_error +[`node_api_create_reference`]: #node_api_node_api_create_reference +[`node_api_create_type_error`]: #node_api_node_api_create_type_error +[`node_api_define_class`]: #node_api_node_api_define_class +[`node_api_delete_async_work`]: #node_api_node_api_delete_async_work +[`node_api_delete_reference`]: #node_api_node_api_delete_reference +[`node_api_escape_handle`]: #node_api_node_api_escape_handle +[`node_api_finalize`]: #node_api_node_api_finalize +[`node_api_get_and_clear_last_exception`]: #node_api_node_api_get_and_clear_last_exception +[`node_api_get_array_length`]: #node_api_node_api_get_array_length +[`node_api_get_element`]: #node_api_node_api_get_element +[`node_api_get_last_error_info`]: #node_api_node_api_get_last_error_info +[`node_api_get_property`]: #node_api_node_api_get_property +[`node_api_get_reference_value`]: #node_api_node_api_get_reference_value +[`node_api_get_value_external`]: #node_api_node_api_get_value_external +[`node_api_has_property`]: #node_api_node_api_has_property +[`node_api_instanceof`]: #node_api_node_api_instanceof +[`node_api_is_error`]: #node_api_node_api_is_error +[`node_api_is_exception_pending`]: #node_api_node_api_is_exception_pending +[`node_api_make_callback`]: #node_api_node_api_make_callback +[`node_api_open_callback_scope`]: #node_api_node_api_open_callback_scope +[`node_api_open_escapable_handle_scope`]: #node_api_node_api_open_escapable_handle_scope +[`node_api_open_handle_scope`]: #node_api_node_api_open_handle_scope +[`node_api_property_attributes`]: #node_api_node_api_property_attributes +[`node_api_property_descriptor`]: #node_api_node_api_property_descriptor +[`node_api_queue_async_work`]: #node_api_node_api_queue_async_work +[`node_api_reference_ref`]: #node_api_node_api_reference_ref +[`node_api_reference_unref`]: #node_api_node_api_reference_unref +[`node_api_remove_async_cleanup_hook`]: #node_api_node_api_remove_async_cleanup_hook +[`node_api_remove_env_cleanup_hook`]: #node_api_node_api_remove_env_cleanup_hook +[`node_api_set_instance_data`]: #node_api_node_api_set_instance_data +[`node_api_set_property`]: #node_api_node_api_set_property +[`node_api_threadsafe_function_call_js`]: #node_api_node_api_threadsafe_function_call_js +[`node_api_throw_error`]: #node_api_node_api_throw_error +[`node_api_throw_range_error`]: #node_api_node_api_throw_range_error +[`node_api_throw_type_error`]: #node_api_node_api_throw_type_error +[`node_api_throw`]: #node_api_node_api_throw +[`node_api_unwrap`]: #node_api_node_api_unwrap +[`node_api_wrap`]: #node_api_node_api_wrap +[`node-addon-api`]: https://github.com/nodejs/node-addon-api +[`node_api.h`]: https://github.com/nodejs/node/blob/master/src/node_api.h +[`process.release`]: process.md#process_process_release +[`uv_ref`]: https://docs.libuv.org/en/v1.x/handle.html#c.uv_ref +[`uv_unref`]: https://docs.libuv.org/en/v1.x/handle.html#c.uv_unref +[async_hooks `type`]: async_hooks.md#async_hooks_type +[context-aware addons]: addons.md#addons_context_aware_addons +[docs]: https://github.com/nodejs/node-addon-api#api-documentation +[global scope]: globals.md +[module scope]: modules.md#modules_the_module_scope +[node-gyp]: https://github.com/nodejs/node-gyp +[node-pre-gyp]: https://github.com/mapbox/node-pre-gyp +[prebuild]: https://github.com/prebuild/prebuild +[prebuildify]: https://github.com/prebuild/prebuildify +[worker threads]: https://nodejs.org/api/worker_threads.html diff --git a/doc/api/process.md b/doc/api/process.md index 773686354efd8a..dbdf98181a3ced 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -786,7 +786,7 @@ An example of the possible output looks like: variables: { host_arch: 'x64', - napi_build_version: 5, + node_api_build_version: 5, node_install_npm: 'true', node_prefix: '', node_shared_cares: 'false', diff --git a/doc/api/util.md b/doc/api/util.md index d6be620b42c56d..0cb541332b0b25 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -1519,31 +1519,31 @@ addons. In JavaScript, they are [frozen][`Object.freeze()`] objects with a ```c #include #include -napi_value result; -static napi_value MyNapi(napi_env env, napi_callback_info info) { +node_api_value result; +static node_api_value MyNapi(node_api_env env, node_api_callback_info info) { int* raw = (int*) malloc(1024); - napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); - if (status != napi_ok) { - napi_throw_error(env, NULL, "napi_create_external failed"); + node_api_status status = node_api_create_external(env, (void*) raw, NULL, NULL, &result); + if (status != node_api_ok) { + node_api_throw_error(env, NULL, "node_api_create_external failed"); return NULL; } return result; } ... -DECLARE_NAPI_PROPERTY("myNapi", MyNapi) +DECLARE_NODE_API_PROPERTY("myNapi", MyNapi) ... ``` ```js -const native = require('napi_addon.node'); +const native = require('node_api_addon.node'); const data = native.myNapi(); util.types.isExternal(data); // returns true util.types.isExternal(0); // returns false util.types.isExternal(new String('foo')); // returns false ``` -For further information on `napi_create_external`, refer to -[`napi_create_external()`][]. +For further information on `node_api_create_external`, refer to +[`node_api_create_external()`][]. ### `util.types.isFloat32Array(value)`