diff --git a/.cto-toolkit/learning/patterns.jsonl b/.cto-toolkit/learning/patterns.jsonl new file mode 100644 index 0000000..cef2d69 --- /dev/null +++ b/.cto-toolkit/learning/patterns.jsonl @@ -0,0 +1,36 @@ +{ + "session_id": "1794959463-1188", + "timestamp": "2026-11-17T23:51:03Z", + "files_modified": 208, + "languages": "javascript,python", + "tests_touched": false, + "security_relevant": true, + "project_root": "/c/Users/nicol/Desktop/QUICKJS-NAPI/quickjs-napi" +} +{ + "session_id": "1794961659-432", + "timestamp": "2026-11-18T00:27:39Z", + "files_modified": 5, + "languages": "python", + "tests_touched": false, + "security_relevant": false, + "project_root": "/c/Users/nicol/Desktop/QUICKJS-NAPI/quickjs-napi" +} +{ + "session_id": "1794961677-237", + "timestamp": "2026-11-18T00:27:57Z", + "files_modified": 5, + "languages": "python", + "tests_touched": false, + "security_relevant": false, + "project_root": "/c/Users/nicol/Desktop/QUICKJS-NAPI/quickjs-napi" +} +{ + "session_id": "1794961714-1861", + "timestamp": "2026-11-18T00:28:34Z", + "files_modified": 5, + "languages": "python", + "tests_touched": false, + "security_relevant": false, + "project_root": "/c/Users/nicol/Desktop/QUICKJS-NAPI/quickjs-napi" +} diff --git a/CMakeLists.txt b/CMakeLists.txt index ce3b4d6..67934d8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,6 +10,8 @@ option(QJSNAPI_SANITIZE option(QJSNAPI_TSAN "Build everything (QuickJS and libuv included) with ThreadSanitizer" OFF) option(QJSNAPI_BUILD_TESTS "Build the test addons and the test suite" ON) +option(QJSNAPI_NODE_ADDON_API_TESTS + "Build and run the node-addon-api test suite (C++, 8 bindings)" ON) set(QJSNAPI_QUICKJS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../quickjs-build" @@ -228,7 +230,7 @@ else() endif() set(CMAKE_C_LINK_LIBRARY_USING_QJSNAPI_WHOLE_ARCHIVE_SUPPORTED TRUE) -add_executable(quickjs-napi host/main.c +add_executable(quickjs-napi host/main.c host/spawn.c "${QJSNAPI_GENERATED_DIR}/bootstrap_js.h") target_include_directories(quickjs-napi PRIVATE "${QJSNAPI_GENERATED_DIR}") set_target_properties(quickjs-napi PROPERTIES C_STANDARD 17 ENABLE_EXPORTS ON) @@ -423,6 +425,10 @@ if(QJSNAPI_BUILD_TESTS) include("${QJSNAPI_NODE_TESTS_SRC}/js-native-api/tests.cmake") include("${QJSNAPI_NODE_TESTS_SRC}/node-api/tests.cmake") + if(QJSNAPI_NODE_ADDON_API_TESTS) + include(cmake/node_addon_api_tests.cmake) + endif() + add_test(NAME js_values COMMAND quickjs-napi "${CMAKE_CURRENT_SOURCE_DIR}/test/js/test_values.js" @@ -435,6 +441,10 @@ if(QJSNAPI_BUILD_TESTS) COMMAND quickjs-napi "${CMAKE_CURRENT_SOURCE_DIR}/test/js/test_node_api.js" "${QJSNAPI_ADDON_DIR}") + # Host features of the executable (child_process, -e, -r, NODE_OPTIONS). + add_test(NAME js_host + COMMAND quickjs-napi "${CMAKE_CURRENT_SOURCE_DIR}/test/js/test_host.js") + set_tests_properties(js_host PROPERTIES PASS_REGULAR_EXPRESSION "^ok") add_executable(test_embed test/unit/test_embed.c) set_target_properties(test_embed PROPERTIES C_STANDARD 17) @@ -453,6 +463,12 @@ if(QJSNAPI_BUILD_TESTS) "${CMAKE_CURRENT_SOURCE_DIR}/test/js/test_${_t}.js" "${QJSNAPI_ADDON_DIR}") endforeach() + add_test(NAME node_parity_host + COMMAND "${QJSNAPI_NODE}" + "${CMAKE_CURRENT_SOURCE_DIR}/test/js/test_host.js") + # The NODE_OPTIONS of the environment must not reach Node.js itself. + set_tests_properties(node_parity_host PROPERTIES + PASS_REGULAR_EXPRESSION "^ok" ENVIRONMENT "NODE_OPTIONS=") endif() find_package(Python3 COMPONENTS Interpreter) diff --git a/README.md b/README.md index 84610ac..7865e0f 100644 --- a/README.md +++ b/README.md @@ -6,17 +6,21 @@ Node-API implementation for QuickJS (2026-06-04, from `../quickjs-build`). Addons built for Node.js (node-gyp, node-addon-api, napi-rs) are loaded unchanged: they resolve `napi_*` from the `quickjs-napi` executable. -Status: milestone **M5** (M1 values, strings, objects, properties, +Status: milestone **M6** in progress (M1 values, strings, objects, properties, functions, classes, errors; M2 references, externals, wrapping, finalizers, type tags, instance data, `napi_run_script`; M3 ArrayBuffer, TypedArray, DataView, BigInt, Date, Promise; M4 the synchronous `node_api.h`: Buffer, async context, `napi_make_callback`, callback scopes, `napi_fatal_exception`; M5 the libuv event loop: async work, thread-safe -functions, async cleanup hooks, `napi_get_uv_event_loop`). All 155 -Node-API functions are implemented and pass 30 tests of the Node.js -`js-native-api` suite and 19 of its `node-api` suite (see -`test/node/README.md`). `NAPI_EXPERIMENTAL` APIs are not provided. See -`PIANO-IMPLEMENTAZIONE.md` in the project for the plan. +functions, async cleanup hooks, `napi_get_uv_event_loop`; M6 real-world +conformance). All 155 Node-API functions are implemented and pass 30 tests +of the Node.js `js-native-api` suite, 19 of its `node-api` suite (see +`test/node/README.md`) and 78 of the 83 test modules of the node-addon-api +8.9.2 suite (the others need `worker_threads`, `npm` or test the npm +package itself), in its four binding variants (C++ exceptions, no exceptions, +`Maybe`, custom namespace; see `test/node-addon-api/harness/README.md`). +`NAPI_EXPERIMENTAL` APIs are not provided. See `PIANO-IMPLEMENTAZIONE.md` +in the project for the plan. ## Lifetime model @@ -24,6 +28,20 @@ Node-API functions are implemented and pass 30 tests of the Node.js count 0 an object, function or local symbol is held through a JS `WeakRef` (QuickJS reports the target dead as soon as its refcount drops to zero), other values are released. +- V8 keeps the target of a weak handle until a garbage collection; QuickJS + frees an object when its refcount drops to zero, so an object created by + a native call and only referenced weakly would die when the call returns + (node-addon-api relies on the V8 behaviour: `Napi::Weak(Object::New(env))` + used later in the same synchronous code). When a reference becomes weak its + target is therefore also put on a list of *kept objects*, like the + `[[KeptAlive]]` list of ECMAScript WeakRefs, cleared at the end of every + macrotask (the library's checkpoint), by `gc()` and at teardown; + embedders call `qjsnapi_host_clear_kept_objects` at the end of their own + macrotasks. +- `napi_define_class`: as with V8's prototype template, a later instance + property with the same key replaces an earlier one, whatever its + attributes (static properties are defined like `napi_define_properties`, + where such a redefinition fails, in Node.js too). - QuickJS has no weak callback in its C API. Each target of a reference, a wrap or a type tag gets a *holder* object in a `WeakMap` keyed by the target; QuickJS drops the entry of a dead key during `JS_RunGC`, and the @@ -123,6 +141,11 @@ Node-API functions are implemented and pass 30 tests of the Node.js thread-safe function and async cleanup hook is done, then the reference finalizers with JavaScript disabled. Async work items and user references the addon never deleted are freed with the env (Node.js leaks them). +- `process.exit()` and a fatal exception end the executable like Node.js + (`DefaultProcessExitHandlerInternal`): the `exit` event is emitted, the + thread pool is shut down, and the process exits without tearing the + environment down (no cleanup hook or finalizer runs, work in flight is not + waited for). A normal end of the script tears everything down as above. - `napi_fatal_error` prints `FATAL ERROR: ` and aborts (`_exit(134)` on Windows, as Node.js). @@ -178,6 +201,7 @@ Options: | `QJSNAPI_SANITIZE` | OFF | ASan + UBSan for everything, QuickJS included | | `QJSNAPI_TSAN` | OFF | ThreadSanitizer for everything (exclusive with `QJSNAPI_SANITIZE`) | | `QJSNAPI_BUILD_TESTS` | ON | test addons and CTest suite | +| `QJSNAPI_NODE_ADDON_API_TESTS` | ON | the node-addon-api suite (8 C++ bindings, about 2 minutes of build) | `include/quickjs.h` and `include/quickjs-libc.h` must be identical to the ones in `quickjs-build`: configuration fails otherwise (JSValue ABI). @@ -216,12 +240,18 @@ resolves the `napi_*` imports from the running executable. ```sh quickjs-napi [options] script.js [args...] +quickjs-napi [options] -e [args...] ``` -Options: `--force-node-api-uncaught-exceptions-policy[=true|false]` and +Options: `-e`/`--eval ` (run the code instead of a script, +`process.argv` is `[execPath, args...]`), `-r`/`--require ` +(loaded before the script, repeatable), +`--force-node-api-uncaught-exceptions-policy[=true|false]` and `--no-force-node-api-uncaught-exceptions-policy` (see above), `--expose-gc` (accepted and ignored: `gc()` is always defined). An unknown option exits -with code 9, as Node.js. +with code 9, as Node.js. `NODE_OPTIONS` is read first, with the same +options separated by spaces; the options only Node.js knows are ignored +there (the variable is shared with Node.js). The script runs as a CommonJS module (`host/bootstrap.js`): `require` loads `.js`, `.json` and `.node` files with Node.js resolution rules @@ -233,7 +263,10 @@ loads `.js`, `.json` and `.node` files with Node.js resolution rules modules `timers` and `timers/promises`), `Buffer` (also `require('buffer')`), minimal builtin modules `util` (`promisify`, `types`), `url` (`pathToFileURL`, `fileURLToPath`) and `vm` (`runInNewContext`, a new realm -of the same runtime), `process.version`, and the quickjs-libc helpers +of the same runtime), `child_process` (`spawnSync` and `spawn` without a +shell; stdio `pipe`, `inherit` or `ignore`, an asynchronous child's stdin is +never a pipe), `events` (a minimal `EventEmitter`), `process.env` (the real +environment), `process.version`, and the quickjs-libc helpers (`console.log`, `print`, `scriptArgs`). As in Node.js, an exception no frame catches (a timer, a microtask, a Node-API finalizer) goes to `process.on('uncaughtException')` or ends the process with exit code 1, and @@ -248,7 +281,8 @@ The embedder runs the host's libuv loop (`uv_run`), which also runs the queued finalizers; it installs `qjsnapi_host_set_uncaught_handler` for exceptions thrown by native callbacks and may install `qjsnapi_host_set_checkpoint` to drain microtasks, rejections and its own -timers after each one. +timers after each one, and calls `qjsnapi_host_clear_kept_objects` at the +end of each macrotask it runs itself and before an explicit GC. ## Layout @@ -271,11 +305,14 @@ timers after each one. | `src/tsfn.c` | thread-safe functions | | `src/loader.c` | `.node` loading: `napi_register_module_v1`, API version, legacy `napi_module_register` | | `src/stubs_generated.c` | generated by `tools/gen_stubs.py`, do not edit (empty now: every function is implemented) | -| `host/main.c`, `host/bootstrap.js` | the `quickjs-napi` executable: libuv event loop (timers, immediates, `beforeExit`), CommonJS loader, `process` (embedded at build time by `cmake/embed.cmake`), `buffer`, `util`, `url`, `vm` | +| `host/main.c`, `host/bootstrap.js` | the `quickjs-napi` executable: options, libuv event loop (timers, immediates, `beforeExit`), CommonJS loader, `process` (embedded at build time by `cmake/embed.cmake`), `buffer`, `util`, `url`, `vm`, `child_process`, `events` | +| `host/spawn.c` | child processes (`spawnSync` on a private loop, `spawn` on the main one) | | `test/addons`, `test/js` | our test addons; the JS tests also run under Node.js as reference | | `test/node` | Node.js conformance tests (vendored, see its README) | +| `test/node-addon-api` | node-addon-api headers and test suite (vendored by `tools/sync_node_addon_api.py`); `harness/` is ours (see its README) | +| `cmake/node_addon_api_tests.cmake` | builds the 8 node-addon-api test bindings, one CTest per test module | | `test/unit` | C embedding test (teardown order, scopes, error state, finalizer queue) | -| `test/lsan.supp` | LeakSanitizer suppressions for leaks the Node.js tests make by design | +| `test/lsan.supp` | LeakSanitizer suppressions for leaks the Node.js and node-addon-api tests make by design | | `cmake/expect_abort.cmake` | runs a Node.js test that must abort (`napi_fatal_error`) and checks its output | After implementing a function, run `python3 tools/gen_stubs.py` to drop its diff --git a/cmake/node_addon_api_tests.cmake b/cmake/node_addon_api_tests.cmake new file mode 100644 index 0000000..974cbec --- /dev/null +++ b/cmake/node_addon_api_tests.cmake @@ -0,0 +1,125 @@ +# node-addon-api test suite (vendored by tools/sync_node_addon_api.py), +# included from CMakeLists.txt when QJSNAPI_NODE_ADDON_API_TESTS is ON. +# +# Layout in the build tree, as in a node-addon-api checkout: +# node-addon-api-tests/index.js harness/index.js (package stub) +# node-addon-api-tests/test/... the vendored test/ directory +# node-addon-api-tests/test/common/ harness/common (quickjs-napi) +# node-addon-api-tests/test/run.js harness/run.js (one module) +# node-addon-api-tests/test/preload.js harness/preload.js (--require) +# node-addon-api-tests/test/qn_assert.js test/node/common/assert.js +# node-addon-api-tests/test/build/Release/.node +# Every module is a CTest named naa/: +# NODE_OPTIONS=--require=test/preload.js \ +# quickjs-napi --expose-gc test/run.js +# NODE_OPTIONS (not -r) so that the child processes the tests start load +# the preload as well. + +set(QJSNAPI_NAA_SRC "${CMAKE_CURRENT_SOURCE_DIR}/test/node-addon-api") +set(QJSNAPI_NAA_BIN "${CMAKE_CURRENT_BINARY_DIR}/node-addon-api-tests") + +# The JavaScript side (configure_file re-copies a changed source). +file(GLOB_RECURSE _naa_js RELATIVE "${QJSNAPI_NAA_SRC}/test" + "${QJSNAPI_NAA_SRC}/test/*.js") +foreach(_f ${_naa_js}) + configure_file("${QJSNAPI_NAA_SRC}/test/${_f}" "${QJSNAPI_NAA_BIN}/test/${_f}" + COPYONLY) +endforeach() +configure_file("${QJSNAPI_NAA_SRC}/harness/common/index.js" + "${QJSNAPI_NAA_BIN}/test/common/index.js" COPYONLY) +configure_file("${QJSNAPI_NAA_SRC}/harness/run.js" + "${QJSNAPI_NAA_BIN}/test/run.js" COPYONLY) +configure_file("${QJSNAPI_NAA_SRC}/harness/preload.js" + "${QJSNAPI_NAA_BIN}/test/preload.js" COPYONLY) +configure_file("${QJSNAPI_NAA_SRC}/harness/index.js" + "${QJSNAPI_NAA_BIN}/index.js" COPYONLY) +configure_file("${CMAKE_CURRENT_SOURCE_DIR}/test/node/common/assert.js" + "${QJSNAPI_NAA_BIN}/test/qn_assert.js" COPYONLY) + +# One binding of test/binding.gyp. The defines are those of +# node_addon_api.gyp (except.gypi / noexcept.gypi) and common.gypi +# (NAPI_VERSION = process.versions.napi of Node.js 22: 10). +function(qjsnapi_naa_binding name exceptions) + cmake_parse_arguments(T "" "" "SOURCES;DEFINES" ${ARGN}) + list(TRANSFORM T_SOURCES PREPEND "${QJSNAPI_NAA_SRC}/test/") + add_library(naa_${name} MODULE ${T_SOURCES}) + set_target_properties( + naa_${name} + PROPERTIES OUTPUT_NAME "${name}" + PREFIX "" + SUFFIX ".node" + CXX_STANDARD 17 + CXX_VISIBILITY_PRESET hidden + LIBRARY_OUTPUT_DIRECTORY "${QJSNAPI_NAA_BIN}/test/build/Release" + RUNTIME_OUTPUT_DIRECTORY "${QJSNAPI_NAA_BIN}/test/build/Release") + target_include_directories(naa_${name} PRIVATE include "${QJSNAPI_NAA_SRC}" + "${QJSNAPI_NAA_SRC}/test/common") + target_compile_definitions( + naa_${name} PRIVATE BUILDING_NODE_EXTENSION NAPI_VERSION=10 + NODE_GYP_MODULE_NAME=${name} ${T_DEFINES}) + if(exceptions) + target_compile_definitions(naa_${name} PRIVATE NAPI_CPP_EXCEPTIONS) + target_compile_options(naa_${name} PRIVATE -fexceptions) + else() + target_compile_definitions(naa_${name} + PRIVATE NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS) + target_compile_options(naa_${name} PRIVATE -fno-exceptions) + endif() + # As node-gyp in Release: assertions stay. + target_compile_options(naa_${name} PRIVATE -UNDEBUG) + # napi-inl.h reads DataView values through misaligned pointers + # (DataView::ReadData): undefined behaviour of node-addon-api itself, which + # UBSan (QJSNAPI_SANITIZE, zig's Debug default) would report. + target_compile_options(naa_${name} PRIVATE -fno-sanitize=alignment) + if(WIN32) + target_link_libraries(naa_${name} PRIVATE quickjs-napi) + elseif(APPLE) + target_link_options(naa_${name} PRIVATE -undefined dynamic_lookup) + endif() + add_dependencies(quickjs-napi-tests naa_${name}) +endfunction() + +# One test module (called by the generated tests.cmake). +function(qjsnapi_naa_test module) + add_test(NAME naa/${module} + COMMAND quickjs-napi --expose-gc "${QJSNAPI_NAA_BIN}/test/run.js" + "${module}" + WORKING_DIRECTORY "${QJSNAPI_NAA_BIN}/test") + set_tests_properties( + naa/${module} + PROPERTIES ENVIRONMENT + "NODE_OPTIONS=--require=${QJSNAPI_NAA_BIN}/test/preload.js") +endfunction() + +include("${QJSNAPI_NAA_SRC}/tests.cmake") + +# Racy upstream: SignalAfterProgressTestWorker calls Send() then Signal() +# from its thread; if the loop thread runs OnWorkProgress between the two, +# the second call sees no data (count 0, "expect 1 count of data"), under +# Node.js as well. The window is a preemption of the worker thread between +# two calls, so the test runs alone to keep the machine unloaded. +if(TEST naa/async_progress_worker) + set_tests_properties(naa/async_progress_worker PROPERTIES RUN_SERIAL ON) +endif() + +qjsnapi_naa_binding(binding ON SOURCES ${QJSNAPI_NAA_BUILD_SOURCES} + DEFINES NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS) +qjsnapi_naa_binding(binding_noexcept OFF SOURCES ${QJSNAPI_NAA_BUILD_SOURCES}) +qjsnapi_naa_binding(binding_noexcept_maybe OFF + SOURCES ${QJSNAPI_NAA_BUILD_SOURCES} + DEFINES NODE_ADDON_API_ENABLE_MAYBE) +qjsnapi_naa_binding(binding_custom_namespace OFF + SOURCES ${QJSNAPI_NAA_BUILD_SOURCES} + DEFINES NAPI_CPP_CUSTOM_NAMESPACE=cstm) +qjsnapi_naa_binding(binding_swallowexcept ON + SOURCES ${QJSNAPI_NAA_SWALLOWEXCEPT_SOURCES} + DEFINES NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS) +qjsnapi_naa_binding(binding_swallowexcept_noexcept OFF + SOURCES ${QJSNAPI_NAA_SWALLOWEXCEPT_SOURCES} + DEFINES NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS) +qjsnapi_naa_binding(binding_except_all ON + SOURCES ${QJSNAPI_NAA_EXCEPT_ALL_SOURCES} + DEFINES NODE_ADDON_API_CPP_EXCEPTIONS_ALL) +qjsnapi_naa_binding(binding_type_check OFF + SOURCES ${QJSNAPI_NAA_TYPE_CHECK_SOURCES} + DEFINES NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS) diff --git a/host/bootstrap.js b/host/bootstrap.js index f963175..28742c7 100644 --- a/host/bootstrap.js +++ b/host/bootstrap.js @@ -214,7 +214,15 @@ const process = { argv: natives.argv, - env: {}, + env: (() => { + const env = {}; + for (const kv of natives.environ) { + // "=C:=C:\\dir" entries (Windows drive cwds) have an empty name. + const i = kv.indexOf('=', 1); + if (i > 0) env[kv.slice(0, i)] = kv.slice(i + 1); + } + return env; + })(), platform: natives.platform, execPath: natives.execPath, // Same as napi_get_node_version: the Node.js release whose Node-API @@ -602,7 +610,213 @@ }; builtins.module.builtinModules.push('buffer', 'util', 'url', 'vm'); + // ------------------------------------------------------- child_process + // spawnSync and spawn (no shell: exec/execSync are not provided), on + // natives.spawnSync / natives.spawn (host/spawn.c). stdio: 'pipe', + // 'inherit', 'ignore' (a string or an array of three); an asynchronous + // child's stdin is never a pipe. + class Emitter { + constructor() { this._events = Object.create(null); } + on(event, fn) { + (this._events[event] || (this._events[event] = [])).push(fn); + return this; + } + once(event, fn) { + const wrapped = (...args) => { + this.removeListener(event, wrapped); + fn.apply(this, args); + }; + wrapped.listener = fn; + return this.on(event, wrapped); + } + removeListener(event, fn) { + const l = this._events[event]; + if (l) { + const i = l.findIndex((f) => f === fn || f.listener === fn); + if (i >= 0) l.splice(i, 1); + } + return this; + } + emit(event, ...args) { + const l = this._events[event]; + if (!l || l.length === 0) { + if (event === 'error') throw args[0]; + return false; + } + for (const fn of l.slice()) fn.apply(this, args); + return true; + } + } + Emitter.prototype.addListener = Emitter.prototype.on; + Emitter.prototype.off = Emitter.prototype.removeListener; + + function stdioModes(stdio) { + if (stdio === undefined) return ['pipe', 'pipe', 'pipe']; + if (typeof stdio === 'string') return [stdio, stdio, stdio]; + return [0, 1, 2].map((i) => { + const m = stdio[i]; + return m === undefined || m === null ? 'pipe' : m; + }); + } + + function envList(env) { + if (env === undefined || env === null) return undefined; + return Object.keys(env).filter((k) => env[k] !== undefined) + .map((k) => `${k}=${env[k]}`); + } + + function spawnArgs(file, args, options) { + if (typeof file !== 'string') { + const e = new TypeError('The "file" argument must be of type string'); + e.code = 'ERR_INVALID_ARG_TYPE'; + throw e; + } + if (!Array.isArray(args)) { + options = args; + args = []; + } + options = options || {}; + return { + args: args.map(String), + options, + native: { + env: envList(options.env), + cwd: options.cwd, + stdio: stdioModes(options.stdio), + }, + }; + } + + function spawnError(code, syscall, file, args) { + const e = new Error(`${syscall} ${file} ${code}`); + e.code = code; + e.errno = code; + e.syscall = `${syscall} ${file}`; + e.path = file; + e.spawnargs = args; + return e; + } + + function spawnSync(file, args, options) { + const a = spawnArgs(file, args, options); + const o = a.options; + const input = o.input; + if (input !== undefined) { + a.native.input = typeof input === 'string' + ? natives.Buffer.from(input, o.encoding || 'utf8').buffer + : ArrayBuffer.isView(input) + ? input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength) + : input; + } + if (o.timeout) a.native.timeout = o.timeout; + if (o.killSignal !== undefined) a.native.killSignal = o.killSignal; + const r = natives.spawnSync(file, a.args, a.native); + const conv = (ab) => { + if (ab === null) return null; + const b = natives.Buffer.from(ab); + return o.encoding && o.encoding !== 'buffer' ? b.toString(o.encoding) : b; + }; + const stdout = conv(r.stdout); + const stderr = conv(r.stderr); + const result = { + pid: r.pid, + output: [null, stdout, stderr], + stdout, + stderr, + status: r.status, + signal: r.signal, + }; + if (r.error) result.error = spawnError(r.error, 'spawnSync', file, a.args); + return result; + } + + class Readable extends Emitter { + constructor() { + super(); + this._encoding = null; + } + setEncoding(enc) { + this._encoding = enc; + return this; + } + _push(ab) { + const b = natives.Buffer.from(ab); + this.emit('data', this._encoding ? b.toString(this._encoding) : b); + } + } + + class ChildProcess extends Emitter { + constructor() { + super(); + this.pid = undefined; + this.exitCode = null; + this.signalCode = null; + this.killed = false; + this.stdin = null; + this.stdout = null; + this.stderr = null; + this._handle = null; + } + kill(signal) { + if (!this._handle) return false; + const ok = this._handle.kill(signal === undefined ? 'SIGTERM' : signal); + if (ok) this.killed = true; + return ok; + } + } + + function spawn(file, args, options) { + const a = spawnArgs(file, args, options); + const child = new ChildProcess(); + child.spawnfile = file; + child.spawnargs = [file, ...a.args]; + const modes = a.native.stdio; + if (modes[1] === 'pipe') child.stdout = new Readable(); + if (modes[2] === 'pipe') child.stderr = new Readable(); + const onEvent = (type, x, y) => { + if (type === 'stdout') { + child.stdout._push(x); + } else if (type === 'stderr') { + child.stderr._push(x); + } else if (type === 'exit') { + child.exitCode = x; + child.signalCode = y; + child.emit('exit', x, y); + } else if (type === 'close') { + if (child.stdout) child.stdout.emit('end'); + if (child.stderr) child.stderr.emit('end'); + child._handle = null; + child.emit('close', x, y); + } + }; + try { + child._handle = natives.spawn(file, a.args, a.native, onEvent); + child.pid = child._handle.pid; + } catch (e) { + if (!e.code) throw e; + const err = spawnError(e.code, 'spawn', file, a.args); + process.nextTick(() => { + child.emit('error', err); + child.emit('close', -2, null); + }); + } + return child; + } + + builtins.child_process = { spawnSync, spawn, ChildProcess }; + builtins.events = Emitter; + Emitter.EventEmitter = Emitter; + builtins.module.builtinModules.push('child_process', 'events'); + + // -r / --require (command line, NODE_OPTIONS): loaded before the main + // module, relative to the current directory. + function runPreloads() { + const req = makeRequire(new Module(resolvePath(natives.cwd(), '[preload]'), null)); + for (const p of natives.preloads) req(p.startsWith('.') ? resolvePath(natives.cwd(), p) : p); + } + function runMain(path) { + runPreloads(); const real = tryFile(resolvePath(natives.cwd(), path)); if (!real) throw notFound(path, null); mainModule = new Module(real, null); @@ -612,12 +826,23 @@ mainModule.loaded = true; } + // -e / --eval: the code runs as a module of the current directory, with + // process.argv = [execPath, args...] (no script). + function runEval(code) { + runPreloads(); + const filename = resolvePath(natives.cwd(), '[eval]'); + mainModule = new Module(filename, null); + mainModule.id = '[eval]'; + compileAndRun(mainModule, code); + mainModule.loaded = true; + } + function emitBeforeExit() { process.emit('beforeExit', process.exitCode | 0); } return { - runMain, emitExit, emitBeforeExit, runDueTimer, immediateCount, + runMain, runEval, emitExit, emitBeforeExit, runDueTimer, immediateCount, runImmediate, fatalException, unhandledRejection, }; }) diff --git a/host/main.c b/host/main.c index cd29311..18f6785 100644 --- a/host/main.c +++ b/host/main.c @@ -2,8 +2,12 @@ * quickjs-napi host executable. * * quickjs-napi [options] [args...] + * quickjs-napi [options] -e [args...] * - * Options (Node.js names): + * Options (Node.js names), also read from NODE_OPTIONS (where the options + * only Node.js knows are ignored): + * -e, --eval run the code instead of a script + * -r, --require load the module first (repeatable) * --expose-gc accepted; gc() is always available * --force-node-api-uncaught-exceptions-policy[=true|false], * --no-force-node-api-uncaught-exceptions-policy @@ -15,7 +19,8 @@ * `global`, `gc()`, `Buffer`, timers (setTimeout, setInterval, setImmediate, * queueMicrotask), plus the quickjs-libc helpers (console.log, print, * scriptArgs). Builtin modules: module, timers, timers/promises, buffer, - * util, url, vm (minimal subsets, see host/bootstrap.js). + * util, url, vm, child_process (host/spawn.c), events (minimal subsets, see + * host/bootstrap.js). * * Event loop: the host's libuv loop (qjsnapi_host_get_loop), run with * uv_run until nothing referenced is left, then process 'beforeExit' (which @@ -36,6 +41,11 @@ * An uncaught exception goes to process 'uncaughtException' listeners or * prints the error and exits with code 1, as in Node.js. * + * Exit: at the end of the script the host is destroyed (cleanup hooks, + * finalizers, see qjsnapi_host_destroy). process.exit() and fatal + * exceptions end the process at once instead, without that teardown, as + * Node.js does. + * * The executable exports every napi_* and uv_* symbol (see CMakeLists.txt): * addons built for Node.js resolve them from this process. */ @@ -50,6 +60,8 @@ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif +#include +#include #include #else #include @@ -59,8 +71,20 @@ #include +#if defined(__SANITIZE_ADDRESS__) +#define QN_LEAK_SANITIZER 1 +#elif defined(__has_feature) +#if __has_feature(address_sanitizer) +#define QN_LEAK_SANITIZER 1 +#endif +#endif +#ifndef QN_LEAK_SANITIZER +#define QN_LEAK_SANITIZER 0 +#endif + #include "bootstrap_js.h" /* generated: qn_bootstrap_js, qn_bootstrap_js_len */ #include "qjsnapi.h" +#include "spawn.h" #include "quickjs-libc.h" #include "quickjs.h" @@ -69,6 +93,15 @@ #endif static int g_exit_requested; +/* -e / --eval: the code to run instead of a script, or NULL. */ +static const char *g_eval_code; +/* -r / --require: modules loaded before the script (from the command line + * and NODE_OPTIONS), in order. */ +#define MAX_PRELOADS 16 +static const char *g_preloads[MAX_PRELOADS]; +static int g_preload_count; +static char *g_node_options_copy; /* storage of the NODE_OPTIONS tokens */ + static int g_exit_code; /* Object returned by bootstrap.js: runMain, emitExit, emitBeforeExit, * runDueTimer, immediateCount, runImmediate, fatalException, @@ -316,6 +349,8 @@ static JSValue js_gc(JSContext *ctx, JSValueConst this_val, int argc, (void)this_val; (void)argc; (void)argv; + /* V8's gc() collects the targets of weak handles at once. */ + qjsnapi_host_clear_kept_objects(qjsnapi_host_from_context(ctx)); JS_RunGC(JS_GetRuntime(ctx)); JS_RunGC(JS_GetRuntime(ctx)); return JS_UNDEFINED; @@ -413,6 +448,31 @@ static int set_fn(JSContext *ctx, JSValueConst obj, const char *name, return JS_SetPropertyStr(ctx, obj, name, JS_NewCFunction(ctx, fn, name, length)); } +static void host_checkpoint(qjsnapi_host *host, JSContext *ctx, void *opaque); +static void handle_uncaught(JSContext *ctx, JSValue exc); + +/* An event of a child process (spawn.c): a macrotask of its own. */ +static void dispatch_callback(JSContext *ctx, JSValueConst fn, int argc, + JSValueConst *argv) { + if (g_exit_requested) return; + JSValue r = JS_Call(ctx, fn, JS_UNDEFINED, argc, argv); + if (JS_IsException(r)) + handle_uncaught(ctx, JS_GetException(ctx)); + else + JS_FreeValue(ctx, r); + host_checkpoint(NULL, ctx, NULL); +} + +#if defined(__APPLE__) +#include +static char **host_environ(void) { return *_NSGetEnviron(); } +#elif defined(_WIN32) +static char **host_environ(void) { return _environ; } +#else +extern char **environ; +static char **host_environ(void) { return environ; } +#endif + static JSValue make_natives(JSContext *ctx, int argc, char **argv) { JSValue n = JS_NewObject(ctx); if (JS_IsException(n)) return n; @@ -427,6 +487,10 @@ static JSValue make_natives(JSContext *ctx, int argc, char **argv) { set_fn(ctx, n, "runInNewContext", native_run_in_new_context, 1); set_fn(ctx, n, "armTimer", native_arm_timer, 2); set_fn(ctx, n, "armImmediate", native_arm_immediate, 2); + if (spawn_add_natives(ctx, n, g_loop, dispatch_callback) < 0) { + JS_FreeValue(ctx, n); + return JS_EXCEPTION; + } JS_SetPropertyStr(ctx, n, "Buffer", qjsnapi_host_get_buffer(qjsnapi_host_from_context(ctx))); const napi_node_version *nv = qjsnapi_node_version(); @@ -445,12 +509,29 @@ static JSValue make_natives(JSContext *ctx, int argc, char **argv) { JSValue args = JS_NewArray(ctx); JS_SetPropertyUint32(ctx, args, 0, JS_NewString(ctx, exec ? exec : argv[0])); free(exec); - char *script = real_path(argv[1]); - JS_SetPropertyUint32(ctx, args, 1, JS_NewString(ctx, script ? script : argv[1])); - free(script); - for (int i = 2; i < argc; i++) + /* With -e there is no script: argv[1...] are the arguments. */ + int first_arg = 1; + if (!g_eval_code) { + char *script = real_path(argv[1]); + JS_SetPropertyUint32(ctx, args, 1, + JS_NewString(ctx, script ? script : argv[1])); + free(script); + first_arg = 2; + } + for (int i = first_arg; i < argc; i++) JS_SetPropertyUint32(ctx, args, (uint32_t)i, JS_NewString(ctx, argv[i])); JS_SetPropertyStr(ctx, n, "argv", args); + /* process.env: the environment as "NAME=value" strings. */ + JSValue env = JS_NewArray(ctx); + char **envp = host_environ(); + for (uint32_t i = 0; envp && envp[i]; i++) + JS_SetPropertyUint32(ctx, env, i, JS_NewString(ctx, envp[i])); + JS_SetPropertyStr(ctx, n, "environ", env); + JSValue preloads = JS_NewArray(ctx); + for (int i = 0; i < g_preload_count; i++) + JS_SetPropertyUint32(ctx, preloads, (uint32_t)i, + JS_NewString(ctx, g_preloads[i])); + JS_SetPropertyStr(ctx, n, "preloads", preloads); if (JS_HasException(ctx)) { JS_FreeValue(ctx, n); return JS_EXCEPTION; @@ -586,6 +667,8 @@ static void host_checkpoint(qjsnapi_host *host, JSContext *ctx, void *opaque) { if (r > 0) continue; if (!process_rejections(ctx)) break; } + /* End of the macrotask (see qjsnapi_host_clear_kept_objects). */ + qjsnapi_host_clear_kept_objects(qjsnapi_host_from_context(ctx)); if (g_exit_requested) uv_stop(g_loop); } @@ -655,8 +738,9 @@ static int run(JSContext *ctx, qjsnapi_host *host, int argc, char **argv) { qjsnapi_host_set_uncaught_handler(host, on_napi_uncaught, NULL); qjsnapi_host_set_checkpoint(host, host_checkpoint, NULL); - JSValue run_main = JS_GetPropertyStr(ctx, api, "runMain"); - JSValue script = JS_NewString(ctx, argv[1]); + JSValue run_main = + JS_GetPropertyStr(ctx, api, g_eval_code ? "runEval" : "runMain"); + JSValue script = JS_NewString(ctx, g_eval_code ? g_eval_code : argv[1]); JSValue r = JS_Call(ctx, run_main, JS_UNDEFINED, 1, &script); JS_FreeValue(ctx, script); JS_FreeValue(ctx, run_main); @@ -709,43 +793,119 @@ static const char kForcePolicy[] = "--force-node-api-uncaught-exceptions-policy" static const char kNoForcePolicy[] = "--no-force-node-api-uncaught-exceptions-policy"; -/* Options before the script. Returns the index of the script in argv, or - * -1 after printing an error. */ -static int parse_options(int argc, char **argv, int *force_policy) { - int i = 1; - for (; i < argc && strncmp(argv[i], "--", 2) == 0; i++) { - const char *opt = argv[i]; - size_t n = strlen(kForcePolicy); - if (strcmp(opt, "--expose-gc") == 0 || strcmp(opt, "--expose_gc") == 0) { - continue; /* gc() is always available */ - } else if (strcmp(opt, kNoForcePolicy) == 0) { - *force_policy = 0; - } else if (strncmp(opt, kForcePolicy, n) == 0 && - (opt[n] == '\0' || strcmp(opt + n, "=true") == 0)) { - *force_policy = 1; - } else if (strncmp(opt, kForcePolicy, n) == 0 && - strcmp(opt + n, "=false") == 0) { - *force_policy = 0; - } else { - fprintf(stderr, "%s: bad option: %s\n", argv[0], opt); + +/* Parses the option argv[*i] (and its value, advancing *i). Returns 1 when + * -e ends the options, 0 otherwise, -1 after printing an error. In + * NODE_OPTIONS, shared with Node.js, the options quickjs-napi does not know + * (--max-old-space-size, --use-openssl-ca, ...) and -e are ignored. */ +static int parse_option(int argc, char **argv, int *i, int *force_policy, + bool from_env) { + const char *opt = argv[*i]; + size_t n = strlen(kForcePolicy); + bool is_eval = strcmp(opt, "-e") == 0 || strcmp(opt, "--eval") == 0; + bool is_require = strcmp(opt, "-r") == 0 || strcmp(opt, "--require") == 0; + if ((is_eval && !from_env) || is_require) { + if (*i + 1 >= argc) { + fprintf(stderr, "quickjs-napi: %s requires an argument\n", opt); return -1; } + const char *value = argv[++*i]; + if (is_eval) { + g_eval_code = value; + return 1; + } + opt = value; + } else if (strncmp(opt, "--require=", 10) == 0) { + opt += 10; + is_require = true; + } + if (is_require) { + if (g_preload_count == MAX_PRELOADS) { + fprintf(stderr, "quickjs-napi: too many --require options\n"); + return -1; + } + g_preloads[g_preload_count++] = opt; + } else if (strcmp(opt, "--expose-gc") == 0 || + strcmp(opt, "--expose_gc") == 0) { + /* gc() is always available */ + } else if (strcmp(opt, kNoForcePolicy) == 0) { + *force_policy = 0; + } else if (strncmp(opt, kForcePolicy, n) == 0 && + (opt[n] == '\0' || strcmp(opt + n, "=true") == 0)) { + *force_policy = 1; + } else if (strncmp(opt, kForcePolicy, n) == 0 && + strcmp(opt + n, "=false") == 0) { + *force_policy = 0; + } else if (!from_env) { + fprintf(stderr, "quickjs-napi: bad option: %s\n", opt); + return -1; + } + return 0; +} + +/* NODE_OPTIONS: options separated by spaces (no quoting), read before the + * command line. Returns -1 after printing an error. */ +static int parse_node_options(int *force_policy) { + const char *env = getenv("NODE_OPTIONS"); + if (env == NULL || env[0] == '\0') return 0; + g_node_options_copy = strdup(env); + if (g_node_options_copy == NULL) return -1; + char *tokens[64]; + int count = 0; + for (char *t = strtok(g_node_options_copy, " \t"); t; + t = strtok(NULL, " \t")) { + if (count == 64) { + fprintf(stderr, "quickjs-napi: NODE_OPTIONS has too many options\n"); + return -1; + } + tokens[count++] = t; + } + for (int i = 0; i < count; i++) + if (parse_option(count, tokens, &i, force_policy, true) < 0) return -1; + return 0; +} + +/* Options before the script. Returns the index of the script in argv (with + * -e: of the first argument), or -1 after printing an error. */ +static int parse_options(int argc, char **argv, int *force_policy) { + if (parse_node_options(force_policy) < 0) return -1; + int i = 1; + for (; i < argc && argv[i][0] == '-' && argv[i][1] != '\0'; i++) { + int r = parse_option(argc, argv, &i, force_policy, false); + if (r < 0) return -1; + if (r == 1) return i + 1; /* -e: what follows are the arguments */ } return i; } int main(int argc, char **argv) { +#ifdef _WIN32 + /* As in Node.js, "\n" is written as is: in the CRT's default text mode it + * would become "\r\n", which a parent reading the pipe would see. Without a + * stream (fd < 0, e.g. started without a stdout) there is nothing to set; a + * failure on a valid stream is reported, but output still works. */ + { + FILE *streams[2] = {stdout, stderr}; + for (int k = 0; k < 2; k++) { + int fd = _fileno(streams[k]); + if (fd >= 0 && _setmode(fd, _O_BINARY) == -1) + fprintf(stderr, "quickjs-napi: cannot set binary mode on fd %d: %s\n", + fd, strerror(errno)); + } + } +#endif int force_policy = 0; int script = parse_options(argc, argv, &force_policy); if (script < 0) return 9; /* Node.js: invalid command-line option */ - if (script >= argc) { + if (script >= argc && !g_eval_code) { fprintf(stderr, "usage: %s [options] [args...]\n" "quickjs-napi: Node-API %u for QuickJS %s\n", argv[0], qjsnapi_napi_version(), QJS_VERSION_STR); return 2; } - /* From here on argv is [executable, script, args...]. */ + /* From here on argv is [executable, script, args...], or with -e + * [executable, args...]. */ argv[script - 1] = argv[0]; argv += script - 1; argc -= script - 1; @@ -785,6 +945,25 @@ int main(int argc, char **argv) { JS_SetPropertyStr(ctx, global, "gc", js_gc_fn(ctx)); JS_FreeValue(ctx, global); exit_code = run(ctx, host, argc, argv); + if (g_exit_requested) { + /* process.exit() and fatal exceptions: like Node.js + * (DefaultProcessExitHandlerInternal), the process ends without + * tearing the environment down. No cleanup hook or finalizer runs, + * work in the thread pool is not waited for (its completion callback + * would run with JavaScript disabled), only the thread pool is shut + * down. The 'exit' event has already been emitted. */ + fflush(stdout); + fflush(stderr); + uv_library_shutdown(); +#if QN_LEAK_SANITIZER + /* What is left allocated is not freed by design (as in Node.js), so + * LeakSanitizer, which checks at exit(), is bypassed. */ + _exit(exit_code); +#else + exit(exit_code); +#endif + } + spawn_close_all(); close_host_handles(); qjsnapi_host_destroy(host); g_loop = NULL; @@ -793,5 +972,6 @@ int main(int argc, char **argv) { js_std_free_handlers(rt); JS_FreeContext(ctx); JS_FreeRuntime(rt); + free(g_node_options_copy); return exit_code; } diff --git a/host/spawn.c b/host/spawn.c new file mode 100644 index 0000000..2cc9138 --- /dev/null +++ b/host/spawn.c @@ -0,0 +1,625 @@ +/* + * Child processes for the quickjs-napi executable: the natives behind the + * child_process module of host/bootstrap.js. + * + * natives.spawnSync(file, args, options) -> { pid, status, signal, + * stdout, stderr, error } + * Runs the child on a private libuv loop until it exits and its pipes + * are drained. options: { env: ["K=V", ...] | undefined (inherit), + * cwd, stdio: ["pipe"|"inherit"|"ignore" x3], input: ArrayBuffer, + * timeout (ms, 0 = none), killSignal (name) }. stdout / stderr are + * ArrayBuffers for "pipe", null otherwise. `error` is the libuv error + * name (e.g. "ENOENT") when the child could not be started, or + * "ETIMEDOUT" when the timeout killed it; status is then null. + * + * natives.spawn(file, args, options, onEvent) -> { pid, kill(signal) } + * Runs the child on the executable's loop. onEvent(type, a, b): + * ("stdout" | "stderr", ArrayBuffer) data from a "pipe" stream; + * ("exit", code, signal) the process ended; + * ("close", code, signal) the process ended and every + * stream is closed (last event). + * A start failure throws an Error whose `code` is the libuv error name. + * stdin "pipe" is not supported for asynchronous children (nothing can + * write to it): it is ignored, so the child reads end-of-file. + * + * Ownership of an asynchronous child: the struct is malloc'ed and linked in + * g_children from uv_spawn until the close callback of its last handle; it + * holds a reference to onEvent until then. The JS handle refers to it by id + * only, so it may outlive the struct. spawn_close_all() closes every + * handle at teardown without calling JavaScript. + */ +#include "spawn.h" + +#include +#include +#include +#include +#include + +/* ------------------------------------------------------------------------ */ +/* Helpers */ +/* ------------------------------------------------------------------------ */ + +typedef struct { + char *data; + size_t len, cap; +} byte_buf; + +static int buf_append(byte_buf *b, const char *p, size_t n) { + if (b->len + n > b->cap) { + size_t cap = b->cap ? b->cap : 4096; + while (cap < b->len + n) cap *= 2; + char *d = (char *)realloc(b->data, cap); + if (d == NULL) return -1; + b->data = d; + b->cap = cap; + } + memcpy(b->data + b->len, p, n); + b->len += n; + return 0; +} + +/* The signals of the platform (uv.h defines SIGHUP, SIGQUIT, SIGKILL on + * Windows, where libuv emulates them). */ +#define SIG(n) {#n, n} +static const struct { + const char *name; + int num; +} kSignals[] = { + SIG(SIGINT), SIG(SIGILL), SIG(SIGABRT), SIG(SIGFPE), SIG(SIGSEGV), + SIG(SIGTERM), +#ifdef SIGHUP + SIG(SIGHUP), +#endif +#ifdef SIGQUIT + SIG(SIGQUIT), +#endif +#ifdef SIGKILL + SIG(SIGKILL), +#endif +#ifdef SIGTRAP + SIG(SIGTRAP), +#endif +#ifdef SIGBUS + SIG(SIGBUS), +#endif +#ifdef SIGUSR1 + SIG(SIGUSR1), +#endif +#ifdef SIGUSR2 + SIG(SIGUSR2), +#endif +#ifdef SIGPIPE + SIG(SIGPIPE), +#endif +#ifdef SIGALRM + SIG(SIGALRM), +#endif +}; +#undef SIG + +static JSValue signal_name(JSContext *ctx, int num) { + if (num == 0) return JS_NULL; + for (size_t i = 0; i < sizeof(kSignals) / sizeof(kSignals[0]); i++) + if (kSignals[i].num == num) return JS_NewString(ctx, kSignals[i].name); + return JS_NewInt32(ctx, num); +} + +/* A signal given as a name ("SIGTERM") or a number; -1 if unknown. */ +static int signal_number(JSContext *ctx, JSValueConst v, int dflt) { + if (JS_IsUndefined(v) || JS_IsNull(v)) return dflt; + if (JS_IsNumber(v)) { + int32_t n; + if (JS_ToInt32(ctx, &n, v) < 0) return -1; + return n; + } + const char *s = JS_ToCString(ctx, v); + if (s == NULL) return -1; + int num = -1; + for (size_t i = 0; i < sizeof(kSignals) / sizeof(kSignals[0]); i++) + if (strcmp(kSignals[i].name, s) == 0) num = kSignals[i].num; + JS_FreeCString(ctx, s); + return num; +} + +/* Strings collected from JS for uv_process_options_t. */ +typedef struct { + char *file; + char **args; /* NULL-terminated, args[0] = file */ + char **env; /* NULL-terminated, or NULL to inherit */ + char *cwd; + int stdio[3]; /* 0 ignore, 1 inherit, 2 pipe */ +} spawn_spec; + +static void spec_free(spawn_spec *s) { + free(s->file); + if (s->args) + for (char **p = s->args; *p; p++) free(*p); + free(s->args); + if (s->env) + for (char **p = s->env; *p; p++) free(*p); + free(s->env); + free(s->cwd); +} + +static char *dup_string(JSContext *ctx, JSValueConst v) { + const char *s = JS_ToCString(ctx, v); + if (s == NULL) return NULL; + char *d = strdup(s); + JS_FreeCString(ctx, s); + if (d == NULL) JS_ThrowOutOfMemory(ctx); + return d; +} + +/* A NULL-terminated copy of the array `arr` of strings, with `first` + * (if not NULL) prepended. */ +static char **dup_string_array(JSContext *ctx, JSValueConst arr, + const char *first) { + int64_t n = 0; + JSValue len = JS_GetPropertyStr(ctx, arr, "length"); + int r = JS_ToInt64(ctx, &n, len); + JS_FreeValue(ctx, len); + if (r < 0) return NULL; + if (n < 0 || n > 65536) { + JS_ThrowRangeError(ctx, "spawn: too many strings"); + return NULL; + } + size_t extra = first ? 1 : 0; + char **out = (char **)calloc((size_t)n + extra + 1, sizeof(char *)); + if (out == NULL) { + JS_ThrowOutOfMemory(ctx); + return NULL; + } + if (first && (out[0] = strdup(first)) == NULL) goto oom; + for (int64_t i = 0; i < n; i++) { + JSValue v = JS_GetPropertyUint32(ctx, arr, (uint32_t)i); + if (JS_IsException(v)) goto fail; + out[extra + i] = dup_string(ctx, v); + JS_FreeValue(ctx, v); + if (out[extra + i] == NULL) goto fail; + } + return out; +oom: + JS_ThrowOutOfMemory(ctx); +fail: + for (char **p = out; *p; p++) free(*p); + free(out); + return NULL; +} + +static int spec_init(JSContext *ctx, spawn_spec *s, JSValueConst file, + JSValueConst args, JSValueConst options) { + memset(s, 0, sizeof(*s)); + s->stdio[0] = s->stdio[1] = s->stdio[2] = 2; + if ((s->file = dup_string(ctx, file)) == NULL) return -1; + if ((s->args = dup_string_array(ctx, args, s->file)) == NULL) return -1; + JSValue env = JS_GetPropertyStr(ctx, options, "env"); + if (JS_IsException(env)) return -1; + if (!JS_IsUndefined(env) && !JS_IsNull(env)) { + s->env = dup_string_array(ctx, env, NULL); + JS_FreeValue(ctx, env); + if (s->env == NULL) return -1; + } + JSValue cwd = JS_GetPropertyStr(ctx, options, "cwd"); + if (JS_IsException(cwd)) return -1; + if (!JS_IsUndefined(cwd) && !JS_IsNull(cwd)) { + s->cwd = dup_string(ctx, cwd); + JS_FreeValue(ctx, cwd); + if (s->cwd == NULL) return -1; + } + JSValue stdio = JS_GetPropertyStr(ctx, options, "stdio"); + if (JS_IsException(stdio)) return -1; + for (uint32_t i = 0; i < 3 && JS_IsArray(ctx, stdio) > 0; i++) { + JSValue m = JS_GetPropertyUint32(ctx, stdio, i); + const char *ms = JS_IsString(m) ? JS_ToCString(ctx, m) : NULL; + if (ms) { + s->stdio[i] = strcmp(ms, "inherit") == 0 ? 1 + : strcmp(ms, "ignore") == 0 ? 0 + : 2; + JS_FreeCString(ctx, ms); + } + JS_FreeValue(ctx, m); + } + JS_FreeValue(ctx, stdio); + return 0; +} + +static void spec_options(const spawn_spec *s, uv_process_options_t *o, + uv_stdio_container_t io[3], uv_pipe_t pipes[3], + bool stdin_pipe) { + memset(o, 0, sizeof(*o)); + o->file = s->file; + o->args = s->args; + o->env = s->env; + o->cwd = s->cwd; + o->flags = UV_PROCESS_WINDOWS_HIDE; + o->stdio = io; + o->stdio_count = 3; + for (int i = 0; i < 3; i++) { + if (s->stdio[i] == 1) { + io[i].flags = UV_INHERIT_FD; + io[i].data.fd = i; + } else if (s->stdio[i] == 2 && (i > 0 || stdin_pipe)) { + io[i].flags = (uv_stdio_flags)(UV_CREATE_PIPE | + (i == 0 ? UV_READABLE_PIPE + : UV_WRITABLE_PIPE)); + io[i].data.stream = (uv_stream_t *)&pipes[i]; + } else { + io[i].flags = UV_IGNORE; + } + } +} + +static JSValue array_buffer(JSContext *ctx, const byte_buf *b) { + return JS_NewArrayBufferCopy(ctx, (const uint8_t *)(b->data ? b->data : ""), + b->len); +} + +static void alloc_cb(uv_handle_t *h, size_t suggested, uv_buf_t *buf) { + (void)h; + buf->base = (char *)malloc(suggested); + buf->len = buf->base ? suggested : 0; +} + +/* ------------------------------------------------------------------------ */ +/* spawnSync */ +/* ------------------------------------------------------------------------ */ + +typedef struct { + uv_process_t proc; + uv_pipe_t pipes[3]; + uv_timer_t timer; + uv_write_t write_req; + byte_buf out[3]; /* [1] stdout, [2] stderr */ + bool exited, timed_out, oom; + int64_t status; + int term_signal; + int kill_signal; +} sync_child; + +static void sync_read_cb(uv_stream_t *s, ssize_t n, const uv_buf_t *buf) { + sync_child *c = (sync_child *)s->data; + int idx = s == (uv_stream_t *)&c->pipes[1] ? 1 : 2; + if (n > 0 && buf_append(&c->out[idx], buf->base, (size_t)n) < 0) + c->oom = true; + free(buf->base); + if (n < 0) uv_close((uv_handle_t *)s, NULL); /* EOF or error */ +} + +static void sync_exit_cb(uv_process_t *p, int64_t status, int sig) { + sync_child *c = (sync_child *)p->data; + c->exited = true; + c->status = status; + c->term_signal = sig; + uv_close((uv_handle_t *)p, NULL); + if (uv_is_active((uv_handle_t *)&c->timer)) uv_timer_stop(&c->timer); + if (!uv_is_closing((uv_handle_t *)&c->timer)) + uv_close((uv_handle_t *)&c->timer, NULL); +} + +static void sync_timeout_cb(uv_timer_t *t) { + sync_child *c = (sync_child *)t->data; + c->timed_out = true; + uv_process_kill(&c->proc, c->kill_signal); +} + +static void sync_write_cb(uv_write_t *req, int status) { + (void)status; + uv_close((uv_handle_t *)req->handle, NULL); /* stdin: end of input */ +} + +static JSValue error_result(JSContext *ctx, int uv_err) { + JSValue r = JS_NewObject(ctx); + JS_SetPropertyStr(ctx, r, "pid", JS_NewInt32(ctx, 0)); + JS_SetPropertyStr(ctx, r, "status", JS_NULL); + JS_SetPropertyStr(ctx, r, "signal", JS_NULL); + JS_SetPropertyStr(ctx, r, "stdout", JS_NULL); + JS_SetPropertyStr(ctx, r, "stderr", JS_NULL); + JS_SetPropertyStr(ctx, r, "error", JS_NewString(ctx, uv_err_name(uv_err))); + return r; +} + +static JSValue native_spawn_sync(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv) { + (void)this_val; + (void)argc; + JSValueConst options = argv[2]; + spawn_spec spec; + if (spec_init(ctx, &spec, argv[0], argv[1], options) < 0) { + spec_free(&spec); + return JS_EXCEPTION; + } + /* Optional input for stdin, and timeout. */ + size_t input_len = 0; + uint8_t *input_data = NULL; + JSValue input = JS_GetPropertyStr(ctx, options, "input"); + if (!JS_IsUndefined(input) && !JS_IsNull(input)) + input_data = JS_GetArrayBuffer(ctx, &input_len, input); + int64_t timeout = 0; + JSValue tv = JS_GetPropertyStr(ctx, options, "timeout"); + if (!JS_IsUndefined(tv)) JS_ToInt64(ctx, &timeout, tv); + JS_FreeValue(ctx, tv); + JSValue ks = JS_GetPropertyStr(ctx, options, "killSignal"); + int kill_signal = signal_number(ctx, ks, SIGTERM); + JS_FreeValue(ctx, ks); + if (JS_HasException(ctx)) { + JS_FreeValue(ctx, input); + spec_free(&spec); + return JS_EXCEPTION; + } + + uv_loop_t loop; + int err = uv_loop_init(&loop); + if (err < 0) { + JS_FreeValue(ctx, input); + spec_free(&spec); + return error_result(ctx, err); + } + sync_child *c = (sync_child *)calloc(1, sizeof(sync_child)); + if (c == NULL) { + uv_loop_close(&loop); + JS_FreeValue(ctx, input); + spec_free(&spec); + return JS_ThrowOutOfMemory(ctx); + } + c->kill_signal = kill_signal < 0 ? SIGTERM : kill_signal; + bool stdin_pipe = spec.stdio[0] == 2 && input_data != NULL; + for (int i = 0; i < 3; i++) { + uv_pipe_init(&loop, &c->pipes[i], 0); + c->pipes[i].data = c; + } + uv_process_options_t o; + uv_stdio_container_t io[3]; + spec_options(&spec, &o, io, c->pipes, stdin_pipe); + o.exit_cb = sync_exit_cb; + c->proc.data = c; + err = uv_spawn(&loop, &c->proc, &o); + + JSValue result; + if (err < 0) { + /* libuv: a process handle that failed to spawn must still be closed. */ + uv_close((uv_handle_t *)&c->proc, NULL); + for (int i = 0; i < 3; i++) uv_close((uv_handle_t *)&c->pipes[i], NULL); + uv_run(&loop, UV_RUN_DEFAULT); + result = error_result(ctx, err); + } else { + for (int i = 0; i < 3; i++) { + bool used = io[i].flags & UV_CREATE_PIPE; + if (!used) { + uv_close((uv_handle_t *)&c->pipes[i], NULL); + } else if (i == 0) { + uv_buf_t b = uv_buf_init((char *)input_data, (unsigned)input_len); + if (uv_write(&c->write_req, (uv_stream_t *)&c->pipes[0], &b, 1, + sync_write_cb) < 0) + uv_close((uv_handle_t *)&c->pipes[0], NULL); + } else { + uv_read_start((uv_stream_t *)&c->pipes[i], alloc_cb, sync_read_cb); + } + } + uv_timer_init(&loop, &c->timer); + c->timer.data = c; + if (timeout > 0) uv_timer_start(&c->timer, sync_timeout_cb, (uint64_t)timeout, 0); + uv_run(&loop, UV_RUN_DEFAULT); + + result = JS_NewObject(ctx); + JS_SetPropertyStr(ctx, result, "pid", JS_NewInt32(ctx, c->proc.pid)); + bool by_signal = c->term_signal != 0; + JS_SetPropertyStr(ctx, result, "status", + by_signal ? JS_NULL : JS_NewInt64(ctx, c->status)); + JS_SetPropertyStr(ctx, result, "signal", signal_name(ctx, c->term_signal)); + for (int i = 1; i < 3; i++) + JS_SetPropertyStr(ctx, result, i == 1 ? "stdout" : "stderr", + spec.stdio[i] == 2 ? array_buffer(ctx, &c->out[i]) + : JS_NULL); + JS_SetPropertyStr(ctx, result, "error", + c->timed_out ? JS_NewString(ctx, "ETIMEDOUT") + : c->oom ? JS_NewString(ctx, "ENOMEM") + : JS_NULL); + } + uv_loop_close(&loop); /* every handle is closed: cannot be EBUSY */ + for (int i = 0; i < 3; i++) free(c->out[i].data); + free(c); + JS_FreeValue(ctx, input); + spec_free(&spec); + return result; +} + +/* ------------------------------------------------------------------------ */ +/* spawn */ +/* ------------------------------------------------------------------------ */ + +typedef struct async_child { + struct async_child *next; + uint32_t id; /* what the kill() function of the JS handle looks up */ + uv_process_t proc; + uv_pipe_t pipes[3]; + bool pipe_open[3]; + int open_handles; + JSContext *ctx; + JSValue on_event; + int64_t status; + int term_signal; + bool exited, silent; /* silent: teardown, no more JavaScript */ +} async_child; + +static uv_loop_t *g_spawn_loop; +static spawn_dispatch_fn g_dispatch; +static async_child *g_children; +static uint32_t g_next_child_id; + +static void child_event(async_child *c, const char *type, JSValue a, + JSValue b) { + if (c->silent) { + JS_FreeValue(c->ctx, a); + JS_FreeValue(c->ctx, b); + return; + } + JSValue args[3] = {JS_NewString(c->ctx, type), a, b}; + g_dispatch(c->ctx, c->on_event, 3, args); + for (int i = 0; i < 3; i++) JS_FreeValue(c->ctx, args[i]); +} + +static void child_unlink(async_child *c) { + for (async_child **p = &g_children; *p; p = &(*p)->next) + if (*p == c) { + *p = c->next; + return; + } +} + +static JSValue exit_code(async_child *c) { + return c->term_signal ? JS_NULL : JS_NewInt64(c->ctx, c->status); +} + +static void child_handle_closed(uv_handle_t *h) { + async_child *c = (async_child *)h->data; + if (--c->open_handles > 0) return; + child_event(c, "close", exit_code(c), signal_name(c->ctx, c->term_signal)); + child_unlink(c); + JS_FreeValue(c->ctx, c->on_event); + free(c); +} + +static void child_read_cb(uv_stream_t *s, ssize_t n, const uv_buf_t *buf) { + async_child *c = (async_child *)s->data; + int idx = s == (uv_stream_t *)&c->pipes[1] ? 1 : 2; + if (n > 0) { + child_event(c, idx == 1 ? "stdout" : "stderr", + JS_NewArrayBufferCopy(c->ctx, (const uint8_t *)buf->base, + (size_t)n), + JS_UNDEFINED); + } + free(buf->base); + if (n < 0 && c->pipe_open[idx]) { + c->pipe_open[idx] = false; + uv_close((uv_handle_t *)s, child_handle_closed); + } +} + +static void child_exit_cb(uv_process_t *p, int64_t status, int sig) { + async_child *c = (async_child *)p->data; + c->exited = true; + c->status = status; + c->term_signal = sig; + child_event(c, "exit", exit_code(c), signal_name(c->ctx, sig)); + uv_close((uv_handle_t *)p, child_handle_closed); +} + +/* kill(signal), bound to a child id (func_data[0]): the handle object may + * outlive the child struct. */ +static JSValue native_child_kill(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv, int magic, + JSValueConst *func_data) { + (void)this_val; + (void)magic; + uint32_t id = 0; + JS_ToUint32(ctx, &id, func_data[0]); + async_child *c = g_children; + while (c && c->id != id) c = c->next; + /* Node.js: kill() after the child exited returns false. */ + if (c == NULL || c->exited) return JS_FALSE; + int sig = signal_number(ctx, argc > 0 ? argv[0] : JS_UNDEFINED, SIGTERM); + if (sig < 0) return JS_ThrowTypeError(ctx, "Unknown signal"); + return JS_NewBool(ctx, uv_process_kill(&c->proc, sig) == 0); +} + +static JSValue native_spawn(JSContext *ctx, JSValueConst this_val, int argc, + JSValueConst *argv) { + (void)this_val; + (void)argc; + if (!JS_IsFunction(ctx, argv[3])) + return JS_ThrowTypeError(ctx, "spawn: onEvent must be a function"); + spawn_spec spec; + if (spec_init(ctx, &spec, argv[0], argv[1], argv[2]) < 0) { + spec_free(&spec); + return JS_EXCEPTION; + } + async_child *c = (async_child *)calloc(1, sizeof(async_child)); + if (c == NULL) { + spec_free(&spec); + return JS_ThrowOutOfMemory(ctx); + } + c->ctx = ctx; + for (int i = 0; i < 3; i++) { + uv_pipe_init(g_spawn_loop, &c->pipes[i], 0); + c->pipes[i].data = c; + } + uv_process_options_t o; + uv_stdio_container_t io[3]; + spec_options(&spec, &o, io, c->pipes, false); + o.exit_cb = child_exit_cb; + c->proc.data = c; + int err = uv_spawn(g_spawn_loop, &c->proc, &o); + spec_free(&spec); + if (err < 0) { + /* The pipes are initialized handles: closed, freed by the callback. */ + c->silent = true; + c->exited = true; /* nothing to kill */ + c->on_event = JS_UNDEFINED; + c->open_handles = 4; + c->next = g_children; + g_children = c; + /* libuv: a process handle that failed to spawn must still be closed. */ + uv_close((uv_handle_t *)&c->proc, child_handle_closed); + for (int i = 0; i < 3; i++) + uv_close((uv_handle_t *)&c->pipes[i], child_handle_closed); + JSValue e = JS_NewError(ctx); + JS_SetPropertyStr(ctx, e, "message", + JS_NewString(ctx, uv_strerror(err))); + JS_SetPropertyStr(ctx, e, "code", JS_NewString(ctx, uv_err_name(err))); + return JS_Throw(ctx, e); + } + c->on_event = JS_DupValue(ctx, argv[3]); + c->open_handles = 1; /* the process */ + for (int i = 0; i < 3; i++) { + if (io[i].flags & UV_CREATE_PIPE) { + c->pipe_open[i] = true; + c->open_handles++; + uv_read_start((uv_stream_t *)&c->pipes[i], alloc_cb, child_read_cb); + } else { + c->open_handles++; + uv_close((uv_handle_t *)&c->pipes[i], child_handle_closed); + } + } + c->id = ++g_next_child_id; + c->next = g_children; + g_children = c; + + JSValue obj = JS_NewObject(ctx); + if (JS_IsException(obj)) return obj; + JSValue id = JS_NewUint32(ctx, c->id); + JS_SetPropertyStr(ctx, obj, "pid", JS_NewInt32(ctx, c->proc.pid)); + JS_SetPropertyStr(ctx, obj, "kill", + JS_NewCFunctionData(ctx, native_child_kill, 1, 0, 1, &id)); + if (JS_HasException(ctx)) { + JS_FreeValue(ctx, obj); + return JS_EXCEPTION; + } + return obj; +} + +void spawn_close_all(void) { + for (async_child *c = g_children; c; c = c->next) { + c->silent = true; + if (!c->exited && !uv_is_closing((uv_handle_t *)&c->proc)) + uv_close((uv_handle_t *)&c->proc, child_handle_closed); + for (int i = 1; i < 3; i++) + if (c->pipe_open[i]) { + c->pipe_open[i] = false; + uv_close((uv_handle_t *)&c->pipes[i], child_handle_closed); + } + } +} + +int spawn_add_natives(JSContext *ctx, JSValueConst natives, uv_loop_t *loop, + spawn_dispatch_fn dispatch) { + g_spawn_loop = loop; + g_dispatch = dispatch; + if (JS_SetPropertyStr(ctx, natives, "spawnSync", + JS_NewCFunction(ctx, native_spawn_sync, "spawnSync", + 3)) < 0 || + JS_SetPropertyStr(ctx, natives, "spawn", + JS_NewCFunction(ctx, native_spawn, "spawn", 4)) < 0) + return -1; + return 0; +} diff --git a/host/spawn.h b/host/spawn.h new file mode 100644 index 0000000..1a7e7bd --- /dev/null +++ b/host/spawn.h @@ -0,0 +1,28 @@ +/* + * Child processes for the quickjs-napi executable (child_process module of + * host/bootstrap.js): natives.spawnSync and natives.spawn, on libuv. + */ +#ifndef QJSNAPI_HOST_SPAWN_H +#define QJSNAPI_HOST_SPAWN_H + +#include + +#include "quickjs.h" + +/* Calls `fn` from a libuv callback: the executable reports an exception as + * uncaught and runs its checkpoint afterwards. */ +typedef void (*spawn_dispatch_fn)(JSContext *ctx, JSValueConst fn, int argc, + JSValueConst *argv); + +/* Adds spawnSync and spawn to `natives`. Asynchronous children run on + * `loop`; their events go through `dispatch`. Returns -1 with an exception + * pending on failure. */ +int spawn_add_natives(JSContext *ctx, JSValueConst natives, uv_loop_t *loop, + spawn_dispatch_fn dispatch); + +/* Closes the handles of asynchronous children still running, without + * waiting for them or calling back into JavaScript (process teardown). The + * caller runs the loop afterwards so that the close callbacks free them. */ +void spawn_close_all(void); + +#endif /* QJSNAPI_HOST_SPAWN_H */ diff --git a/include/qjsnapi.h b/include/qjsnapi.h index f3d8c47..b9b02c3 100644 --- a/include/qjsnapi.h +++ b/include/qjsnapi.h @@ -105,6 +105,20 @@ uint32_t qjsnapi_napi_version(void); /* Runs the queued finalizers of every env. Returns how many ran. */ size_t qjsnapi_host_run_finalizers(qjsnapi_host *host); +/* ---- Weak references ------------------------------------------------------ + * + * V8 keeps the target of a weak handle alive until a garbage collection + * finds it unreachable; QuickJS frees an object as soon as its refcount drops + * to zero. Addons rely on V8's behaviour (node-addon-api: Napi::Weak of an + * object created in the same call). So when a reference becomes weak (count + * 0) its target is also put on a "kept objects" list, like the [[KeptAlive]] + * list of ECMAScript WeakRefs, and stays alive until the list is cleared: + * at every checkpoint of the library (after a callback from the event loop), + * when the host is destroyed, and when the embedder calls this function. An + * embedder clears it at the end of each macrotask it runs itself, and before + * an explicit garbage collection (global.gc()). */ +void qjsnapi_host_clear_kept_objects(qjsnapi_host *host); + /* Non-zero when finalizers are queued: the event loop must not exit yet. */ int qjsnapi_host_has_pending_finalizers(qjsnapi_host *host); diff --git a/src/env.c b/src/env.c index 0d1cda2..4ef8155 100644 --- a/src/env.c +++ b/src/env.c @@ -349,6 +349,7 @@ void qjsnapi_host_destroy(qjsnapi_host *host) { qn_env_cancel_works(QN_CONTAINER_OF(el, struct napi_env__, link)); } qn_loop_drain(host); + qjsnapi_host_clear_kept_objects(host); /* 3. References and finalizers. */ for (qn_list *el = host->envs.prev; el != &host->envs; el = el->prev) { qn_env_teardown(QN_CONTAINER_OF(el, struct napi_env__, link)); @@ -358,6 +359,7 @@ void qjsnapi_host_destroy(qjsnapi_host *host) { qn_env_free(QN_CONTAINER_OF(host->envs.prev, struct napi_env__, link)); } qn_loop_close(host); + qjsnapi_host_clear_kept_objects(host); host_free_values(host); if (JS_GetContextOpaque(host->ctx) == host) JS_SetContextOpaque(host->ctx, NULL); diff --git a/src/function.c b/src/function.c index 1ef1154..e98c0af 100644 --- a/src/function.c +++ b/src/function.c @@ -329,6 +329,41 @@ NAPI_EXTERN napi_status NAPI_CDECL napi_new_instance(napi_env env, * one with a receiver not created by the class throws "Illegal invocation". * Here such a call reaches the native callback, which must validate `this` * (napi_unwrap fails on foreign objects). */ +/* The key of a property descriptor, JS_ATOM_NULL when it has none or the + * name is invalid (qn_define_property then reports the error). */ +static JSAtom descriptor_key(JSContext *ctx, const napi_property_descriptor *p) { + if (p->utf8name != NULL) return JS_NewAtom(ctx, p->utf8name); + if (p->name == NULL) return JS_ATOM_NULL; + JSValueConst name = qn_value(p->name); + if (!JS_IsString(name) && !JS_IsSymbol(name)) return JS_ATOM_NULL; + return JS_ValueToAtom(ctx, name); +} + +/* Whether a later instance (non-static) descriptor has the same key as + * properties[i]. */ +static bool instance_key_redefined(JSContext *ctx, + const napi_property_descriptor *properties, + size_t count, size_t i) { + JSAtom key = descriptor_key(ctx, &properties[i]); + if (key == JS_ATOM_NULL) { + if (JS_HasException(ctx)) JS_FreeValue(ctx, JS_GetException(ctx)); + return false; + } + bool found = false; + for (size_t j = i + 1; j < count && !found; j++) { + if (properties[j].attributes & napi_static) continue; + JSAtom other = descriptor_key(ctx, &properties[j]); + if (other == JS_ATOM_NULL) { + if (JS_HasException(ctx)) JS_FreeValue(ctx, JS_GetException(ctx)); + continue; + } + found = other == key; + JS_FreeAtom(ctx, other); + } + JS_FreeAtom(ctx, key); + return found; +} + NAPI_EXTERN napi_status NAPI_CDECL napi_define_class(napi_env env, const char *utf8name, size_t length, napi_callback constructor, void *data, @@ -361,6 +396,13 @@ napi_define_class(napi_env env, const char *utf8name, size_t length, static_count++; continue; } + /* V8 adds instance properties to the prototype template, where a later + * definition of the same key replaces an earlier one whatever its + * attributes (node-addon-api's objectwrap test defines a symbol-keyed + * non-configurable accessor twice). Static properties are defined on the + * function like napi_define_properties, where such a redefinition + * fails, in Node.js too. */ + if (instance_key_redefined(ctx, properties, property_count, i)) continue; napi_status st = qn_define_property(env, proto, p); if (st != napi_ok) { JS_FreeValue(ctx, proto); diff --git a/src/lifetime.c b/src/lifetime.c index 0a45472..399b8ff 100644 --- a/src/lifetime.c +++ b/src/lifetime.c @@ -9,7 +9,11 @@ * symbol is held through a JS WeakRef: QuickJS reports a WeakRef target * dead as soon as its refcount drops to zero, so napi_get_reference_value * returns NULL exactly when the value is gone. Other primitives are - * released for good at count 0 (Node: persistent reset). + * released for good at count 0 (Node: persistent reset). A target that + * becomes weak is also kept alive until qjsnapi_host_clear_kept_objects + * (end of the macrotask, gc()), as V8 keeps it until a GC: without this + * an object created by a native call and referenced weakly would die + * when the call's handle scope closes. * * - Weak callback. V8 notifies a weak persistent when its target is * collected; QuickJS has no such C hook. Every weakable target gets a @@ -232,6 +236,37 @@ static void ref_reset(napi_ref ref) { JS_FreeValue(ctx, weak); } +/* Adds `v` (whose reference the caller hands over) to the kept objects. On + * allocation failure the object is released at once: it is only kept alive + * for a shorter time. */ +static void keep_alive(qjsnapi_host *host, JSValue v) { + if (host->kept_len == host->kept_cap) { + size_t cap = host->kept_cap ? host->kept_cap * 2 : 16; + JSValue *a = (JSValue *)realloc(host->kept, cap * sizeof(JSValue)); + if (a == NULL) { + JS_FreeValue(host->ctx, v); + return; + } + host->kept = a; + host->kept_cap = cap; + } + host->kept[host->kept_len++] = v; +} + +void qjsnapi_host_clear_kept_objects(qjsnapi_host *host) { + if (host == NULL) return; + /* Freeing may run class finalizers that make other references weak, so + * the list is detached first and cleared until it stays empty. */ + while (host->kept_len > 0) { + JSValue *a = host->kept; + size_t n = host->kept_len; + host->kept = NULL; + host->kept_len = host->kept_cap = 0; + for (size_t i = 0; i < n; i++) JS_FreeValue(host->ctx, a[i]); + free(a); + } +} + /* Node: Reference::SetWeak(). Returns -1 (exception pending) only when the * WeakRef cannot be allocated; the reference then stays strong. */ static int ref_set_weak(napi_ref ref) { @@ -244,7 +279,7 @@ static int ref_set_weak(napi_ref ref) { ref->weak = w; JSValue v = ref->value; ref->value = JS_UNDEFINED; - JS_FreeValue(ctx, v); + keep_alive(ref->env->host, v); /* takes over the reference held */ return 0; } ref_reset(ref); @@ -344,16 +379,15 @@ static void ref_delete(napi_ref ref) { /* Node: Reference::Finalize(). The target is gone (or the env is being torn * down): reset the value, unlink, run the user finalizer, and delete the * reference if the runtime owns it. A user-owned reference may be deleted by - * its own finalizer, so it is not touched after the callback; at teardown it - * is parked in env->orphan_refs first, so it is freed with the env when the - * addon never deletes it (qn_env_free_orphan_refs). */ + * its own finalizer, so it is not touched after the callback; it is parked + * in env->orphan_refs first, so it is freed with the env when the addon + * never deletes it (qn_env_free_orphan_refs; Node.js leaks it). */ static void ref_finalize(napi_ref ref) { napi_env env = ref->env; if (!ref->tracker) ref_reset(ref); bool delete_me = ref->runtime_owned; unlink_if_linked(&ref->link); - if (!delete_me && env->destructing) - qn_list_add_tail(&ref->link, &env->orphan_refs); + if (!delete_me) qn_list_add_tail(&ref->link, &env->orphan_refs); ref_dequeue(ref); ref_detach_holder(ref); napi_finalize cb = ref->finalize_cb; diff --git a/src/node_api.c b/src/node_api.c index a33cf9e..738a47f 100644 --- a/src/node_api.c +++ b/src/node_api.c @@ -38,14 +38,16 @@ void qn_env_free_async_contexts(napi_env env) { void qn_microtask_checkpoint(qjsnapi_host *host) { if (host->checkpoint_fn) { host->checkpoint_fn(host, host->ctx, host->checkpoint_opaque); - return; - } - for (;;) { - JSContext *job_ctx; - int r = JS_ExecutePendingJob(host->rt, &job_ctx); - if (r == 0) break; - if (r < 0) qn_report_uncaught(host, JS_GetException(job_ctx)); + } else { + for (;;) { + JSContext *job_ctx; + int r = JS_ExecutePendingJob(host->rt, &job_ctx); + if (r == 0) break; + if (r < 0) qn_report_uncaught(host, JS_GetException(job_ctx)); + } } + /* End of the macrotask: weak targets may go (see qjsnapi.h). */ + qjsnapi_host_clear_kept_objects(host); } /* V8's ToObject fails, with a pending TypeError, only for undefined and diff --git a/src/qjsnapi_internal.h b/src/qjsnapi_internal.h index e0352b4..1d57ecc 100644 --- a/src/qjsnapi_internal.h +++ b/src/qjsnapi_internal.h @@ -213,6 +213,10 @@ struct qjsnapi_host { uint32_t live_tsfns; /* thread-safe functions not finalized */ uint32_t running_async_cleanup; /* async cleanup hooks started, not removed */ bool destroying; + /* Targets of references that became weak, held strongly until the next + * qjsnapi_host_clear_kept_objects (lifetime.c). */ + JSValue *kept; + size_t kept_len, kept_cap; }; /* Per-target side record of the lifetime machinery, stored as the opaque of @@ -289,7 +293,7 @@ struct napi_env__ { qn_list async_contexts; /* napi_async_work queued and not completed (cancelled at teardown). */ qn_list works; /* napi_async_work items not deleted yet */ - qn_list orphan_refs; /* user references finalized at teardown */ + qn_list orphan_refs; /* finalized user references, not deleted yet */ uint32_t open_callback_scopes; bool destructing; }; diff --git a/test/js/fixtures/preload.js b/test/js/fixtures/preload.js new file mode 100644 index 0000000..f692354 --- /dev/null +++ b/test/js/fixtures/preload.js @@ -0,0 +1,3 @@ +'use strict'; +// Preloaded with -r / NODE_OPTIONS by test_host.js. +globalThis.PRELOADED = 42; diff --git a/test/js/test_host.js b/test/js/test_host.js new file mode 100644 index 0000000..4695d5d --- /dev/null +++ b/test/js/test_host.js @@ -0,0 +1,115 @@ +'use strict'; +// The executable's Node.js-compatible host features used by the test suites: +// child_process (spawnSync, spawn), -e, -r / NODE_OPTIONS, process.env. +// Every child is this same executable, so the test runs on every platform; +// it passes under Node.js 22 as well: +// +// quickjs-napi test/js/test_host.js +// node test/js/test_host.js + +const { spawnSync, spawn } = require('child_process'); + +let failures = 0; +function check(cond, what) { + if (!cond) { + failures++; + console.log(`FAIL: ${what}`); + } +} + +const exe = process.execPath; +const run = (args, options) => + spawnSync(exe, args, Object.assign({ encoding: 'utf8' }, options)); + +// spawnSync: exit code, both streams, process.argv with -e. +{ + const r = run(['-e', 'console.log(process.argv.length, process.argv[1]);' + + 'console.error("to stderr"); process.exit(3)', 'arg']); + check(r.status === 3 && r.signal === null, `exit status 3 (got ${r.status})`); + check(r.stdout === '2 arg\n', `-e argv (got ${JSON.stringify(r.stdout)})`); + check(r.stderr === 'to stderr\n', 'stderr captured'); + check(Array.isArray(r.output) && r.output[1] === r.stdout && + r.output[2] === r.stderr, 'output array'); + check(typeof r.pid === 'number' && r.pid > 0, 'pid'); +} + +// Buffers without encoding. +{ + const r = spawnSync(exe, ['-e', 'console.log("x")']); + check(Buffer.isBuffer(r.stdout) && r.stdout.toString() === 'x\n', + 'stdout is a Buffer without encoding'); +} + +// A program that does not exist. +{ + const r = spawnSync(exe + '-does-not-exist', []); + check(r.error instanceof Error && r.error.code === 'ENOENT', + `ENOENT (got ${r.error && r.error.code})`); + check(r.status === null, 'no status without a process'); +} + +// timeout: the child is killed with SIGTERM. +{ + const r = run(['-e', 'setTimeout(() => {}, 20000)'], { timeout: 200 }); + check(r.error && r.error.code === 'ETIMEDOUT', + `ETIMEDOUT (got ${r.error && r.error.code})`); + check(r.signal === 'SIGTERM', `killed by SIGTERM (got ${r.signal})`); +} + +// process.env, passed on to the child (env option). +{ + const env = Object.assign({}, process.env, { QJSNAPI_TEST_VAR: 'value 1' }); + const r = run(['-e', 'console.log(process.env.QJSNAPI_TEST_VAR)'], { env }); + check(r.stdout === 'value 1\n', `env (got ${JSON.stringify(r.stdout)})`); + check(typeof process.env.PATH === 'string' || + typeof process.env.Path === 'string', 'process.env has PATH'); +} + +// --require, from the command line and from NODE_OPTIONS (where options +// only Node.js knows are ignored). +{ + const preload = `${__dirname}/fixtures/preload.js`; + const a = run(['-r', preload, '-e', 'console.log(globalThis.PRELOADED)']); + check(a.stdout === '42\n', `-r (got ${JSON.stringify(a.stdout)} ${a.stderr})`); + const env = Object.assign({}, process.env, { + NODE_OPTIONS: `--max-old-space-size=100 --require=${preload}` + }); + const b = run(['-e', 'console.log(globalThis.PRELOADED)'], { env }); + check(b.stdout === '42\n', + `NODE_OPTIONS --require (got ${JSON.stringify(b.stdout)} ${b.stderr})`); +} + +// spawn: data, then 'exit', then 'close'; kill(). +const events = []; +const child = spawn(exe, ['-e', 'console.log("async child")']); +child.stdout.setEncoding('utf8'); +child.stdout.on('data', (d) => events.push(`data:${d.trim()}`)); +child.on('exit', (code) => events.push(`exit:${code}`)); +child.on('close', (code) => { + events.push(`close:${code}`); + check(events.join(' ') === 'data:async child exit:0 close:0', + `spawn events (got ${events.join(' ')})`); + const sleeper = spawn(exe, ['-e', 'setTimeout(() => {}, 20000)'], + { stdio: 'ignore' }); + sleeper.on('close', (code, signal) => { + check(code === null && signal === 'SIGTERM', + `kill (got ${code} ${signal})`); + check(sleeper.kill() === false, 'kill() after the exit is false'); + // A spawn failure is an 'error' event. + const bad = spawn(exe + '-does-not-exist', []); + bad.on('error', (e) => { + check(e.code === 'ENOENT', `spawn ENOENT (got ${e.code})`); + finish(); + }); + }); + check(sleeper.kill() === true, 'kill() of a running child'); +}); + +function finish() { + if (failures) { + console.log(`${failures} failure(s)`); + process.exitCode = 1; + } else { + console.log('ok'); + } +} diff --git a/test/lsan.supp b/test/lsan.supp index e1f30c9..523735b 100644 --- a/test/lsan.supp +++ b/test/lsan.supp @@ -1,12 +1,24 @@ -# LeakSanitizer suppressions for the vendored Node.js tests (QJSNAPI_SANITIZE). +# LeakSanitizer suppressions for the vendored Node.js and node-addon-api tests +# (QJSNAPI_SANITIZE). # -# Only memory that a Node.js test leaks by design, in addon code, belongs -# here. References and async work items the addon never deletes are freed -# with the env (qn_env_free_orphan_refs, qn_env_free_works), so they need no -# entry; Node.js leaks them. +# Only memory that a test leaks by design, in addon code, belongs here. +# References and async work items the addon never deletes are freed with the +# env (qn_env_free_orphan_refs, qn_env_free_works), so they need no entry; +# Node.js leaks them. # node-api/test_env_teardown_gc/binding.c: MyObject_fini runs at teardown, # when JavaScript can no longer run; napi_get_named_property fails (as in # Node.js) and NODE_API_CALL_RETURN_VOID returns before freeing the # malloc'ed MyObject. leak:test_env_teardown_gc/binding.c + +# node-addon-api test addons (test/node-addon-api/test), leaks of the tests +# or of node-addon-api itself, as under Node.js: +# - `new` without delete in the test code. +leak:node-addon-api/test/basic_types/boolean.cc +leak:node-addon-api/test/function_reference.cc +leak:node-addon-api/test/object/object.cc +# - Napi::ThreadSafeFunction: the CallbackWrapper of a call is deleted only +# by CallJS after the callback returns normally, never when the function +# is closing (call_js_cb with a NULL env) or the callback throws. +leak:node-addon-api/test/threadsafe_function/ diff --git a/test/node-addon-api/LICENSE.md b/test/node-addon-api/LICENSE.md new file mode 100644 index 0000000..819d91a --- /dev/null +++ b/test/node-addon-api/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2017 [Node.js API collaborators](https://github.com/nodejs/node-addon-api#collaborators) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/test/node-addon-api/NODE_ADDON_API_VERSION b/test/node-addon-api/NODE_ADDON_API_VERSION new file mode 100644 index 0000000..32c861f --- /dev/null +++ b/test/node-addon-api/NODE_ADDON_API_VERSION @@ -0,0 +1 @@ +8.9.2 diff --git a/test/node-addon-api/harness/README.md b/test/node-addon-api/harness/README.md new file mode 100644 index 0000000..2a575ad --- /dev/null +++ b/test/node-addon-api/harness/README.md @@ -0,0 +1,66 @@ +# node-addon-api test suite + +`test/node-addon-api` holds the headers (`napi.h`, `napi-inl.h`, +`napi-inl.deprecated.h`), the license and the `test/` directory of +node-addon-api (version in `NODE_ADDON_API_VERSION`), copied by + +```sh +python3 tools/sync_node_addon_api.py +``` + +which also applies the patches listed in the script and writes `tests.cmake`. +Everything there except this `harness/` directory is regenerated by the sync. + +`cmake/node_addon_api_tests.cmake` (option `QJSNAPI_NODE_ADDON_API_TESTS`, +ON by default) builds the eight bindings of `test/binding.gyp` with the +defines of `node_addon_api.gyp` / `common.gypi` (`NAPI_VERSION=10`, C++ +exceptions on or off) into `build//node-addon-api-tests/test/build/Release`, +and registers one CTest per test module, named `naa/`: + +```sh +ctest --preset unix-debug -R naa/ +``` + +## Harness (this directory) + +| File | | +|---|---| +| `common/index.js` | replaces upstream `test/common/index.js` (which needs readline, os and fs/promises): `mustCall`, `runTest` over the four bindings (`binding`, `binding_noexcept`, `binding_noexcept_maybe`, `binding_custom_namespace`), `runTestInChildProcess` with `child_process.spawnSync` and `-e` | +| `run.js` | runs one module, as upstream `test/index.js` does for all of them (the module name is removed from `process.argv`: some tests decide from it whether they run as a child process) | +| `preload.js` | loaded with `NODE_OPTIONS=--require=...`, so that the child processes the tests start get it too: registers `assert` (`test/node/common/assert.js`) and sets `process.versions.node`, which the tests read | +| `index.js` | stand-in for the package's `index.js` (`needsFlag: false`), required by `test/napi_child.js` | + +## Not run + +| Module | Reason | +|---|---| +| `addon_build`, `require_basic_finalizers` | not copied: they build an addon with `npm install` | +| `exports` | checks the npm package's `index.js` (semver, package.json), not Node-API | +| `objectwrap_worker_thread`, `error_terminating_environment` | need `worker_threads` | + +## Patches (see `PATCHES` in the sync script) + +| Module | Patch | +|---|---| +| `async_context`, `async_progress_worker`, `async_progress_queue_worker`, `async_worker`, `callbackscope` | no `async_hooks`: the tests take their path for Node.js < 8, which runs the same native code without checking hook events | +| `async_worker` | in that path, `{}` instead of a `null` resource: the binding built with `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` turns `null` into a fatal error (Node.js never runs that path) | +| `function_reference` | the `async_hooks` part (`canCallAsyncFunctionWithDifferentOverloads`) is removed | +| `array_buffer` | no WebAssembly: the buffer is detached with `ArrayBuffer.prototype.transfer()` instead of `WebAssembly.Memory.grow()` | +| `object/object_freeze_seal` | V8 error messages matched by regular expression: `TypeError` is checked instead | + +## Notes + +- `async_progress_worker` runs alone (`RUN_SERIAL`): its + `SignalAfterProgressTestWorker` case is racy upstream (Send then Signal + from the worker thread; if the loop thread handles the first call in + between, the second sees no data), under Node.js as well. +- The bindings are compiled with `-fno-sanitize=alignment`: + `DataView::ReadData` in `napi-inl.h` reads through misaligned pointers. +- `test/lsan.supp` suppresses the leaks of the test code and of + `Napi::ThreadSafeFunction` (its call wrappers are deleted only when the + callback returns normally), as under Node.js. +- Running the suite found three differences that were fixed in the runtime: + `napi_define_class` with an instance key defined twice (V8 templates + replace), weak references to objects that QuickJS freed at once (kept + objects, see the README), and `process.exit()` tearing the environment + down (Node.js does not). diff --git a/test/node-addon-api/harness/common/index.js b/test/node-addon-api/harness/common/index.js new file mode 100644 index 0000000..89ab9e7 --- /dev/null +++ b/test/node-addon-api/harness/common/index.js @@ -0,0 +1,107 @@ +'use strict'; +// quickjs-napi replacement for node-addon-api's test/common/index.js (the +// upstream file needs readline, os and fs/promises). Same exports, same +// semantics for the parts the tests use; async_hooks helpers are absent. +const assert = require('assert'); + +const mustCallChecks = []; + +function runCallChecks (exitCode) { + if (exitCode !== 0) return; + const failed = mustCallChecks.filter((c) => + 'minimum' in c ? c.actual < c.minimum : c.actual !== c.exact); + for (const c of failed) { + console.log('Mismatched %s function calls. Expected %s, actual %d.', + c.name, 'minimum' in c ? `at least ${c.minimum}` : `exactly ${c.exact}`, + c.actual); + console.log(c.stack.split('\n').slice(2).join('\n')); + } + if (failed.length) process.exit(1); +} + +function _mustCallInner (fn, criteria, field) { + if (typeof fn === 'number') { + criteria = fn; + fn = () => {}; + } else if (fn === undefined) { + fn = () => {}; + } + if (criteria === undefined) criteria = 1; + if (typeof criteria !== 'number') { + throw new TypeError(`Invalid ${field} value: ${criteria}`); + } + const context = { + [field]: criteria, + actual: 0, + stack: (new Error()).stack, + name: fn.name || '' + }; + if (mustCallChecks.length === 0) process.on('exit', runCallChecks); + mustCallChecks.push(context); + return function () { + context.actual++; + return fn.apply(this, arguments); + }; +} + +exports.mustCall = (fn, exact) => _mustCallInner(fn, exact, 'exact'); +exports.mustCallAtLeast = (fn, minimum) => + _mustCallInner(fn, minimum, 'minimum'); +exports.mustNotCall = (msg) => function mustNotCall () { + assert.fail(msg || 'function should not have been called'); +}; + +// CMake builds the bindings into test/build/Release whatever the build type. +exports.whichBuildType = async () => 'Release'; + +const variants = ['binding', 'binding_noexcept', 'binding_noexcept_maybe', + 'binding_custom_namespace']; +const bindingPaths = (buildType) => + variants.map((v) => `${__dirname}/../build/${buildType}/${v}.node`); + +// As upstream, the first await defers the test until the requiring module +// has finished evaluating (its later `const` declarations are initialized). +exports.runTest = async function (test, buildType) { + buildType = buildType || await exports.whichBuildType(); + for (const item of bindingPaths(buildType)) { + await Promise.resolve(test(require(item), { bindingPath: item })) + .finally(exports.mustCall()); + } +}; + +exports.runTestWithBindingPath = async function (test, buildType) { + buildType = buildType || await exports.whichBuildType(); + for (const item of bindingPaths(buildType)) await test(item); +}; + +exports.runTestWithBuildType = async function (test, buildType) { + buildType = buildType || await exports.whichBuildType(); + await Promise.resolve(test(buildType)).finally(exports.mustCall()); +}; + +// Upstream spawns `node -e` with readline over stderr; spawnSync gives the +// same result: exit code, signal and the expected stderr lines. +exports.runTestInChildProcess = function ({ suite, testName, expectedStderr, execArgv }) { + const { spawnSync } = require('child_process'); + return exports.runTestWithBindingPath((bindingName) => { + const suitePath = `${__dirname}/../child_processes/${suite}`; + const child = spawnSync(process.execPath, [ + '--expose-gc', + ...(execArgv ?? []), + '-e', + `require(${JSON.stringify(suitePath)}).${testName}(require(${JSON.stringify(bindingName)}))` + ], { encoding: 'utf8' }); + const stderr = (child.stderr || '').split(/\r?\n/).filter((l) => l !== ''); + const actual = { stderr, code: child.status, signal: child.signal }; + const expected = { stderr: expectedStderr, code: 0, signal: null }; + if (!expectedStderr) { + delete actual.stderr; + delete expected.stderr; + } else { + actual.stderr = actual.stderr.filter((line) => expectedStderr.includes(line)); + } + assert.deepStrictEqual(actual, expected, + `Assertion for child process test ${suite}.${testName} failed:\n` + + stderr.map((l) => `from child process: ${l}`).join('\n')); + }); +}; diff --git a/test/node-addon-api/harness/index.js b/test/node-addon-api/harness/index.js new file mode 100644 index 0000000..f9f0da3 --- /dev/null +++ b/test/node-addon-api/harness/index.js @@ -0,0 +1,7 @@ +'use strict'; +// Stand-in for node-addon-api's package entry point (index.js), required by +// test/napi_child.js: the Node-API module flag is never needed. +module.exports = { + isNodeApiBuiltin: true, + needsFlag: false +}; diff --git a/test/node-addon-api/harness/preload.js b/test/node-addon-api/harness/preload.js new file mode 100644 index 0000000..ac88301 --- /dev/null +++ b/test/node-addon-api/harness/preload.js @@ -0,0 +1,7 @@ +'use strict'; +// Loaded with --require (NODE_OPTIONS, so child processes load it too) +// before every node-addon-api test script. +require('module').registerBuiltin('assert', require('./qn_assert.js')); +// The tests read the Node.js major version (process.versions.node is not +// set by quickjs-napi, see README): the release whose behaviour is reproduced. +process.versions.node = process.version.slice(1); diff --git a/test/node-addon-api/harness/run.js b/test/node-addon-api/harness/run.js new file mode 100644 index 0000000..93ba680 --- /dev/null +++ b/test/node-addon-api/harness/run.js @@ -0,0 +1,15 @@ +'use strict'; +// quickjs-napi runner for one node-addon-api test module, the per-module +// equivalent of upstream test/index.js (preload.js is loaded first): +// NODE_OPTIONS=--require=.../test/preload.js \ +// quickjs-napi --expose-gc test/run.js +// Requiring the module runs it; it exports a promise (or nothing). The +// module name is taken out of process.argv: some tests decide from +// process.argv whether they run as a child process. +const name = process.argv.splice(2, 1)[0]; +(async () => { + await require('./' + name); +})().catch((error) => { + console.log(error && error.stack ? `${error}\n${error.stack}` : error); + process.exit(1); +}); diff --git a/test/node-addon-api/napi-inl.deprecated.h b/test/node-addon-api/napi-inl.deprecated.h new file mode 100644 index 0000000..3ddbb2e --- /dev/null +++ b/test/node-addon-api/napi-inl.deprecated.h @@ -0,0 +1,186 @@ +#ifndef SRC_NAPI_INL_DEPRECATED_H_ +#define SRC_NAPI_INL_DEPRECATED_H_ + +//////////////////////////////////////////////////////////////////////////////// +// PropertyDescriptor class +//////////////////////////////////////////////////////////////////////////////// + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, + Getter getter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({getter, nullptr}); + + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), getter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + napi_value name, + Getter getter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({getter, nullptr}); + + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Name name, Getter getter, napi_property_attributes attributes, void* data) { + napi_value nameValue = name; + return PropertyDescriptor::Accessor(nameValue, getter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::AccessorCallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({getter, setter, nullptr}); + + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), getter, setter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + napi_value name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::AccessorCallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({getter, setter, nullptr}); + + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + napi_value nameValue = name; + return PropertyDescriptor::Accessor( + nameValue, getter, setter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + const char* utf8name, + Callable cb, + napi_property_attributes attributes, + void* /*data*/) { + using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({cb, nullptr}); + + return PropertyDescriptor({utf8name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return Function(utf8name.c_str(), cb, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + napi_value name, + Callable cb, + napi_property_attributes attributes, + void* /*data*/) { + using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({cb, nullptr}); + + return PropertyDescriptor({nullptr, + name, + CbData::Wrapper, + nullptr, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + Name name, Callable cb, napi_property_attributes attributes, void* data) { + napi_value nameValue = name; + return PropertyDescriptor::Function(nameValue, cb, attributes, data); +} + +#endif // !SRC_NAPI_INL_DEPRECATED_H_ diff --git a/test/node-addon-api/napi-inl.h b/test/node-addon-api/napi-inl.h new file mode 100644 index 0000000..4a1c18b --- /dev/null +++ b/test/node-addon-api/napi-inl.h @@ -0,0 +1,7250 @@ +#ifndef SRC_NAPI_INL_H_ +#define SRC_NAPI_INL_H_ + +//////////////////////////////////////////////////////////////////////////////// +// Node-API C++ Wrapper Classes +// +// Inline header-only implementations for "Node-API" ABI-stable C APIs for +// Node.js. +//////////////////////////////////////////////////////////////////////////////// + +// Note: Do not include this file directly! Include "napi.h" instead. +// This should be a no-op and is intended for better IDE integration. +#include "napi.h" + +#include +#include +#include +#if NAPI_HAS_THREADS +#include +#endif // NAPI_HAS_THREADS +#include +#include +#include + +#if defined(__clang__) || defined(__GNUC__) +#define NAPI_NO_SANITIZE_VPTR __attribute__((no_sanitize("vptr"))) +#else +#define NAPI_NO_SANITIZE_VPTR +#endif + +namespace Napi { + +#ifdef NAPI_CPP_CUSTOM_NAMESPACE +namespace NAPI_CPP_CUSTOM_NAMESPACE { +#endif + +// Helpers to handle functions exposed from C++ and internal constants. +namespace details { + +// New napi_status constants not yet available in all supported versions of +// Node.js releases. Only necessary when they are used in napi.h and napi-inl.h. +constexpr int napi_no_external_buffers_allowed = 22; + +template +inline void default_basic_finalizer(node_addon_api_basic_env /*env*/, + void* data, + void* /*hint*/) { + delete static_cast(data); +} + +// Attach a data item to an object and delete it when the object gets +// garbage-collected. +// TODO: Replace this code with `napi_add_finalizer()` whenever it becomes +// available on all supported versions of Node.js. +template < + typename FreeType, + node_addon_api_basic_finalize finalizer = default_basic_finalizer> +inline napi_status AttachData(napi_env env, + napi_value obj, + FreeType* data, + void* hint = nullptr) { + napi_status status; +#if (NAPI_VERSION < 5) + napi_value symbol, external; + status = napi_create_symbol(env, nullptr, &symbol); + if (status == napi_ok) { + status = napi_create_external(env, data, finalizer, hint, &external); + if (status == napi_ok) { + napi_property_descriptor desc = {nullptr, + symbol, + nullptr, + nullptr, + nullptr, + external, + napi_default, + nullptr}; + status = napi_define_properties(env, obj, 1, &desc); + } + } +#else // NAPI_VERSION >= 5 + status = napi_add_finalizer(env, obj, data, finalizer, hint, nullptr); +#endif + return status; +} + +// For use in JS to C++ callback wrappers to catch any Napi::Error exceptions +// and rethrow them as JavaScript exceptions before returning from the callback. +template +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL +inline napi_value WrapCallback(napi_env env, Callable callback) { +#else +inline napi_value WrapCallback(napi_env, Callable callback) { +#endif +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + try { + return callback(); + } catch (const Error& e) { + e.ThrowAsJavaScriptException(); + return nullptr; + } +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL + catch (const std::exception& e) { + Napi::Error::New(env, e.what()).ThrowAsJavaScriptException(); + return nullptr; + } catch (...) { + Napi::Error::New(env, "A native exception was thrown") + .ThrowAsJavaScriptException(); + return nullptr; + } +#endif // NODE_ADDON_API_CPP_EXCEPTIONS_ALL +#else // NODE_ADDON_API_CPP_EXCEPTIONS + // When C++ exceptions are disabled, errors are immediately thrown as JS + // exceptions, so there is no need to catch and rethrow them here. + return callback(); +#endif // NODE_ADDON_API_CPP_EXCEPTIONS +} + +// For use in JS to C++ void callback wrappers to catch any Napi::Error +// exceptions and rethrow them as JavaScript exceptions before returning from +// the callback. +template +inline void WrapVoidCallback(Callable callback) { +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + try { + callback(); + } catch (const Error& e) { + e.ThrowAsJavaScriptException(); + } +#else // NAPI_CPP_EXCEPTIONS + // When C++ exceptions are disabled, errors are immediately thrown as JS + // exceptions, so there is no need to catch and rethrow them here. + callback(); +#endif // NAPI_CPP_EXCEPTIONS +} + +// For use in JS to C++ void callback wrappers to catch _any_ thrown exception +// and rethrow them as JavaScript exceptions before returning from the callback, +// wrapping in an Napi::Error as needed. +template +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL +inline void WrapVoidCallback(napi_env env, Callable callback) { +#else +inline void WrapVoidCallback(napi_env, Callable callback) { +#endif +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + try { + callback(); + } catch (const Error& e) { + e.ThrowAsJavaScriptException(); + } +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL + catch (const std::exception& e) { + Napi::Error::New(env, e.what()).ThrowAsJavaScriptException(); + } catch (...) { + Napi::Error::New(env, "A native exception was thrown") + .ThrowAsJavaScriptException(); + } +#endif // NODE_ADDON_API_CPP_EXCEPTIONS_ALL +#else + // When C++ exceptions are disabled, there is no need to catch and rethrow C++ + // exceptions. JS errors should be thrown with + // `Error::ThrowAsJavaScriptException`. + callback(); +#endif // NODE_ADDON_API_CPP_EXCEPTIONS +} + +template +struct CallbackData { + static inline napi_value Wrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + CallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->callback(callbackInfo); + }); + } + + Callable callback; + void* data; +}; + +template +struct CallbackData { + static inline napi_value Wrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + CallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->callback(callbackInfo); + return nullptr; + }); + } + + Callable callback; + void* data; +}; + +template +napi_value TemplatedVoidCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback(env, [&] { + CallbackInfo cbInfo(env, info); + Callback(cbInfo); + return nullptr; + }); +} + +template +napi_value TemplatedCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback(env, [&] { + CallbackInfo cbInfo(env, info); + // MSVC requires to copy 'Callback' function pointer to a local variable + // before invoking it. + auto callback = Callback; + return callback(cbInfo); + }); +} + +template +napi_value TemplatedInstanceCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback(env, [&] { + CallbackInfo cbInfo(env, info); + T* instance = T::Unwrap(cbInfo.This().As()); + return instance ? (instance->*UnwrapCallback)(cbInfo) : Napi::Value(); + }); +} + +template +napi_value TemplatedInstanceVoidCallback(napi_env env, napi_callback_info info) + NAPI_NOEXCEPT { + return details::WrapCallback(env, [&] { + CallbackInfo cbInfo(env, info); + T* instance = T::Unwrap(cbInfo.This().As()); + if (instance) (instance->*UnwrapCallback)(cbInfo); + return nullptr; + }); +} + +template +struct FinalizeData { +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + template >> +#endif + static inline void Wrapper(node_addon_api_basic_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback([&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(env, static_cast(data)); + delete finalizeData; + }); + } + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + template >, + typename = void> + static inline void Wrapper(node_addon_api_basic_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { +#ifdef NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS + static_assert(false, + "NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS defined: Finalizer " + "must be basic."); +#endif + napi_status status = + node_api_post_finalizer(env, WrapperGC, data, finalizeHint); + NAPI_FATAL_IF_FAILED( + status, "FinalizeData::Wrapper", "node_api_post_finalizer failed"); + } +#endif + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + template >> +#endif + static inline void WrapperWithHint(node_addon_api_basic_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback([&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(env, static_cast(data), finalizeData->hint); + delete finalizeData; + }); + } + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + template >, + typename = void> + static inline void WrapperWithHint(node_addon_api_basic_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { +#ifdef NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS + static_assert(false, + "NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS defined: Finalizer " + "must be basic."); +#endif + napi_status status = + node_api_post_finalizer(env, WrapperGCWithHint, data, finalizeHint); + NAPI_FATAL_IF_FAILED( + status, "FinalizeData::Wrapper", "node_api_post_finalizer failed"); + } +#endif + + static inline void WrapperGCWithoutData(napi_env env, + void* /*data*/, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback(env, [&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(env); + delete finalizeData; + }); + } + + static inline void WrapperGC(napi_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback(env, [&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(env, static_cast(data)); + delete finalizeData; + }); + } + + static inline void WrapperGCWithHint(napi_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback(env, [&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(env, static_cast(data), finalizeData->hint); + delete finalizeData; + }); + } + + Finalizer callback; + Hint* hint; +}; + +#if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) +template , + typename FinalizerDataType = void> +struct ThreadSafeFinalize { + static inline void Wrapper(napi_env env, + void* rawFinalizeData, + void* /* rawContext */) { + if (rawFinalizeData == nullptr) return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback(Env(env)); + delete finalizeData; + } + + static inline void FinalizeWrapperWithData(napi_env env, + void* rawFinalizeData, + void* /* rawContext */) { + if (rawFinalizeData == nullptr) return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback(Env(env), finalizeData->data); + delete finalizeData; + } + + static inline void FinalizeWrapperWithContext(napi_env env, + void* rawFinalizeData, + void* rawContext) { + if (rawFinalizeData == nullptr) return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback(Env(env), static_cast(rawContext)); + delete finalizeData; + } + + static inline void FinalizeFinalizeWrapperWithDataAndContext( + napi_env env, void* rawFinalizeData, void* rawContext) { + if (rawFinalizeData == nullptr) return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback( + Env(env), finalizeData->data, static_cast(rawContext)); + delete finalizeData; + } + + FinalizerDataType* data; + Finalizer callback; +}; + +template +inline typename std::enable_if(nullptr)>::type +CallJsWrapper(napi_env env, napi_value jsCallback, void* context, void* data) { + details::WrapVoidCallback(env, [&]() { + call(env, + Function(env, jsCallback), + static_cast(context), + static_cast(data)); + }); +} + +template +inline typename std::enable_if(nullptr)>::type +CallJsWrapper(napi_env env, + napi_value jsCallback, + void* /*context*/, + void* /*data*/) { + details::WrapVoidCallback(env, [&]() { + if (jsCallback != nullptr) { + Function(env, jsCallback).Call(0, nullptr); + } + }); +} + +#if NAPI_VERSION > 4 + +template +napi_value DefaultCallbackWrapper(napi_env /*env*/, std::nullptr_t /*cb*/) { + return nullptr; +} + +template +napi_value DefaultCallbackWrapper(napi_env /*env*/, Napi::Function cb) { + return cb; +} + +#else +template +napi_value DefaultCallbackWrapper(napi_env env, Napi::Function cb) { + if (cb.IsEmpty()) { + return TSFN::EmptyFunctionFactory(env); + } + return cb; +} +#endif // NAPI_VERSION > 4 +#endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS + +template +struct AccessorCallbackData { + static inline napi_value GetterWrapper(napi_env env, + napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + AccessorCallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->getterCallback(callbackInfo); + }); + } + + static inline napi_value SetterWrapper(napi_env env, + napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + AccessorCallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->setterCallback(callbackInfo); + return nullptr; + }); + } + + Getter getterCallback; + Setter setterCallback; + void* data; +}; + +// Debugging-purpose C++-style variant of sprintf(). +inline std::string StringFormat(const char* format, ...) { + std::string result; + va_list args; + va_start(args, format); + int len = vsnprintf(nullptr, 0, format, args); + result.resize(len); + vsnprintf(&result[0], len + 1, format, args); + va_end(args); + return result; +} + +template +class HasExtendedFinalizer { + private: + template + struct SFINAE {}; + template + static char test(SFINAE*); + template + static int test(...); + + public: + static constexpr bool value = sizeof(test(0)) == sizeof(char); +}; + +template +class HasBasicFinalizer { + private: + template + struct SFINAE {}; + template + static char test(SFINAE*); + template + static int test(...); + + public: + static constexpr bool value = sizeof(test(0)) == sizeof(char); +}; + +} // namespace details + +#ifndef NODE_ADDON_API_DISABLE_DEPRECATED +#include "napi-inl.deprecated.h" +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED + +//////////////////////////////////////////////////////////////////////////////// +// Module registration +//////////////////////////////////////////////////////////////////////////////// + +// Register an add-on based on an initializer function. +#define NODE_API_MODULE(modname, regfunc) \ + static napi_value __napi_##regfunc(napi_env env, napi_value exports) { \ + return Napi::RegisterModule(env, exports, regfunc); \ + } \ + NAPI_MODULE(modname, __napi_##regfunc) + +// Register an add-on based on a subclass of `Addon` with a custom Node.js +// module name. +#define NODE_API_NAMED_ADDON(modname, classname) \ + static napi_value __napi_##classname(napi_env env, napi_value exports) { \ + return Napi::RegisterModule(env, exports, &classname::Init); \ + } \ + NAPI_MODULE(modname, __napi_##classname) + +// Register an add-on based on a subclass of `Addon` with the Node.js module +// name given by node-gyp from the `target_name` in binding.gyp. +#define NODE_API_ADDON(classname) \ + NODE_API_NAMED_ADDON(NODE_GYP_MODULE_NAME, classname) + +// Adapt the NAPI_MODULE registration function: +// - Wrap the arguments in NAPI wrappers. +// - Catch any NAPI errors and rethrow as JS exceptions. +inline napi_value RegisterModule(napi_env env, + napi_value exports, + ModuleRegisterCallback registerCallback) { + return details::WrapCallback(env, [&] { + return napi_value( + registerCallback(Napi::Env(env), Napi::Object(env, exports))); + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// Maybe class +//////////////////////////////////////////////////////////////////////////////// + +template +bool Maybe::IsNothing() const { + return !_has_value; +} + +template +bool Maybe::IsJust() const { + return _has_value; +} + +template +void Maybe::Check() const { + NAPI_CHECK(IsJust(), "Napi::Maybe::Check", "Maybe value is Nothing."); +} + +template +T Maybe::Unwrap() const { + NAPI_CHECK(IsJust(), "Napi::Maybe::Unwrap", "Maybe value is Nothing."); + return _value; +} + +template +T Maybe::UnwrapOr(const T& default_value) const { + return _has_value ? _value : default_value; +} + +template +bool Maybe::UnwrapTo(T* out) const { + if (IsJust()) { + *out = _value; + return true; + }; + return false; +} + +template +bool Maybe::operator==(const Maybe& other) const { + return (IsJust() == other.IsJust()) && + (!IsJust() || Unwrap() == other.Unwrap()); +} + +template +bool Maybe::operator!=(const Maybe& other) const { + return !operator==(other); +} + +template +Maybe::Maybe() : _has_value(false) {} + +template +Maybe::Maybe(const T& t) : _has_value(true), _value(t) {} + +template +inline Maybe Nothing() { + return Maybe(); +} + +template +inline Maybe Just(const T& t) { + return Maybe(t); +} + +//////////////////////////////////////////////////////////////////////////////// +// BasicEnv / Env class +//////////////////////////////////////////////////////////////////////////////// + +inline BasicEnv::BasicEnv(node_addon_api_basic_env env) : _env(env) {} + +inline BasicEnv::operator node_addon_api_basic_env() const { + return _env; +} + +inline Env::Env(napi_env env) : BasicEnv(env) {} + +inline Env::operator napi_env() const { + return const_cast(_env); +} + +inline Object Env::Global() const { + napi_value value; + napi_status status = napi_get_global(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Object()); + return Object(*this, value); +} + +inline Value Env::Undefined() const { + napi_value value; + napi_status status = napi_get_undefined(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Value()); + return Value(*this, value); +} + +inline Value Env::Null() const { + napi_value value; + napi_status status = napi_get_null(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Value()); + return Value(*this, value); +} + +inline bool Env::IsExceptionPending() const { + bool result; + napi_status status = napi_is_exception_pending(*this, &result); + if (status != napi_ok) + result = false; // Checking for a pending exception shouldn't throw. + return result; +} + +inline Error Env::GetAndClearPendingException() const { + napi_value value; + napi_status status = napi_get_and_clear_last_exception(*this, &value); + if (status != napi_ok) { + // Don't throw another exception when failing to get the exception! + return Error(); + } + return Error(*this, value); +} + +inline MaybeOrValue Env::RunScript(const char* utf8script) const { + String script = String::New(*this, utf8script); + return RunScript(script); +} + +inline MaybeOrValue Env::RunScript(const std::string& utf8script) const { + return RunScript(utf8script.c_str()); +} + +inline MaybeOrValue Env::RunScript(String script) const { + napi_value result; + napi_status status = napi_run_script(*this, script, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + *this, status, Napi::Value(*this, result), Napi::Value); +} + +#if NAPI_VERSION > 2 +template +void BasicEnv::CleanupHook::Wrapper(void* data) NAPI_NOEXCEPT { + auto* cleanupData = static_cast< + typename Napi::BasicEnv::CleanupHook::CleanupData*>(data); + cleanupData->hook(); + delete cleanupData; +} + +template +void BasicEnv::CleanupHook::WrapperWithArg(void* data) + NAPI_NOEXCEPT { + auto* cleanupData = static_cast< + typename Napi::BasicEnv::CleanupHook::CleanupData*>(data); + cleanupData->hook(static_cast(cleanupData->arg)); + delete cleanupData; +} +#endif // NAPI_VERSION > 2 + +#if NAPI_VERSION > 5 +template fini> +inline void BasicEnv::SetInstanceData(T* data) const { + napi_status status = napi_set_instance_data( + _env, + data, + [](napi_env env, void* data, void*) { fini(env, static_cast(data)); }, + nullptr); + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::SetInstanceData", "invalid arguments"); +} + +template fini> +inline void BasicEnv::SetInstanceData(DataType* data, HintType* hint) const { + napi_status status = napi_set_instance_data( + _env, + data, + [](napi_env env, void* data, void* hint) { + fini(env, static_cast(data), static_cast(hint)); + }, + hint); + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::SetInstanceData", "invalid arguments"); +} + +template +inline T* BasicEnv::GetInstanceData() const { + void* data = nullptr; + + napi_status status = napi_get_instance_data(_env, &data); + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::GetInstanceData", "invalid arguments"); + + return static_cast(data); +} + +template +void BasicEnv::DefaultFini(Env, T* data) { + delete data; +} + +template +void BasicEnv::DefaultFiniWithHint(Env, DataType* data, HintType*) { + delete data; +} +#endif // NAPI_VERSION > 5 + +#if NAPI_VERSION > 8 +inline const char* BasicEnv::GetModuleFileName() const { + const char* result; + napi_status status = node_api_get_module_file_name(_env, &result); + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::GetModuleFileName", "invalid arguments"); + return result; +} +#endif // NAPI_VERSION > 8 +//////////////////////////////////////////////////////////////////////////////// +// Value class +//////////////////////////////////////////////////////////////////////////////// + +inline Value::Value() : _env(nullptr), _value(nullptr) {} + +inline Value::Value(napi_env env, napi_value value) + : _env(env), _value(value) {} + +inline Value::operator napi_value() const { + return _value; +} + +inline bool Value::operator==(const Value& other) const { + return StrictEquals(other); +} + +inline bool Value::operator!=(const Value& other) const { + return !this->operator==(other); +} + +inline bool Value::StrictEquals(const Value& other) const { + bool result; + napi_status status = napi_strict_equals(_env, *this, other, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline Napi::Env Value::Env() const { + return Napi::Env(_env); +} + +inline bool Value::IsEmpty() const { + return _value == nullptr; +} + +inline napi_valuetype Value::Type() const { + if (IsEmpty()) { + return napi_undefined; + } + + napi_valuetype type; + napi_status status = napi_typeof(_env, _value, &type); + NAPI_THROW_IF_FAILED(_env, status, napi_undefined); + return type; +} + +inline bool Value::IsUndefined() const { + return Type() == napi_undefined; +} + +inline bool Value::IsNull() const { + return Type() == napi_null; +} + +inline bool Value::IsBoolean() const { + return Type() == napi_boolean; +} + +inline bool Value::IsNumber() const { + return Type() == napi_number; +} + +#if NAPI_VERSION > 5 +inline bool Value::IsBigInt() const { + return Type() == napi_bigint; +} +#endif // NAPI_VERSION > 5 + +#if (NAPI_VERSION > 4) +inline bool Value::IsDate() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_date(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} +#endif + +inline bool Value::IsString() const { + return Type() == napi_string; +} + +inline bool Value::IsSymbol() const { + return Type() == napi_symbol; +} + +inline bool Value::IsArray() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_array(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsArrayBuffer() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_arraybuffer(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsTypedArray() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_typedarray(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsObject() const { + return Type() == napi_object || IsFunction(); +} + +inline bool Value::IsFunction() const { + return Type() == napi_function; +} + +inline bool Value::IsPromise() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_promise(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsDataView() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_dataview(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsBuffer() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_buffer(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsExternal() const { + return Type() == napi_external; +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +inline bool Value::IsSharedArrayBuffer() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = node_api_is_sharedarraybuffer(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} +#endif + +template +inline T Value::As() const { +#ifdef NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS + T::CheckCast(_env, _value); +#endif + return T(_env, _value); +} + +template +inline T Value::UnsafeAs() const { + return T(_env, _value); +} + +// static +inline void Value::CheckCast(napi_env /* env */, napi_value value) { + NAPI_CHECK(value != nullptr, "Value::CheckCast", "empty value"); +} + +inline MaybeOrValue Value::ToBoolean() const { + napi_value result; + napi_status status = napi_coerce_to_bool(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Boolean(_env, result), Napi::Boolean); +} + +inline MaybeOrValue Value::ToNumber() const { + napi_value result; + napi_status status = napi_coerce_to_number(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Number(_env, result), Napi::Number); +} + +inline MaybeOrValue Value::ToString() const { + napi_value result; + napi_status status = napi_coerce_to_string(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::String(_env, result), Napi::String); +} + +inline MaybeOrValue Value::ToObject() const { + napi_value result; + napi_status status = napi_coerce_to_object(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Object(_env, result), Napi::Object); +} + +//////////////////////////////////////////////////////////////////////////////// +// Boolean class +//////////////////////////////////////////////////////////////////////////////// + +inline Boolean Boolean::New(napi_env env, bool val) { + napi_value value; + napi_status status = napi_get_boolean(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, Boolean()); + return Boolean(env, value); +} + +inline void Boolean::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Boolean::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Boolean::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_boolean, "%d", "Boolean::CheckCast"); +} + +inline Boolean::Boolean() : Napi::Value() {} + +inline Boolean::Boolean(napi_env env, napi_value value) + : Napi::Value(env, value) {} + +inline Boolean::operator bool() const { + return Value(); +} + +inline bool Boolean::Value() const { + bool result; + napi_status status = napi_get_value_bool(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// Number class +//////////////////////////////////////////////////////////////////////////////// + +inline Number Number::New(napi_env env, double val) { + napi_value value; + napi_status status = napi_create_double(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, Number()); + return Number(env, value); +} + +inline void Number::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Number::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Number::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_number, "%d", "Number::CheckCast"); +} + +inline Number::Number() : Value() {} + +inline Number::Number(napi_env env, napi_value value) : Value(env, value) {} + +inline Number::operator int32_t() const { + return Int32Value(); +} + +inline Number::operator uint32_t() const { + return Uint32Value(); +} + +inline Number::operator int64_t() const { + return Int64Value(); +} + +inline Number::operator float() const { + return FloatValue(); +} + +inline Number::operator double() const { + return DoubleValue(); +} + +inline int32_t Number::Int32Value() const { + int32_t result; + napi_status status = napi_get_value_int32(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline uint32_t Number::Uint32Value() const { + uint32_t result; + napi_status status = napi_get_value_uint32(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline int64_t Number::Int64Value() const { + int64_t result; + napi_status status = napi_get_value_int64(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline float Number::FloatValue() const { + return static_cast(DoubleValue()); +} + +inline double Number::DoubleValue() const { + double result; + napi_status status = napi_get_value_double(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +#if NAPI_VERSION > 5 +//////////////////////////////////////////////////////////////////////////////// +// BigInt Class +//////////////////////////////////////////////////////////////////////////////// + +inline BigInt BigInt::New(napi_env env, int64_t val) { + napi_value value; + napi_status status = napi_create_bigint_int64(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline BigInt BigInt::New(napi_env env, uint64_t val) { + napi_value value; + napi_status status = napi_create_bigint_uint64(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline BigInt BigInt::New(napi_env env, + int sign_bit, + size_t word_count, + const uint64_t* words) { + napi_value value; + napi_status status = + napi_create_bigint_words(env, sign_bit, word_count, words, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline void BigInt::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "BigInt::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "BigInt::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_bigint, "%d", "BigInt::CheckCast"); +} + +inline BigInt::BigInt() : Value() {} + +inline BigInt::BigInt(napi_env env, napi_value value) : Value(env, value) {} + +inline int64_t BigInt::Int64Value(bool* lossless) const { + int64_t result; + napi_status status = + napi_get_value_bigint_int64(_env, _value, &result, lossless); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline uint64_t BigInt::Uint64Value(bool* lossless) const { + uint64_t result; + napi_status status = + napi_get_value_bigint_uint64(_env, _value, &result, lossless); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline size_t BigInt::WordCount() const { + size_t word_count; + napi_status status = + napi_get_value_bigint_words(_env, _value, nullptr, &word_count, nullptr); + NAPI_THROW_IF_FAILED(_env, status, 0); + return word_count; +} + +inline void BigInt::ToWords(int* sign_bit, + size_t* word_count, + uint64_t* words) { + napi_status status = + napi_get_value_bigint_words(_env, _value, sign_bit, word_count, words); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} +#endif // NAPI_VERSION > 5 + +#if (NAPI_VERSION > 4) +//////////////////////////////////////////////////////////////////////////////// +// Date Class +//////////////////////////////////////////////////////////////////////////////// + +inline Date Date::New(napi_env env, double val) { + napi_value value; + napi_status status = napi_create_date(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, Date()); + return Date(env, value); +} + +inline Date Date::New(napi_env env, std::chrono::system_clock::time_point tp) { + using namespace std::chrono; + auto ms = static_cast( + duration_cast(tp.time_since_epoch()).count()); + return Date::New(env, ms); +} + +inline void Date::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Date::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_date(env, value, &result); + NAPI_CHECK(status == napi_ok, "Date::CheckCast", "napi_is_date failed"); + NAPI_CHECK(result, "Date::CheckCast", "value is not date"); +} + +inline Date::Date() : Value() {} + +inline Date::Date(napi_env env, napi_value value) : Value(env, value) {} + +inline Date::operator double() const { + return ValueOf(); +} + +inline double Date::ValueOf() const { + double result; + napi_status status = napi_get_date_value(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Name class +//////////////////////////////////////////////////////////////////////////////// +inline void Name::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Name::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Name::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK(type == napi_string || type == napi_symbol, + "Name::CheckCast", + "value is not napi_string or napi_symbol, got %d.", + type); +} + +inline Name::Name() : Value() {} + +inline Name::Name(napi_env env, napi_value value) : Value(env, value) {} + +//////////////////////////////////////////////////////////////////////////////// +// String class +//////////////////////////////////////////////////////////////////////////////// + +inline String String::New(napi_env env, const std::string& val) { + return String::New(env, val.c_str(), val.size()); +} + +inline String String::New(napi_env env, const std::u16string& val) { + return String::New(env, val.c_str(), val.size()); +} + +inline String String::New(napi_env env, std::string_view val) { + return String::New(env, val.data(), val.size()); +} + +inline String String::New(napi_env env, const char* val) { + // TODO(@gabrielschulhof) Remove if-statement when core's error handling is + // available in all supported versions. + if (val == nullptr) { + // Throw an error that looks like it came from core. + NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String()); + } + napi_value value; + napi_status status = + napi_create_string_utf8(env, val, std::strlen(val), &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char16_t* val) { + napi_value value; + // TODO(@gabrielschulhof) Remove if-statement when core's error handling is + // available in all supported versions. + if (val == nullptr) { + // Throw an error that looks like it came from core. + NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String()); + } + napi_status status = + napi_create_string_utf16(env, val, std::u16string(val).size(), &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char* val, size_t length) { + napi_value value; + napi_status status = napi_create_string_utf8(env, val, length, &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char16_t* val, size_t length) { + napi_value value; + napi_status status = napi_create_string_utf16(env, val, length, &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline void String::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "String::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "String::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_string, "%d", "String::CheckCast"); +} + +inline String::String() : Name() {} + +inline String::String(napi_env env, napi_value value) : Name(env, value) {} + +inline String::operator std::string() const { + return Utf8Value(); +} + +inline String::operator std::u16string() const { + return Utf16Value(); +} + +inline std::string String::Utf8Value() const { + size_t length; + napi_status status = + napi_get_value_string_utf8(_env, _value, nullptr, 0, &length); + NAPI_THROW_IF_FAILED(_env, status, ""); + + std::string value; + value.reserve(length + 1); + value.resize(length); + status = napi_get_value_string_utf8( + _env, _value, &value[0], value.capacity(), nullptr); + NAPI_THROW_IF_FAILED(_env, status, ""); + return value; +} + +inline std::u16string String::Utf16Value() const { + size_t length; + napi_status status = + napi_get_value_string_utf16(_env, _value, nullptr, 0, &length); + NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); + + std::u16string value; + value.reserve(length + 1); + value.resize(length); + status = napi_get_value_string_utf16( + _env, _value, &value[0], value.capacity(), nullptr); + NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); + return value; +} + +//////////////////////////////////////////////////////////////////////////////// +// Symbol class +//////////////////////////////////////////////////////////////////////////////// + +inline Symbol Symbol::New(napi_env env, const char* description) { + napi_value descriptionValue = description != nullptr + ? String::New(env, description) + : static_cast(nullptr); + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, const std::string& description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, std::string_view description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, String description) { + napi_value descriptionValue = description; + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, napi_value description) { + napi_value value; + napi_status status = napi_create_symbol(env, description, &value); + NAPI_THROW_IF_FAILED(env, status, Symbol()); + return Symbol(env, value); +} + +inline MaybeOrValue Symbol::WellKnown(napi_env env, + const std::string& name) { + // No need to check if the return value is a symbol or undefined. + // Well known symbols are definite and it is an develop time error + // if the symbol does not exist. +#if defined(NODE_ADDON_API_ENABLE_MAYBE) + Value symbol_obj; + Value symbol_value; + if (Napi::Env(env).Global().Get("Symbol").UnwrapTo(&symbol_obj) && + symbol_obj.As().Get(name).UnwrapTo(&symbol_value)) { + return Just(symbol_value.UnsafeAs()); + } + return Nothing(); +#else + return Napi::Env(env) + .Global() + .Get("Symbol") + .As() + .Get(name) + .UnsafeAs(); +#endif +} + +inline MaybeOrValue Symbol::For(napi_env env, + const std::string& description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::For(env, descriptionValue); +} + +inline MaybeOrValue Symbol::For(napi_env env, + std::string_view description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::For(env, descriptionValue); +} + +template > +inline MaybeOrValue Symbol::For(napi_env env, T&& description) { + std::string_view descriptionView = std::forward(description); + return Symbol::For(env, descriptionView); +} + +inline MaybeOrValue Symbol::For(napi_env env, const char* description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::For(env, descriptionValue); +} + +inline MaybeOrValue Symbol::For(napi_env env, String description) { + return Symbol::For(env, static_cast(description)); +} + +inline MaybeOrValue Symbol::For(napi_env env, napi_value description) { +#if defined(NODE_ADDON_API_ENABLE_MAYBE) + Value symbol_obj; + Value symbol_for_value; + Value symbol_value; + if (Napi::Env(env).Global().Get("Symbol").UnwrapTo(&symbol_obj) && + symbol_obj.As().Get("for").UnwrapTo(&symbol_for_value) && + symbol_for_value.As() + .Call(symbol_obj, {description}) + .UnwrapTo(&symbol_value)) { + return Just(symbol_value.As()); + } + return Nothing(); +#else + Object symbol_obj = Napi::Env(env).Global().Get("Symbol").As(); + return symbol_obj.Get("for") + .As() + .Call(symbol_obj, {description}) + .As(); +#endif +} + +inline void Symbol::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Symbol::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Symbol::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_symbol, "%d", "Symbol::CheckCast"); +} + +inline Symbol::Symbol() : Name() {} + +inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) {} + +//////////////////////////////////////////////////////////////////////////////// +// Automagic value creation +//////////////////////////////////////////////////////////////////////////////// + +namespace details { +template +struct vf_number { + static Number From(napi_env env, T value) { + return Number::New(env, static_cast(value)); + } +}; + +template <> +struct vf_number { + static Boolean From(napi_env env, bool value) { + return Boolean::New(env, value); + } +}; + +struct vf_utf8_charp { + static String From(napi_env env, const char* value) { + return String::New(env, value); + } +}; + +struct vf_utf16_charp { + static String From(napi_env env, const char16_t* value) { + return String::New(env, value); + } +}; +struct vf_utf8_string { + static String From(napi_env env, const std::string& value) { + return String::New(env, value); + } +}; + +struct vf_utf16_string { + static String From(napi_env env, const std::u16string& value) { + return String::New(env, value); + } +}; + +template +struct vf_fallback { + static Value From(napi_env env, const T& value) { return Value(env, value); } +}; + +template +struct disjunction : std::false_type {}; +template +struct disjunction : B {}; +template +struct disjunction + : std::conditional>::type {}; + +template +struct can_make_string + : disjunction::type, + typename std::is_convertible::type, + typename std::is_convertible::type, + typename std::is_convertible::type> {}; +} // namespace details + +template +Value Value::From(napi_env env, const T& value) { + using Helper = typename std::conditional< + std::is_integral::value || std::is_floating_point::value, + details::vf_number, + typename std::conditional::value, + String, + details::vf_fallback>::type>::type; + return Helper::From(env, value); +} + +template +String String::From(napi_env env, const T& value) { + struct Dummy {}; + using Helper = typename std::conditional< + std::is_convertible::value, + details::vf_utf8_charp, + typename std::conditional< + std::is_convertible::value, + details::vf_utf16_charp, + typename std::conditional< + std::is_convertible::value, + details::vf_utf8_string, + typename std::conditional< + std::is_convertible::value, + details::vf_utf16_string, + Dummy>::type>::type>::type>::type; + return Helper::From(env, value); +} + +//////////////////////////////////////////////////////////////////////////////// +// TypeTaggable class +//////////////////////////////////////////////////////////////////////////////// + +inline TypeTaggable::TypeTaggable() : Value() {} + +inline TypeTaggable::TypeTaggable(napi_env _env, napi_value _value) + : Value(_env, _value) {} + +#if NAPI_VERSION >= 8 + +inline void TypeTaggable::TypeTag(const napi_type_tag* type_tag) const { + napi_status status = napi_type_tag_object(_env, _value, type_tag); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline bool TypeTaggable::CheckTypeTag(const napi_type_tag* type_tag) const { + bool result; + napi_status status = + napi_check_object_type_tag(_env, _value, type_tag, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +#endif // NAPI_VERSION >= 8 + +//////////////////////////////////////////////////////////////////////////////// +// Object class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Object::PropertyLValue::operator Value() const { + MaybeOrValue val = Object(_env, _object).Get(_key); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + return val.Unwrap(); +#else + return val; +#endif +} + +template +template +inline Object::PropertyLValue& Object::PropertyLValue::operator=( + ValueType value) { +#ifdef NODE_ADDON_API_ENABLE_MAYBE + MaybeOrValue result = +#endif + Object(_env, _object).Set(_key, value); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + result.Unwrap(); +#endif + return *this; +} + +template +inline Value Object::PropertyLValue::AsValue() const { + return Value(*this); +} + +template +inline Object::PropertyLValue::PropertyLValue(Object object, Key key) + : _env(object.Env()), _object(object), _key(key) {} + +inline Object Object::New(napi_env env) { + napi_value value; + napi_status status = napi_create_object(env, &value); + NAPI_THROW_IF_FAILED(env, status, Object()); + return Object(env, value); +} + +inline void Object::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Object::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Object::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK(type == napi_object || type == napi_function, + "Object::CheckCast", + "Expect napi_object or napi_function, but got %d.", + type); +} + +inline Object::Object() : TypeTaggable() {} + +inline Object::Object(napi_env env, napi_value value) + : TypeTaggable(env, value) {} + +inline Object::PropertyLValue Object::operator[]( + const char* utf8name) { + return PropertyLValue(*this, utf8name); +} + +inline Object::PropertyLValue Object::operator[]( + const std::string& utf8name) { + return PropertyLValue(*this, utf8name); +} + +inline Object::PropertyLValue Object::operator[](uint32_t index) { + return PropertyLValue(*this, index); +} + +inline Object::PropertyLValue Object::operator[](Value index) const { + return PropertyLValue(*this, index); +} + +inline MaybeOrValue Object::operator[](const char* utf8name) const { + return Get(utf8name); +} + +inline MaybeOrValue Object::operator[]( + const std::string& utf8name) const { + return Get(utf8name); +} + +inline MaybeOrValue Object::operator[](uint32_t index) const { + return Get(index); +} + +inline MaybeOrValue Object::Has(napi_value key) const { + bool result; + napi_status status = napi_has_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Has(Value key) const { + bool result; + napi_status status = napi_has_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Has(const char* utf8name) const { + bool result; + napi_status status = napi_has_named_property(_env, _value, utf8name, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Has(const std::string& utf8name) const { + return Has(utf8name.c_str()); +} + +inline MaybeOrValue Object::HasOwnProperty(napi_value key) const { + bool result; + napi_status status = napi_has_own_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::HasOwnProperty(Value key) const { + bool result; + napi_status status = napi_has_own_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::HasOwnProperty(const char* utf8name) const { + napi_value key; + napi_status status = + napi_create_string_utf8(_env, utf8name, std::strlen(utf8name), &key); + NAPI_MAYBE_THROW_IF_FAILED(_env, status, bool); + return HasOwnProperty(key); +} + +inline MaybeOrValue Object::HasOwnProperty( + const std::string& utf8name) const { + return HasOwnProperty(utf8name.c_str()); +} + +inline MaybeOrValue Object::Get(napi_value key) const { + napi_value result; + napi_status status = napi_get_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value); +} + +inline MaybeOrValue Object::Get(Value key) const { + napi_value result; + napi_status status = napi_get_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value); +} + +inline MaybeOrValue Object::Get(const char* utf8name) const { + napi_value result; + napi_status status = napi_get_named_property(_env, _value, utf8name, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value); +} + +inline MaybeOrValue Object::Get(const std::string& utf8name) const { + return Get(utf8name.c_str()); +} + +template +inline MaybeOrValue Object::Set(napi_value key, + const ValueType& value) const { + napi_status status = + napi_set_property(_env, _value, key, Value::From(_env, value)); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +template +inline MaybeOrValue Object::Set(Value key, const ValueType& value) const { + napi_status status = + napi_set_property(_env, _value, key, Value::From(_env, value)); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +template +inline MaybeOrValue Object::Set(const char* utf8name, + const ValueType& value) const { + napi_status status = + napi_set_named_property(_env, _value, utf8name, Value::From(_env, value)); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +template +inline MaybeOrValue Object::Set(const std::string& utf8name, + const ValueType& value) const { + return Set(utf8name.c_str(), value); +} + +inline MaybeOrValue Object::Delete(napi_value key) const { + bool result; + napi_status status = napi_delete_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Delete(Value key) const { + bool result; + napi_status status = napi_delete_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Delete(const char* utf8name) const { + return Delete(String::New(_env, utf8name)); +} + +inline MaybeOrValue Object::Delete(const std::string& utf8name) const { + return Delete(String::New(_env, utf8name)); +} + +inline MaybeOrValue Object::Has(uint32_t index) const { + bool result; + napi_status status = napi_has_element(_env, _value, index, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Get(uint32_t index) const { + napi_value value; + napi_status status = napi_get_element(_env, _value, index, &value); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, value), Value); +} + +template +inline MaybeOrValue Object::Set(uint32_t index, + const ValueType& value) const { + napi_status status = + napi_set_element(_env, _value, index, Value::From(_env, value)); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +inline MaybeOrValue Object::Delete(uint32_t index) const { + bool result; + napi_status status = napi_delete_element(_env, _value, index, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::GetPropertyNames() const { + napi_value result; + napi_status status = napi_get_property_names(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Array(_env, result), Array); +} + +inline MaybeOrValue Object::DefineProperty( + const PropertyDescriptor& property) const { + napi_status status = napi_define_properties( + _env, + _value, + 1, + reinterpret_cast(&property)); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +inline MaybeOrValue Object::DefineProperties( + const std::initializer_list& properties) const { + napi_status status = napi_define_properties( + _env, + _value, + properties.size(), + reinterpret_cast(properties.begin())); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +inline MaybeOrValue Object::DefineProperties( + const std::vector& properties) const { + napi_status status = napi_define_properties( + _env, + _value, + properties.size(), + reinterpret_cast(properties.data())); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +inline MaybeOrValue Object::InstanceOf( + const Function& constructor) const { + bool result; + napi_status status = napi_instanceof(_env, _value, constructor, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +template +inline void Object::AddFinalizer(Finalizer finalizeCallback, T* data) const { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = + details::AttachData::Wrapper>( + _env, *this, data, finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +template +inline void Object::AddFinalizer(Finalizer finalizeCallback, + T* data, + Hint* finalizeHint) const { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = details:: + AttachData::WrapperWithHint>( + _env, *this, data, finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS +inline Object::const_iterator::const_iterator(const Object* object, + const Type type) { + _object = object; + _keys = object->GetPropertyNames(); + _index = type == Type::BEGIN ? 0 : _keys.Length(); +} + +inline Object::const_iterator Napi::Object::begin() const { + const_iterator it(this, Object::const_iterator::Type::BEGIN); + return it; +} + +inline Object::const_iterator Napi::Object::end() const { + const_iterator it(this, Object::const_iterator::Type::END); + return it; +} + +inline Object::const_iterator& Object::const_iterator::operator++() { + ++_index; + return *this; +} + +inline bool Object::const_iterator::operator==( + const const_iterator& other) const { + return _index == other._index; +} + +inline bool Object::const_iterator::operator!=( + const const_iterator& other) const { + return _index != other._index; +} + +inline const std::pair> +Object::const_iterator::operator*() const { + const Value key = _keys[_index]; + const PropertyLValue value = (*_object)[key]; + return {key, value}; +} + +inline Object::iterator::iterator(Object* object, const Type type) { + _object = object; + _keys = object->GetPropertyNames(); + _index = type == Type::BEGIN ? 0 : _keys.Length(); +} + +inline Object::iterator Napi::Object::begin() { + iterator it(this, Object::iterator::Type::BEGIN); + return it; +} + +inline Object::iterator Napi::Object::end() { + iterator it(this, Object::iterator::Type::END); + return it; +} + +inline Object::iterator& Object::iterator::operator++() { + ++_index; + return *this; +} + +inline bool Object::iterator::operator==(const iterator& other) const { + return _index == other._index; +} + +inline bool Object::iterator::operator!=(const iterator& other) const { + return _index != other._index; +} + +inline std::pair> +Object::iterator::operator*() { + Value key = _keys[_index]; + PropertyLValue value = (*_object)[key]; + return {key, value}; +} +#endif // NODE_ADDON_API_CPP_EXCEPTIONS + +#if NAPI_VERSION >= 8 +inline MaybeOrValue Object::Freeze() const { + napi_status status = napi_object_freeze(_env, _value); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +inline MaybeOrValue Object::Seal() const { + napi_status status = napi_object_seal(_env, _value); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} +#endif // NAPI_VERSION >= 8 + +inline MaybeOrValue Object::GetPrototype() const { + napi_value result; + napi_status status = napi_get_prototype(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Object(_env, result), Object); +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE +inline MaybeOrValue Object::SetPrototype(const Object& value) const { + napi_status status = node_api_set_prototype(_env, _value, value); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} +#endif + +//////////////////////////////////////////////////////////////////////////////// +// External class +//////////////////////////////////////////////////////////////////////////////// + +template +inline External External::New(napi_env env, T* data) { + napi_value value; + napi_status status = + napi_create_external(env, data, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, External()); + return External(env, value); +} + +template +template +inline External External::New(napi_env env, + T* data, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = + napi_create_external(env, + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, External()); + } + return External(env, value); +} + +template +template +inline External External::New(napi_env env, + T* data, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = napi_create_external( + env, + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, External()); + } + return External(env, value); +} + +template +inline void External::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "External::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "External::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_external, "%d", "External::CheckCast"); +} + +template +inline External::External() : TypeTaggable() {} + +template +inline External::External(napi_env env, napi_value value) + : TypeTaggable(env, value) {} + +template +inline T* External::Data() const { + void* data; + napi_status status = napi_get_value_external(_env, _value, &data); + NAPI_THROW_IF_FAILED(_env, status, nullptr); + return reinterpret_cast(data); +} + +//////////////////////////////////////////////////////////////////////////////// +// Array class +//////////////////////////////////////////////////////////////////////////////// + +inline Array Array::New(napi_env env) { + napi_value value; + napi_status status = napi_create_array(env, &value); + NAPI_THROW_IF_FAILED(env, status, Array()); + return Array(env, value); +} + +inline Array Array::New(napi_env env, size_t length) { + napi_value value; + napi_status status = napi_create_array_with_length(env, length, &value); + NAPI_THROW_IF_FAILED(env, status, Array()); + return Array(env, value); +} + +inline void Array::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Array::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_array(env, value, &result); + NAPI_CHECK(status == napi_ok, "Array::CheckCast", "napi_is_array failed"); + NAPI_CHECK(result, "Array::CheckCast", "value is not array"); +} + +inline Array::Array() : Object() {} + +inline Array::Array(napi_env env, napi_value value) : Object(env, value) {} + +inline uint32_t Array::Length() const { + uint32_t result; + napi_status status = napi_get_array_length(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +//////////////////////////////////////////////////////////////////////////////// +// SharedArrayBuffer class +//////////////////////////////////////////////////////////////////////////////// + +inline SharedArrayBuffer::SharedArrayBuffer() : Object() {} + +inline SharedArrayBuffer::SharedArrayBuffer(napi_env env, napi_value value) + : Object(env, value) {} + +inline void SharedArrayBuffer::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "SharedArrayBuffer::CheckCast", "empty value"); + + bool result; + napi_status status = node_api_is_sharedarraybuffer(env, value, &result); + NAPI_CHECK(status == napi_ok, + "SharedArrayBuffer::CheckCast", + "node_api_is_sharedarraybuffer failed"); + NAPI_CHECK( + result, "SharedArrayBuffer::CheckCast", "value is not sharedarraybuffer"); +} + +inline SharedArrayBuffer SharedArrayBuffer::New(napi_env env, + size_t byteLength) { + napi_value value; + void* data; + napi_status status = + node_api_create_sharedarraybuffer(env, byteLength, &data, &value); + NAPI_THROW_IF_FAILED(env, status, SharedArrayBuffer()); + + return SharedArrayBuffer(env, value); +} + +inline void* SharedArrayBuffer::Data() { + void* data; + napi_status status = napi_get_arraybuffer_info(_env, _value, &data, nullptr); + NAPI_THROW_IF_FAILED(_env, status, nullptr); + return data; +} + +inline size_t SharedArrayBuffer::ByteLength() { + size_t length; + napi_status status = + napi_get_arraybuffer_info(_env, _value, nullptr, &length); + NAPI_THROW_IF_FAILED(_env, status, 0); + return length; +} +#endif // NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + +//////////////////////////////////////////////////////////////////////////////// +// ArrayBuffer class +//////////////////////////////////////////////////////////////////////////////// + +inline ArrayBuffer ArrayBuffer::New(napi_env env, size_t byteLength) { + napi_value value; + void* data; + napi_status status = napi_create_arraybuffer(env, byteLength, &data, &value); + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + + return ArrayBuffer(env, value); +} + +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength) { + napi_value value; + napi_status status = napi_create_external_arraybuffer( + env, externalData, byteLength, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + + return ArrayBuffer(env, value); +} + +template +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = napi_create_external_arraybuffer( + env, + externalData, + byteLength, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + } + + return ArrayBuffer(env, value); +} + +template +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = napi_create_external_arraybuffer( + env, + externalData, + byteLength, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + } + + return ArrayBuffer(env, value); +} +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + +inline void ArrayBuffer::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "ArrayBuffer::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_arraybuffer(env, value, &result); + NAPI_CHECK(status == napi_ok, + "ArrayBuffer::CheckCast", + "napi_is_arraybuffer failed"); + NAPI_CHECK(result, "ArrayBuffer::CheckCast", "value is not arraybuffer"); +} + +inline ArrayBuffer::ArrayBuffer() : Object() {} + +inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value) + : Object(env, value) {} + +inline void* ArrayBuffer::Data() { + void* data; + napi_status status = napi_get_arraybuffer_info(_env, _value, &data, nullptr); + NAPI_THROW_IF_FAILED(_env, status, nullptr); + return data; +} + +inline size_t ArrayBuffer::ByteLength() { + size_t length; + napi_status status = + napi_get_arraybuffer_info(_env, _value, nullptr, &length); + NAPI_THROW_IF_FAILED(_env, status, 0); + return length; +} + +#if NAPI_VERSION >= 7 +inline bool ArrayBuffer::IsDetached() const { + bool detached; + napi_status status = napi_is_detached_arraybuffer(_env, _value, &detached); + NAPI_THROW_IF_FAILED(_env, status, false); + return detached; +} + +inline void ArrayBuffer::Detach() { + napi_status status = napi_detach_arraybuffer(_env, _value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} +#endif // NAPI_VERSION >= 7 + +//////////////////////////////////////////////////////////////////////////////// +// DataView class +//////////////////////////////////////////////////////////////////////////////// +inline DataView DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer) { + return New(env, arrayBuffer, 0, arrayBuffer.ByteLength()); +} + +inline DataView DataView::New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset) { + if (byteOffset > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New( + env, "Start offset is outside the bounds of the buffer"), + DataView()); + } + return New( + env, arrayBuffer, byteOffset, arrayBuffer.ByteLength() - byteOffset); +} + +inline DataView DataView::New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength) { + if (byteOffset + byteLength > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New(env, "Invalid DataView length"), DataView()); + } + napi_value value; + napi_status status = + napi_create_dataview(env, byteLength, arrayBuffer, byteOffset, &value); + NAPI_THROW_IF_FAILED(env, status, DataView()); + return DataView(env, value); +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +inline DataView DataView::New(napi_env env, + Napi::SharedArrayBuffer arrayBuffer) { + return New(env, arrayBuffer, 0, arrayBuffer.ByteLength()); +} + +inline DataView DataView::New(napi_env env, + Napi::SharedArrayBuffer arrayBuffer, + size_t byteOffset) { + if (byteOffset > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New( + env, "Start offset is outside the bounds of the buffer"), + DataView()); + } + return New( + env, arrayBuffer, byteOffset, arrayBuffer.ByteLength() - byteOffset); +} + +inline DataView DataView::New(napi_env env, + Napi::SharedArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength) { + if (byteOffset + byteLength > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New(env, "Invalid DataView length"), DataView()); + } + napi_value value; + napi_status status = + napi_create_dataview(env, byteLength, arrayBuffer, byteOffset, &value); + NAPI_THROW_IF_FAILED(env, status, DataView()); + return DataView(env, value); +} +#endif // NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + +inline void DataView::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "DataView::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_dataview(env, value, &result); + NAPI_CHECK( + status == napi_ok, "DataView::CheckCast", "napi_is_dataview failed"); + NAPI_CHECK(result, "DataView::CheckCast", "value is not dataview"); +} + +inline DataView::DataView() : Object() {} + +inline DataView::DataView(napi_env env, napi_value value) : Object(env, value) { + napi_status status = napi_get_dataview_info(_env, + _value /* dataView */, + &_length /* byteLength */, + &_data /* data */, + nullptr /* arrayBuffer */, + nullptr /* byteOffset */); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline Napi::ArrayBuffer DataView::ArrayBuffer() const { + return Buffer().As(); +} + +inline Napi::Value DataView::Buffer() const { + napi_value arrayBuffer; + napi_status status = napi_get_dataview_info(_env, + _value /* dataView */, + nullptr /* byteLength */, + nullptr /* data */, + &arrayBuffer /* arrayBuffer */, + nullptr /* byteOffset */); + NAPI_THROW_IF_FAILED(_env, status, Napi::Value()); + return Napi::Value(_env, arrayBuffer); +} + +inline size_t DataView::ByteOffset() const { + size_t byteOffset; + napi_status status = napi_get_dataview_info(_env, + _value /* dataView */, + nullptr /* byteLength */, + nullptr /* data */, + nullptr /* arrayBuffer */, + &byteOffset /* byteOffset */); + NAPI_THROW_IF_FAILED(_env, status, 0); + return byteOffset; +} + +inline size_t DataView::ByteLength() const { + return _length; +} + +inline void* DataView::Data() const { + return _data; +} + +inline float DataView::GetFloat32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline double DataView::GetFloat64(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int8_t DataView::GetInt8(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int16_t DataView::GetInt16(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int32_t DataView::GetInt32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint8_t DataView::GetUint8(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint16_t DataView::GetUint16(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint32_t DataView::GetUint32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline void DataView::SetFloat32(size_t byteOffset, float value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetFloat64(size_t byteOffset, double value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt8(size_t byteOffset, int8_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt16(size_t byteOffset, int16_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt32(size_t byteOffset, int32_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint8(size_t byteOffset, uint8_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint16(size_t byteOffset, uint16_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint32(size_t byteOffset, uint32_t value) const { + WriteData(byteOffset, value); +} + +template +inline T DataView::ReadData(size_t byteOffset) const { + if (byteOffset + sizeof(T) > _length || + byteOffset + sizeof(T) < byteOffset) { // overflow + NAPI_THROW( + RangeError::New(_env, "Offset is outside the bounds of the DataView"), + 0); + } + + return *reinterpret_cast(static_cast(_data) + byteOffset); +} + +template +inline void DataView::WriteData(size_t byteOffset, T value) const { + if (byteOffset + sizeof(T) > _length || + byteOffset + sizeof(T) < byteOffset) { // overflow + NAPI_THROW_VOID( + RangeError::New(_env, "Offset is outside the bounds of the DataView")); + } + + *reinterpret_cast(static_cast(_data) + byteOffset) = value; +} + +//////////////////////////////////////////////////////////////////////////////// +// TypedArray class +//////////////////////////////////////////////////////////////////////////////// +inline void TypedArray::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "TypedArray::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_typedarray(env, value, &result); + NAPI_CHECK( + status == napi_ok, "TypedArray::CheckCast", "napi_is_typedarray failed"); + NAPI_CHECK(result, "TypedArray::CheckCast", "value is not typedarray"); +} + +inline TypedArray::TypedArray() + : Object(), _type(napi_typedarray_type::napi_int8_array), _length(0) {} + +inline TypedArray::TypedArray(napi_env env, napi_value value) + : Object(env, value), + _type(napi_typedarray_type::napi_int8_array), + _length(0) { + if (value != nullptr) { + napi_status status = + napi_get_typedarray_info(_env, + _value, + &const_cast(this)->_type, + &const_cast(this)->_length, + nullptr, + nullptr, + nullptr); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +inline TypedArray::TypedArray(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length) + : Object(env, value), _type(type), _length(length) {} + +inline napi_typedarray_type TypedArray::TypedArrayType() const { + return _type; +} + +inline uint8_t TypedArray::ElementSize() const { + switch (_type) { + case napi_int8_array: + case napi_uint8_array: + case napi_uint8_clamped_array: + return 1; + case napi_int16_array: + case napi_uint16_array: + return 2; + case napi_int32_array: + case napi_uint32_array: + case napi_float32_array: + return 4; + case napi_float64_array: +#if (NAPI_VERSION > 5) + case napi_bigint64_array: + case napi_biguint64_array: +#endif // (NAPI_VERSION > 5) + return 8; + default: + return 0; + } +} + +inline size_t TypedArray::ElementLength() const { + return _length; +} + +inline size_t TypedArray::ByteOffset() const { + size_t byteOffset; + napi_status status = napi_get_typedarray_info( + _env, _value, nullptr, nullptr, nullptr, nullptr, &byteOffset); + NAPI_THROW_IF_FAILED(_env, status, 0); + return byteOffset; +} + +inline size_t TypedArray::ByteLength() const { + return ElementSize() * ElementLength(); +} + +inline Napi::ArrayBuffer TypedArray::ArrayBuffer() const { + napi_value arrayBuffer; + napi_status status = napi_get_typedarray_info( + _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr); + NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer()); + return Napi::ArrayBuffer(_env, arrayBuffer); +} + +inline Napi::Value TypedArray::Buffer() const { + napi_value arrayBuffer; + napi_status status = napi_get_typedarray_info( + _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr); + NAPI_THROW_IF_FAILED(_env, status, Napi::Value()); + return Napi::Value(_env, arrayBuffer); +} + +//////////////////////////////////////////////////////////////////////////////// +// TypedArrayOf class +//////////////////////////////////////////////////////////////////////////////// +template +inline void TypedArrayOf::CheckCast(napi_env env, napi_value value) { + TypedArray::CheckCast(env, value); + napi_typedarray_type type; + napi_status status = napi_get_typedarray_info( + env, value, &type, nullptr, nullptr, nullptr, nullptr); + NAPI_CHECK(status == napi_ok, + "TypedArrayOf::CheckCast", + "napi_is_typedarray failed"); + + NAPI_INTERNAL_CHECK( + (type == TypedArrayTypeForPrimitiveType() || + (type == napi_uint8_clamped_array && std::is_same::value)), + "TypedArrayOf::CheckCast", + "Array type must match the template parameter, (Uint8 arrays may " + "optionally have the \"clamped\" array type.), got %d.", + type); +} + +template +inline TypedArrayOf TypedArrayOf::New(napi_env env, + size_t elementLength, + napi_typedarray_type type) { + Napi::ArrayBuffer arrayBuffer = + Napi::ArrayBuffer::New(env, elementLength * sizeof(T)); + return New(env, elementLength, arrayBuffer, 0, type); +} + +template +inline TypedArrayOf TypedArrayOf::New(napi_env env, + size_t elementLength, + Napi::ArrayBuffer arrayBuffer, + size_t bufferOffset, + napi_typedarray_type type) { + napi_value value; + napi_status status = napi_create_typedarray( + env, type, elementLength, arrayBuffer, bufferOffset, &value); + NAPI_THROW_IF_FAILED(env, status, TypedArrayOf()); + + return TypedArrayOf( + env, + value, + type, + elementLength, + reinterpret_cast(reinterpret_cast(arrayBuffer.Data()) + + bufferOffset)); +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +template +inline TypedArrayOf TypedArrayOf::New(napi_env env, + size_t elementLength, + Napi::SharedArrayBuffer arrayBuffer, + size_t bufferOffset, + napi_typedarray_type type) { + napi_value value; + napi_status status = napi_create_typedarray( + env, type, elementLength, arrayBuffer, bufferOffset, &value); + NAPI_THROW_IF_FAILED(env, status, TypedArrayOf()); + + return TypedArrayOf( + env, + value, + type, + elementLength, + reinterpret_cast(reinterpret_cast(arrayBuffer.Data()) + + bufferOffset)); +} +#endif + +template +inline TypedArrayOf::TypedArrayOf() : TypedArray(), _data(nullptr) {} + +template +inline TypedArrayOf::TypedArrayOf(napi_env env, napi_value value) + : TypedArray(env, value), _data(nullptr) { + napi_status status = napi_ok; + if (value != nullptr) { + void* data = nullptr; + status = napi_get_typedarray_info( + _env, _value, &_type, &_length, &data, nullptr, nullptr); + _data = static_cast(data); + } else { + _type = TypedArrayTypeForPrimitiveType(); + _length = 0; + } + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +template +inline TypedArrayOf::TypedArrayOf(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length, + T* data) + : TypedArray(env, value, type, length), _data(data) { + if (!(type == TypedArrayTypeForPrimitiveType() || + (type == napi_uint8_clamped_array && + std::is_same::value))) { + NAPI_THROW_VOID(TypeError::New( + env, + "Array type must match the template parameter. " + "(Uint8 arrays may optionally have the \"clamped\" array type.)")); + } +} + +template +inline T& TypedArrayOf::operator[](size_t index) { + return _data[index]; +} + +template +inline const T& TypedArrayOf::operator[](size_t index) const { + return _data[index]; +} + +template +inline T* TypedArrayOf::Data() { + return _data; +} + +template +inline const T* TypedArrayOf::Data() const { + return _data; +} + +//////////////////////////////////////////////////////////////////////////////// +// Function class +//////////////////////////////////////////////////////////////////////////////// + +template +inline napi_status CreateFunction(napi_env env, + const char* utf8name, + napi_callback cb, + CbData* data, + napi_value* result) { + napi_status status = + napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, cb, data, result); + if (status == napi_ok) { + status = Napi::details::AttachData(env, *result, data); + } + + return status; +} + +template +inline Function Function::New(napi_env env, const char* utf8name, void* data) { + napi_value result = nullptr; + napi_status status = napi_create_function(env, + utf8name, + NAPI_AUTO_LENGTH, + details::TemplatedVoidCallback, + data, + &result); + NAPI_THROW_IF_FAILED(env, status, Function()); + return Function(env, result); +} + +template +inline Function Function::New(napi_env env, const char* utf8name, void* data) { + napi_value result = nullptr; + napi_status status = napi_create_function(env, + utf8name, + NAPI_AUTO_LENGTH, + details::TemplatedCallback, + data, + &result); + NAPI_THROW_IF_FAILED(env, status, Function()); + return Function(env, result); +} + +template +inline Function Function::New(napi_env env, + const std::string& utf8name, + void* data) { + return Function::New(env, utf8name.c_str(), data); +} + +template +inline Function Function::New(napi_env env, + const std::string& utf8name, + void* data) { + return Function::New(env, utf8name.c_str(), data); +} + +template +inline Function Function::New(napi_env env, + Callable cb, + const char* utf8name, + void* data) { + using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); + using CbData = details::CallbackData; + auto callbackData = new CbData{std::move(cb), data}; + + napi_value value; + napi_status status = + CreateFunction(env, utf8name, CbData::Wrapper, callbackData, &value); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, Function()); + } + + return Function(env, value); +} + +template +inline Function Function::New(napi_env env, + Callable cb, + const std::string& utf8name, + void* data) { + return New(env, cb, utf8name.c_str(), data); +} + +inline void Function::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Function::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Function::CheckCast", "napi_typeof failed"); + NAPI_INTERNAL_CHECK_EQ(type, napi_function, "%d", "Function::CheckCast"); +} + +inline Function::Function() : Object() {} + +inline Function::Function(napi_env env, napi_value value) + : Object(env, value) {} + +inline MaybeOrValue Function::operator()( + const std::initializer_list& args) const { + return Call(Env().Undefined(), args); +} + +inline MaybeOrValue Function::Call( + const std::initializer_list& args) const { + return Call(Env().Undefined(), args); +} + +inline MaybeOrValue Function::Call( + const std::vector& args) const { + return Call(Env().Undefined(), args); +} + +inline MaybeOrValue Function::Call( + const std::vector& args) const { + return Call(Env().Undefined(), args); +} + +inline MaybeOrValue Function::Call(size_t argc, + const napi_value* args) const { + return Call(Env().Undefined(), argc, args); +} + +inline MaybeOrValue Function::Call( + napi_value recv, const std::initializer_list& args) const { + return Call(recv, args.size(), args.begin()); +} + +inline MaybeOrValue Function::Call( + napi_value recv, const std::vector& args) const { + return Call(recv, args.size(), args.data()); +} + +inline MaybeOrValue Function::Call( + napi_value recv, const std::vector& args) const { + const size_t argc = args.size(); + const size_t stackArgsCount = 6; + napi_value stackArgs[stackArgsCount]; + std::vector heapArgs; + napi_value* argv; + if (argc <= stackArgsCount) { + argv = stackArgs; + } else { + heapArgs.resize(argc); + argv = heapArgs.data(); + } + + for (size_t index = 0; index < argc; index++) { + argv[index] = static_cast(args[index]); + } + + return Call(recv, argc, argv); +} + +inline MaybeOrValue Function::Call(napi_value recv, + size_t argc, + const napi_value* args) const { + napi_value result; + napi_status status = + napi_call_function(_env, recv, _value, argc, args, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Value(_env, result), Napi::Value); +} + +inline MaybeOrValue Function::MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context) const { + return MakeCallback(recv, args.size(), args.begin(), context); +} + +inline MaybeOrValue Function::MakeCallback( + napi_value recv, + const std::vector& args, + napi_async_context context) const { + return MakeCallback(recv, args.size(), args.data(), context); +} + +inline MaybeOrValue Function::MakeCallback( + napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context) const { + napi_value result; + napi_status status = + napi_make_callback(_env, context, recv, _value, argc, args, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Value(_env, result), Napi::Value); +} + +inline MaybeOrValue Function::New( + const std::initializer_list& args) const { + return New(args.size(), args.begin()); +} + +inline MaybeOrValue Function::New( + const std::vector& args) const { + return New(args.size(), args.data()); +} + +inline MaybeOrValue Function::New(size_t argc, + const napi_value* args) const { + napi_value result; + napi_status status = napi_new_instance(_env, _value, argc, args, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Object(_env, result), Napi::Object); +} + +//////////////////////////////////////////////////////////////////////////////// +// Promise class +//////////////////////////////////////////////////////////////////////////////// + +inline Promise::Deferred Promise::Deferred::New(napi_env env) { + return Promise::Deferred(env); +} + +inline Promise::Deferred::Deferred(napi_env env) : _env(env) { + napi_status status = napi_create_promise(_env, &_deferred, &_promise); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline Promise Promise::Deferred::Promise() const { + return Napi::Promise(_env, _promise); +} + +inline Napi::Env Promise::Deferred::Env() const { + return Napi::Env(_env); +} + +inline void Promise::Deferred::Resolve(napi_value value) const { + napi_status status = napi_resolve_deferred(_env, _deferred, value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void Promise::Deferred::Reject(napi_value value) const { + napi_status status = napi_reject_deferred(_env, _deferred, value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void Promise::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Promise::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_promise(env, value, &result); + NAPI_CHECK(status == napi_ok, "Promise::CheckCast", "napi_is_promise failed"); + NAPI_CHECK(result, "Promise::CheckCast", "value is not promise"); +} + +inline Promise::Promise() : Object() {} + +inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) {} + +inline MaybeOrValue Promise::Then(napi_value onFulfilled) const { + EscapableHandleScope scope(_env); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + Value thenMethod; + if (!Get("then").UnwrapTo(&thenMethod)) { + return Nothing(); + } + MaybeOrValue result = + thenMethod.As().Call(*this, {onFulfilled}); + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap()).As()); + } + return Nothing(); +#else + Function thenMethod = Get("then").As(); + MaybeOrValue result = thenMethod.Call(*this, {onFulfilled}); + if (scope.Env().IsExceptionPending()) { + return Promise(); + } + return scope.Escape(result).As(); +#endif +} + +inline MaybeOrValue Promise::Then(napi_value onFulfilled, + napi_value onRejected) const { + EscapableHandleScope scope(_env); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + Value thenMethod; + if (!Get("then").UnwrapTo(&thenMethod)) { + return Nothing(); + } + MaybeOrValue result = + thenMethod.As().Call(*this, {onFulfilled, onRejected}); + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap()).As()); + } + return Nothing(); +#else + Function thenMethod = Get("then").As(); + MaybeOrValue result = + thenMethod.Call(*this, {onFulfilled, onRejected}); + if (scope.Env().IsExceptionPending()) { + return Promise(); + } + return scope.Escape(result).As(); +#endif +} + +inline MaybeOrValue Promise::Catch(napi_value onRejected) const { + EscapableHandleScope scope(_env); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + Value catchMethod; + if (!Get("catch").UnwrapTo(&catchMethod)) { + return Nothing(); + } + MaybeOrValue result = + catchMethod.As().Call(*this, {onRejected}); + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap()).As()); + } + return Nothing(); +#else + Function catchMethod = Get("catch").As(); + MaybeOrValue result = catchMethod.Call(*this, {onRejected}); + if (scope.Env().IsExceptionPending()) { + return Promise(); + } + return scope.Escape(result).As(); +#endif +} + +inline MaybeOrValue Promise::Then(const Function& onFulfilled) const { + return Then(static_cast(onFulfilled)); +} + +inline MaybeOrValue Promise::Then(const Function& onFulfilled, + const Function& onRejected) const { + return Then(static_cast(onFulfilled), + static_cast(onRejected)); +} + +inline MaybeOrValue Promise::Catch(const Function& onRejected) const { + return Catch(static_cast(onRejected)); +} + +//////////////////////////////////////////////////////////////////////////////// +// Buffer class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Buffer Buffer::New(napi_env env, size_t length) { + napi_value value; + void* data; + napi_status status = + napi_create_buffer(env, length * sizeof(T), &data, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value); +} + +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +template +inline Buffer Buffer::New(napi_env env, T* data, size_t length) { + napi_value value; + napi_status status = napi_create_external_buffer( + env, length * sizeof(T), data, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value); +} + +template +template +inline Buffer Buffer::New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = + napi_create_external_buffer(env, + length * sizeof(T), + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value); +} + +template +template +inline Buffer Buffer::New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = napi_create_external_buffer( + env, + length * sizeof(T), + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value); +} +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + +template +inline Buffer Buffer::NewOrCopy(napi_env env, T* data, size_t length) { +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + napi_value value; + napi_status status = napi_create_external_buffer( + env, length * sizeof(T), data, nullptr, nullptr, &value); + if (status == details::napi_no_external_buffers_allowed) { +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + // If we can't create an external buffer, we'll just copy the data. + return Buffer::Copy(env, data, length); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + } + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +} + +template +template +inline Buffer Buffer::NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback) { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + napi_value value; + napi_status status = + napi_create_external_buffer(env, + length * sizeof(T), + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status == details::napi_no_external_buffers_allowed) { +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + // If we can't create an external buffer, we'll just copy the data. + Buffer ret = Buffer::Copy(env, data, length); + details::FinalizeData::WrapperGC(env, data, finalizeData); + return ret; +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + } + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +} + +template +template +inline Buffer Buffer::NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint) { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + napi_value value; + napi_status status = napi_create_external_buffer( + env, + length * sizeof(T), + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status == details::napi_no_external_buffers_allowed) { +#endif + // If we can't create an external buffer, we'll just copy the data. + Buffer ret = Buffer::Copy(env, data, length); + details::FinalizeData::WrapperGCWithHint( + env, data, finalizeData); + return ret; +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + } + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value); +#endif +} + +template +inline Buffer Buffer::Copy(napi_env env, const T* data, size_t length) { + napi_value value; + napi_status status = + napi_create_buffer_copy(env, length * sizeof(T), data, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value); +} + +template +inline void Buffer::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Buffer::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_buffer(env, value, &result); + NAPI_CHECK(status == napi_ok, "Buffer::CheckCast", "napi_is_buffer failed"); + NAPI_CHECK(result, "Buffer::CheckCast", "value is not buffer"); +} + +template +inline Buffer::Buffer() : Uint8Array() {} + +template +inline Buffer::Buffer(napi_env env, napi_value value) + : Uint8Array(env, value) {} + +template +inline size_t Buffer::Length() const { + return ByteLength() / sizeof(T); +} + +template +inline T* Buffer::Data() const { + return reinterpret_cast(const_cast(Uint8Array::Data())); +} + +//////////////////////////////////////////////////////////////////////////////// +// Error class +//////////////////////////////////////////////////////////////////////////////// + +inline Error Error::New(napi_env env) { + napi_status status; + napi_value error = nullptr; + bool is_exception_pending; + napi_extended_error_info last_error_info_copy; + + { + // We must retrieve the last error info before doing anything else because + // doing anything else will replace the last error info. + const napi_extended_error_info* last_error_info; + status = napi_get_last_error_info(env, &last_error_info); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_last_error_info"); + + // All fields of the `napi_extended_error_info` structure gets reset in + // subsequent Node-API function calls on the same `env`. This includes a + // call to `napi_is_exception_pending()`. So here it is necessary to make a + // copy of the information as the `error_code` field is used later on. + memcpy(&last_error_info_copy, + last_error_info, + sizeof(napi_extended_error_info)); + } + + status = napi_is_exception_pending(env, &is_exception_pending); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_is_exception_pending"); + + // A pending exception takes precedence over any internal error status. + if (is_exception_pending) { + status = napi_get_and_clear_last_exception(env, &error); + NAPI_FATAL_IF_FAILED( + status, "Error::New", "napi_get_and_clear_last_exception"); + } else { + const char* error_message = last_error_info_copy.error_message != nullptr + ? last_error_info_copy.error_message + : "Error in native callback"; + + napi_value message; + status = napi_create_string_utf8( + env, error_message, std::strlen(error_message), &message); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_string_utf8"); + + switch (last_error_info_copy.error_code) { + case napi_object_expected: + case napi_string_expected: + case napi_boolean_expected: + case napi_number_expected: + status = napi_create_type_error(env, nullptr, message, &error); + break; + default: + status = napi_create_error(env, nullptr, message, &error); + break; + } + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_error"); + } + + return Error(env, error); +} + +inline Error Error::New(napi_env env, const char* message) { + return Error::New( + env, message, std::strlen(message), napi_create_error); +} + +inline Error Error::New(napi_env env, const std::string& message) { + return Error::New( + env, message.c_str(), message.size(), napi_create_error); +} + +inline NAPI_NO_RETURN void Error::Fatal(const char* location, + const char* message) { + napi_fatal_error(location, NAPI_AUTO_LENGTH, message, NAPI_AUTO_LENGTH); +} + +inline Error::Error() : ObjectReference() {} + +inline Error::Error(napi_env env, napi_value value) + : ObjectReference(env, nullptr) { + if (value != nullptr) { + // Attempting to create a reference on the error object. + // If it's not a Object/Function/Symbol, this call will return an error + // status. + napi_status status = napi_create_reference(env, value, 1, &_ref); + + if (status != napi_ok) { + napi_value wrappedErrorObj; + + // Create an error object + status = napi_create_object(env, &wrappedErrorObj); + NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_object"); + + // property flag that we attach to show the error object is wrapped + napi_property_descriptor wrapObjFlag = { + ERROR_WRAP_VALUE(), // Unique GUID identifier since Symbol isn't a + // viable option + nullptr, + nullptr, + nullptr, + nullptr, + Value::From(env, value), + napi_enumerable, + nullptr}; + + status = napi_define_properties(env, wrappedErrorObj, 1, &wrapObjFlag); +#ifdef NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS + if (status == napi_pending_exception) { + // Test if the pending exception was reported because the environment is + // shutting down. We assume that a status of napi_pending_exception + // coupled with the absence of an actual pending exception means that + // the environment is shutting down. If so, we replace the + // napi_pending_exception status with napi_ok. + bool is_exception_pending = false; + status = napi_is_exception_pending(env, &is_exception_pending); + if (status == napi_ok && !is_exception_pending) { + status = napi_ok; + } else { + status = napi_pending_exception; + } + } +#endif // NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS + NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_define_properties"); + + // Create a reference on the newly wrapped object + status = napi_create_reference(env, wrappedErrorObj, 1, &_ref); + } + + // Avoid infinite recursion in the failure case. + NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_reference"); + } +} + +inline Object Error::Value() const { + if (_ref == nullptr) { + return Object(_env, nullptr); + } + + napi_value refValue; + napi_status status = napi_get_reference_value(_env, _ref, &refValue); + NAPI_THROW_IF_FAILED(_env, status, Object()); + + napi_valuetype type; + status = napi_typeof(_env, refValue, &type); + NAPI_THROW_IF_FAILED(_env, status, Object()); + + // If refValue isn't a symbol, then we proceed to whether the refValue has the + // wrapped error flag + if (type != napi_symbol) { + // We are checking if the object is wrapped + bool isWrappedObject = false; + + status = napi_has_property(_env, + refValue, + String::From(_env, ERROR_WRAP_VALUE()), + &isWrappedObject); + + // Don't care about status + if (isWrappedObject) { + napi_value unwrappedValue; + status = napi_get_property(_env, + refValue, + String::From(_env, ERROR_WRAP_VALUE()), + &unwrappedValue); + NAPI_THROW_IF_FAILED(_env, status, Object()); + + return Object(_env, unwrappedValue); + } + } + + return Object(_env, refValue); +} + +inline Error::Error(Error&& other) : ObjectReference(std::move(other)) {} + +inline Error& Error::operator=(Error&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline Error::Error(const Error& other) : ObjectReference(other) {} + +inline Error& Error::operator=(const Error& other) { + Reset(); + + _env = other.Env(); + HandleScope scope(_env); + + napi_value value = other.Value(); + if (value != nullptr) { + napi_status status = napi_create_reference(_env, value, 1, &_ref); + NAPI_THROW_IF_FAILED(_env, status, *this); + } + + return *this; +} + +inline const std::string& Error::Message() const NAPI_NOEXCEPT { + if (_message.size() == 0 && _env != nullptr) { +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + try { + _message = Get("message").As(); + } catch (...) { + // Catch all errors here, to include e.g. a std::bad_alloc from + // the std::string::operator=, because this method may not throw. + } +#else // NODE_ADDON_API_CPP_EXCEPTIONS +#if defined(NODE_ADDON_API_ENABLE_MAYBE) + Napi::Value message_val; + if (Get("message").UnwrapTo(&message_val)) { + _message = message_val.As(); + } +#else + _message = Get("message").As(); +#endif +#endif // NODE_ADDON_API_CPP_EXCEPTIONS + } + return _message; +} + +// we created an object on the &_ref +inline void Error::ThrowAsJavaScriptException() const { + HandleScope scope(_env); + if (!IsEmpty()) { +#ifdef NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS + bool pendingException = false; + + // check if there is already a pending exception. If so don't try to throw a + // new one as that is not allowed/possible + napi_status status = napi_is_exception_pending(_env, &pendingException); + + if ((status != napi_ok) || + ((status == napi_ok) && (pendingException == false))) { + // We intentionally don't use `NAPI_THROW_*` macros here to ensure + // that there is no possible recursion as `ThrowAsJavaScriptException` + // is part of `NAPI_THROW_*` macro definition for noexcept. + + status = napi_throw(_env, Value()); + +#if (NAPI_VERSION >= 10) + napi_status expected_failure_mode = napi_cannot_run_js; +#else + napi_status expected_failure_mode = napi_pending_exception; +#endif + if (status == expected_failure_mode) { + // The environment must be terminating as we checked earlier and there + // was no pending exception. In this case continuing will result + // in a fatal error and there is nothing the author has done incorrectly + // in their code that is worth flagging through a fatal error + return; + } + } else { + status = napi_pending_exception; + } +#else + // We intentionally don't use `NAPI_THROW_*` macros here to ensure + // that there is no possible recursion as `ThrowAsJavaScriptException` + // is part of `NAPI_THROW_*` macro definition for noexcept. + + napi_status status = napi_throw(_env, Value()); +#endif + +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + if (status != napi_ok) { + throw Error::New(_env); + } +#else // NODE_ADDON_API_CPP_EXCEPTIONS + NAPI_FATAL_IF_FAILED( + status, "Error::ThrowAsJavaScriptException", "napi_throw"); +#endif // NODE_ADDON_API_CPP_EXCEPTIONS + } +} + +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + +inline const char* Error::what() const NAPI_NOEXCEPT { + return Message().c_str(); +} + +#endif // NODE_ADDON_API_CPP_EXCEPTIONS + +inline const char* Error::ERROR_WRAP_VALUE() NAPI_NOEXCEPT { + return "4bda9e7e-4913-4dbc-95de-891cbf66598e-errorVal"; +} + +template +inline TError Error::New(napi_env env, + const char* message, + size_t length, + create_error_fn create_error) { + napi_value str; + napi_status status = napi_create_string_utf8(env, message, length, &str); + NAPI_THROW_IF_FAILED(env, status, TError()); + + napi_value error; + status = create_error(env, nullptr, str, &error); + NAPI_THROW_IF_FAILED(env, status, TError()); + + return TError(env, error); +} + +inline TypeError TypeError::New(napi_env env, const char* message) { + return Error::New( + env, message, std::strlen(message), napi_create_type_error); +} + +inline TypeError TypeError::New(napi_env env, const std::string& message) { + return Error::New( + env, message.c_str(), message.size(), napi_create_type_error); +} + +inline TypeError::TypeError() : Error() {} + +inline TypeError::TypeError(napi_env env, napi_value value) + : Error(env, value) {} + +inline RangeError RangeError::New(napi_env env, const char* message) { + return Error::New( + env, message, std::strlen(message), napi_create_range_error); +} + +inline RangeError RangeError::New(napi_env env, const std::string& message) { + return Error::New( + env, message.c_str(), message.size(), napi_create_range_error); +} + +inline RangeError::RangeError() : Error() {} + +inline RangeError::RangeError(napi_env env, napi_value value) + : Error(env, value) {} + +#if NAPI_VERSION > 8 +inline SyntaxError SyntaxError::New(napi_env env, const char* message) { + return Error::New( + env, message, std::strlen(message), node_api_create_syntax_error); +} + +inline SyntaxError SyntaxError::New(napi_env env, const std::string& message) { + return Error::New( + env, message.c_str(), message.size(), node_api_create_syntax_error); +} + +inline SyntaxError::SyntaxError() : Error() {} + +inline SyntaxError::SyntaxError(napi_env env, napi_value value) + : Error(env, value) {} +#endif // NAPI_VERSION > 8 + +//////////////////////////////////////////////////////////////////////////////// +// Reference class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Reference Reference::New(const T& value, + uint32_t initialRefcount) { + napi_env env = value.Env(); + napi_value val = value; + + if (val == nullptr) { + return Reference(env, nullptr); + } + + napi_ref ref; + napi_status status = napi_create_reference(env, value, initialRefcount, &ref); + NAPI_THROW_IF_FAILED(env, status, Reference()); + + return Reference(env, ref); +} + +template +inline Reference::Reference() + : _env(nullptr), _ref(nullptr), _suppressDestruct(false) {} + +template +inline Reference::Reference(napi_env env, napi_ref ref) + : _env(env), _ref(ref), _suppressDestruct(false) {} + +template +inline Reference::~Reference() { + if (_ref != nullptr) { + if (!_suppressDestruct) { + // TODO(legendecas): napi_delete_reference should be invoked immediately. + // Fix this when https://github.com/nodejs/node/pull/55620 lands. +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + Env().PostFinalizer( + [](Napi::Env env, napi_ref ref) { napi_delete_reference(env, ref); }, + _ref); +#else + napi_delete_reference(_env, _ref); +#endif + } + + _ref = nullptr; + } +} + +template +inline Reference::Reference(Reference&& other) + : _env(other._env), + _ref(other._ref), + _suppressDestruct(other._suppressDestruct) { + other._env = nullptr; + other._ref = nullptr; + other._suppressDestruct = false; +} + +template +inline Reference& Reference::operator=(Reference&& other) { + Reset(); + _env = other._env; + _ref = other._ref; + _suppressDestruct = other._suppressDestruct; + other._env = nullptr; + other._ref = nullptr; + other._suppressDestruct = false; + return *this; +} + +template +inline Reference::Reference(const Reference& other) + : _env(other._env), _ref(nullptr), _suppressDestruct(false) { + HandleScope scope(_env); + + napi_value value = other.Value(); + if (value != nullptr) { + // Copying is a limited scenario (currently only used for Error object) and + // always creates a strong reference to the given value even if the incoming + // reference is weak. + napi_status status = napi_create_reference(_env, value, 1, &_ref); + NAPI_FATAL_IF_FAILED( + status, "Reference::Reference", "napi_create_reference"); + } +} + +template +inline Reference::operator napi_ref() const { + return _ref; +} + +template +inline bool Reference::operator==(const Reference& other) const { + HandleScope scope(_env); + return this->Value().StrictEquals(other.Value()); +} + +template +inline bool Reference::operator!=(const Reference& other) const { + return !this->operator==(other); +} + +template +inline Napi::Env Reference::Env() const { + return Napi::Env(_env); +} + +template +inline bool Reference::IsEmpty() const { + return _ref == nullptr; +} + +template +inline T Reference::Value() const { + if (_ref == nullptr) { + return T(_env, nullptr); + } + + napi_value value; + napi_status status = napi_get_reference_value(_env, _ref, &value); + NAPI_THROW_IF_FAILED(_env, status, T()); + return T(_env, value); +} + +template +inline uint32_t Reference::Ref() const { + uint32_t result; + napi_status status = napi_reference_ref(_env, _ref, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +template +inline uint32_t Reference::Unref() const { + uint32_t result; + napi_status status = napi_reference_unref(_env, _ref, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +template +inline void Reference::Reset() { + if (_ref != nullptr) { + napi_status status = napi_delete_reference(_env, _ref); + NAPI_THROW_IF_FAILED_VOID(_env, status); + _ref = nullptr; + } +} + +template +inline void Reference::Reset(const T& value, uint32_t refcount) { + Reset(); + _env = value.Env(); + + napi_value val = value; + if (val != nullptr) { + napi_status status = napi_create_reference(_env, value, refcount, &_ref); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +template +inline void Reference::SuppressDestruct() { + _suppressDestruct = true; +} + +template +inline Reference Weak(T value) { + return Reference::New(value, 0); +} + +inline ObjectReference Weak(Object value) { + return Reference::New(value, 0); +} + +inline FunctionReference Weak(Function value) { + return Reference::New(value, 0); +} + +template +inline Reference Persistent(T value) { + return Reference::New(value, 1); +} + +inline ObjectReference Persistent(Object value) { + return Reference::New(value, 1); +} + +inline FunctionReference Persistent(Function value) { + return Reference::New(value, 1); +} + +//////////////////////////////////////////////////////////////////////////////// +// ObjectReference class +//////////////////////////////////////////////////////////////////////////////// + +inline ObjectReference::ObjectReference() : Reference() {} + +inline ObjectReference::ObjectReference(napi_env env, napi_ref ref) + : Reference(env, ref) {} + +inline ObjectReference::ObjectReference(Reference&& other) + : Reference(std::move(other)) {} + +inline ObjectReference& ObjectReference::operator=(Reference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline ObjectReference::ObjectReference(ObjectReference&& other) + : Reference(std::move(other)) {} + +inline ObjectReference& ObjectReference::operator=(ObjectReference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline ObjectReference::ObjectReference(const ObjectReference& other) + : Reference(other) {} + +inline MaybeOrValue ObjectReference::Get( + const char* utf8name) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Get(utf8name); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue ObjectReference::Get( + const std::string& utf8name) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Get(utf8name); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue ObjectReference::Set(const char* utf8name, + napi_value value) const { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline MaybeOrValue ObjectReference::Set(const char* utf8name, + Napi::Value value) const { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline MaybeOrValue ObjectReference::Set(const char* utf8name, + const char* utf8value) const { + HandleScope scope(_env); + return Value().Set(utf8name, utf8value); +} + +inline MaybeOrValue ObjectReference::Set(const char* utf8name, + bool boolValue) const { + HandleScope scope(_env); + return Value().Set(utf8name, boolValue); +} + +inline MaybeOrValue ObjectReference::Set(const char* utf8name, + double numberValue) const { + HandleScope scope(_env); + return Value().Set(utf8name, numberValue); +} + +inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, + napi_value value) const { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, + Napi::Value value) const { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline MaybeOrValue ObjectReference::Set( + const std::string& utf8name, const std::string& utf8value) const { + HandleScope scope(_env); + return Value().Set(utf8name, utf8value); +} + +inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, + bool boolValue) const { + HandleScope scope(_env); + return Value().Set(utf8name, boolValue); +} + +inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, + double numberValue) const { + HandleScope scope(_env); + return Value().Set(utf8name, numberValue); +} + +inline MaybeOrValue ObjectReference::Get(uint32_t index) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Get(index); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue ObjectReference::Set(uint32_t index, + napi_value value) const { + HandleScope scope(_env); + return Value().Set(index, value); +} + +inline MaybeOrValue ObjectReference::Set(uint32_t index, + Napi::Value value) const { + HandleScope scope(_env); + return Value().Set(index, value); +} + +inline MaybeOrValue ObjectReference::Set(uint32_t index, + const char* utf8value) const { + HandleScope scope(_env); + return Value().Set(index, utf8value); +} + +inline MaybeOrValue ObjectReference::Set( + uint32_t index, const std::string& utf8value) const { + HandleScope scope(_env); + return Value().Set(index, utf8value); +} + +inline MaybeOrValue ObjectReference::Set(uint32_t index, + bool boolValue) const { + HandleScope scope(_env); + return Value().Set(index, boolValue); +} + +inline MaybeOrValue ObjectReference::Set(uint32_t index, + double numberValue) const { + HandleScope scope(_env); + return Value().Set(index, numberValue); +} + +//////////////////////////////////////////////////////////////////////////////// +// FunctionReference class +//////////////////////////////////////////////////////////////////////////////// + +inline FunctionReference::FunctionReference() : Reference() {} + +inline FunctionReference::FunctionReference(napi_env env, napi_ref ref) + : Reference(env, ref) {} + +inline FunctionReference::FunctionReference(Reference&& other) + : Reference(std::move(other)) {} + +inline FunctionReference& FunctionReference::operator=( + Reference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline FunctionReference::FunctionReference(FunctionReference&& other) + : Reference(std::move(other)) {} + +inline FunctionReference& FunctionReference::operator=( + FunctionReference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline MaybeOrValue FunctionReference::operator()( + const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value()(args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::Call( + const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Call(args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::Call( + const std::vector& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Call(args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::Call( + napi_value recv, const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Call(recv, args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::Call( + napi_value recv, const std::vector& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Call(recv, args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::Call( + napi_value recv, size_t argc, const napi_value* args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Call(recv, argc, args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().MakeCallback(recv, args, context); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::MakeCallback( + napi_value recv, + const std::vector& args, + napi_async_context context) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().MakeCallback(recv, args, context); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::MakeCallback( + napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = + Value().MakeCallback(recv, argc, args, context); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::New( + const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().New(args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap()).As()); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Object(); + } + return scope.Escape(result).As(); +#endif +} + +inline MaybeOrValue FunctionReference::New( + const std::vector& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().New(args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap()).As()); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Object(); + } + return scope.Escape(result).As(); +#endif +} + +//////////////////////////////////////////////////////////////////////////////// +// CallbackInfo class +//////////////////////////////////////////////////////////////////////////////// + +inline CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info) + : _env(env), + _info(info), + _this(nullptr), + _dynamicArgs(nullptr), + _data(nullptr) { + _argc = _staticArgCount; + _argv = _staticArgs; + napi_status status = + napi_get_cb_info(env, info, &_argc, _argv, &_this, &_data); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + if (_argc > _staticArgCount) { + // Use either a fixed-size array (on the stack) or a dynamically-allocated + // array (on the heap) depending on the number of args. + _dynamicArgs = new napi_value[_argc]; + _argv = _dynamicArgs; + + status = napi_get_cb_info(env, info, &_argc, _argv, nullptr, nullptr); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +inline CallbackInfo::~CallbackInfo() { + if (_dynamicArgs != nullptr) { + delete[] _dynamicArgs; + } +} + +inline CallbackInfo::operator napi_callback_info() const { + return _info; +} + +inline Value CallbackInfo::NewTarget() const { + napi_value newTarget; + napi_status status = napi_get_new_target(_env, _info, &newTarget); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, newTarget); +} + +inline bool CallbackInfo::IsConstructCall() const { + return !NewTarget().IsEmpty(); +} + +inline Napi::Env CallbackInfo::Env() const { + return Napi::Env(_env); +} + +inline size_t CallbackInfo::Length() const { + return _argc; +} + +inline const Value CallbackInfo::operator[](size_t index) const { + return index < _argc ? Value(_env, _argv[index]) : Env().Undefined(); +} + +inline Value CallbackInfo::This() const { + if (_this == nullptr) { + return Env().Undefined(); + } + return Object(_env, _this); +} + +inline void* CallbackInfo::Data() const { + return _data; +} + +inline void CallbackInfo::SetData(void* data) { + _data = data; +} + +//////////////////////////////////////////////////////////////////////////////// +// PropertyDescriptor class +//////////////////////////////////////////////////////////////////////////////// + +template +PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + + desc.utf8name = utf8name; + desc.getter = details::TemplatedCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template +PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), attributes, data); +} + +template +PropertyDescriptor PropertyDescriptor::Accessor( + Name name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + + desc.name = name; + desc.getter = details::TemplatedCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template +PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + + desc.utf8name = utf8name; + desc.getter = details::TemplatedCallback; + desc.setter = details::TemplatedVoidCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template +PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), attributes, data); +} + +template +PropertyDescriptor PropertyDescriptor::Accessor( + Name name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + + desc.name = name; + desc.getter = details::TemplatedCallback; + desc.setter = details::TemplatedVoidCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { + using CbData = details::CallbackData; + auto callbackData = new CbData({getter, data}); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { + return Accessor(env, object, utf8name.c_str(), getter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + napi_property_attributes attributes, + void* data) { + using CbData = details::CallbackData; + auto callbackData = new CbData({getter, data}); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + using CbData = details::AccessorCallbackData; + auto callbackData = new CbData({getter, setter, data}); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + return Accessor( + env, object, utf8name.c_str(), getter, setter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + using CbData = details::AccessorCallbackData; + auto callbackData = new CbData({getter, setter, data}); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + Napi::Env env, + Napi::Object /*object*/, + const char* utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + nullptr, + nullptr, + Napi::Function::New(env, cb, utf8name, data), + attributes, + nullptr}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return Function(env, object, utf8name.c_str(), cb, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + Napi::Env env, + Napi::Object /*object*/, + Name name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return PropertyDescriptor({nullptr, + name, + nullptr, + nullptr, + nullptr, + Napi::Function::New(env, cb, nullptr, data), + attributes, + nullptr}); +} + +inline PropertyDescriptor PropertyDescriptor::Value( + const char* utf8name, + napi_value value, + napi_property_attributes attributes) { + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + nullptr, + nullptr, + value, + attributes, + nullptr}); +} + +inline PropertyDescriptor PropertyDescriptor::Value( + const std::string& utf8name, + napi_value value, + napi_property_attributes attributes) { + return Value(utf8name.c_str(), value, attributes); +} + +inline PropertyDescriptor PropertyDescriptor::Value( + napi_value name, napi_value value, napi_property_attributes attributes) { + return PropertyDescriptor( + {nullptr, name, nullptr, nullptr, nullptr, value, attributes, nullptr}); +} + +inline PropertyDescriptor PropertyDescriptor::Value( + Name name, Napi::Value value, napi_property_attributes attributes) { + napi_value nameValue = name; + napi_value valueValue = value; + return PropertyDescriptor::Value(nameValue, valueValue, attributes); +} + +inline PropertyDescriptor::PropertyDescriptor(napi_property_descriptor desc) + : _desc(desc) {} + +inline PropertyDescriptor::operator napi_property_descriptor&() { + return _desc; +} + +inline PropertyDescriptor::operator const napi_property_descriptor&() const { + return _desc; +} + +//////////////////////////////////////////////////////////////////////////////// +// InstanceWrap class +//////////////////////////////////////////////////////////////////////////////// + +template +inline void InstanceWrap::AttachPropData( + napi_env env, napi_value value, const napi_property_descriptor* prop) { + napi_status status; + if (!(prop->attributes & napi_static)) { + if (prop->method == T::InstanceVoidMethodCallbackWrapper) { + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); + NAPI_THROW_IF_FAILED_VOID(env, status); + } else if (prop->method == T::InstanceMethodCallbackWrapper) { + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); + NAPI_THROW_IF_FAILED_VOID(env, status); + } else if (prop->getter == T::InstanceGetterCallbackWrapper || + prop->setter == T::InstanceSetterCallbackWrapper) { + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); + NAPI_THROW_IF_FAILED_VOID(env, status); + } + } +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceVoidMethodCallbackData* callbackData = + new InstanceVoidMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::InstanceVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, + InstanceMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceMethodCallbackData* callbackData = + new InstanceMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::InstanceMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceVoidMethodCallbackData* callbackData = + new InstanceVoidMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::InstanceVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, + InstanceMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceMethodCallbackData* callbackData = + new InstanceMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::InstanceMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceVoidMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // MSVC (as of v145 / Visual Studio 2026) raises an internal compiler error + // (C1001) when a pointer-to-member-function is used as a non-type template + // parameter, as the static compile-time dispatch below does. On MSVC, fall + // back to the runtime overload, which passes `method` as a value instead. + return InstanceMethod(utf8name, method, attributes, data); +#else + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedInstanceVoidCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +#endif +} + +template +template ::InstanceMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // See the note in the InstanceMethod overload above. + return InstanceMethod(utf8name, method, attributes, data); +#else + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedInstanceCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +#endif +} + +template +template ::InstanceVoidMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // See the note in the InstanceMethod overload above. + return InstanceMethod(name, method, attributes, data); +#else + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedInstanceVoidCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +#endif +} + +template +template ::InstanceMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // See the note in the InstanceMethod overload above. + return InstanceMethod(name, method, attributes, data); +#else + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedInstanceCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +#endif +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + const char* utf8name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes, + void* data) { + InstanceAccessorCallbackData* callbackData = + new InstanceAccessorCallbackData({getter, setter, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + Symbol name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes, + void* data) { + InstanceAccessorCallbackData* callbackData = + new InstanceAccessorCallbackData({getter, setter, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceGetterCallback getter, + typename InstanceWrap::InstanceSetterCallback setter> +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + const char* utf8name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // See the note in the InstanceMethod overload above. + return InstanceAccessor(utf8name, getter, setter, attributes, data); +#else + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = details::TemplatedInstanceCallback; + desc.setter = This::WrapSetter(This::SetterTag()); + desc.data = data; + desc.attributes = attributes; + return desc; +#endif +} + +template +template ::InstanceGetterCallback getter, + typename InstanceWrap::InstanceSetterCallback setter> +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + Symbol name, napi_property_attributes attributes, void* data) { +#ifdef _MSC_VER + // See the note in the InstanceMethod overload above. + return InstanceAccessor(name, getter, setter, attributes, data); +#else + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = details::TemplatedInstanceCallback; + desc.setter = This::WrapSetter(This::SetterTag()); + desc.data = data; + desc.attributes = attributes; + return desc; +#endif +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.value = value; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceValue( + Symbol name, Napi::Value value, napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.value = value; + desc.attributes = attributes; + return desc; +} + +template +inline napi_value InstanceWrap::InstanceVoidMethodCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + InstanceVoidMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->callback; + if (instance) (instance->*cb)(callbackInfo); + return nullptr; + }); +} + +template +inline napi_value InstanceWrap::InstanceMethodCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + InstanceMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->callback; + return instance ? (instance->*cb)(callbackInfo) : Napi::Value(); + }); +} + +template +inline napi_value InstanceWrap::InstanceGetterCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + InstanceAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->getterCallback; + return instance ? (instance->*cb)(callbackInfo) : Napi::Value(); + }); +} + +template +inline napi_value InstanceWrap::InstanceSetterCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + InstanceAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->setterCallback; + if (instance) (instance->*cb)(callbackInfo, callbackInfo[0]); + return nullptr; + }); +} + +template +template ::InstanceSetterCallback method> +inline napi_value InstanceWrap::WrappedMethod( + napi_env env, napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback(env, [&] { + const CallbackInfo cbInfo(env, info); + T* instance = T::Unwrap(cbInfo.This().As()); + if (instance) (instance->*method)(cbInfo, cbInfo[0]); + return nullptr; + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// ObjectWrap class +//////////////////////////////////////////////////////////////////////////////// + +template +inline NAPI_NO_SANITIZE_VPTR ObjectWrap::ObjectWrap( + const Napi::CallbackInfo& callbackInfo) { + napi_env env = callbackInfo.Env(); + napi_value wrapper = callbackInfo.This(); + napi_status status; + napi_ref ref; + T* instance = static_cast(this); + status = napi_wrap(env, wrapper, instance, FinalizeCallback, nullptr, &ref); + NAPI_THROW_IF_FAILED_VOID(env, status); + + Reference* instanceRef = instance; + *instanceRef = Reference(env, ref); +} + +template +inline NAPI_NO_SANITIZE_VPTR ObjectWrap::~ObjectWrap() { + // If the JS object still exists at this point, remove the finalizer added + // through `napi_wrap()`. + if (!IsEmpty() && !_finalized) { + Object object = Value(); + // It is not valid to call `napi_remove_wrap()` with an empty `object`. + // This happens e.g. during garbage collection. + if (!object.IsEmpty() && _construction_failed) { + napi_remove_wrap(Env(), object, nullptr); + } + } +} + +// with RTTI turned on, modern compilers check to see if virtual function +// pointers are stripped of RTTI by void casts. this is intrinsic to how Unwrap +// works, so we inject a compiler pragma to turn off that check just for the +// affected methods. this compiler check is on by default in Android NDK 29. +template +inline NAPI_NO_SANITIZE_VPTR T* ObjectWrap::Unwrap(Object wrapper) { + void* unwrapped; + napi_status status = napi_unwrap(wrapper.Env(), wrapper, &unwrapped); + NAPI_THROW_IF_FAILED(wrapper.Env(), status, nullptr); + return static_cast(unwrapped); +} + +template +inline Function ObjectWrap::DefineClass( + Napi::Env env, + const char* utf8name, + const size_t props_count, + const napi_property_descriptor* descriptors, + void* data) { + napi_status status; + std::vector props(props_count); + + // We copy the descriptors to a local array because before defining the class + // we must replace static method property descriptors with value property + // descriptors such that the value is a function-valued `napi_value` created + // with `CreateFunction()`. + // + // This replacement could be made for instance methods as well, but V8 aborts + // if we do that, because it expects methods defined on the prototype template + // to have `FunctionTemplate`s. + for (size_t index = 0; index < props_count; index++) { + props[index] = descriptors[index]; + napi_property_descriptor* prop = &props[index]; + if (prop->method == T::StaticMethodCallbackWrapper) { + status = + CreateFunction(env, + utf8name, + prop->method, + static_cast(prop->data), + &(prop->value)); + NAPI_THROW_IF_FAILED(env, status, Function()); + prop->method = nullptr; + prop->data = nullptr; + } else if (prop->method == T::StaticVoidMethodCallbackWrapper) { + status = + CreateFunction(env, + utf8name, + prop->method, + static_cast(prop->data), + &(prop->value)); + NAPI_THROW_IF_FAILED(env, status, Function()); + prop->method = nullptr; + prop->data = nullptr; + } + } + + napi_value value; + status = napi_define_class(env, + utf8name, + NAPI_AUTO_LENGTH, + T::ConstructorCallbackWrapper, + data, + props_count, + props.data(), + &value); + NAPI_THROW_IF_FAILED(env, status, Function()); + + // After defining the class we iterate once more over the property descriptors + // and attach the data associated with accessors and instance methods to the + // newly created JavaScript class. + for (size_t idx = 0; idx < props_count; idx++) { + const napi_property_descriptor* prop = &props[idx]; + + if (prop->getter == T::StaticGetterCallbackWrapper || + prop->setter == T::StaticSetterCallbackWrapper) { + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); + NAPI_THROW_IF_FAILED(env, status, Function()); + } else { + // InstanceWrap::AttachPropData is responsible for attaching the data + // of instance methods and accessors. + T::AttachPropData(env, value, prop); + } + } + + return Function(env, value); +} + +template +inline Function ObjectWrap::DefineClass( + Napi::Env env, + const char* utf8name, + const std::initializer_list>& properties, + void* data) { + return DefineClass( + env, + utf8name, + properties.size(), + reinterpret_cast(properties.begin()), + data); +} + +template +inline Function ObjectWrap::DefineClass( + Napi::Env env, + const char* utf8name, + const std::vector>& properties, + void* data) { + return DefineClass( + env, + utf8name, + properties.size(), + reinterpret_cast(properties.data()), + data); +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, + StaticVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticVoidMethodCallbackData* callbackData = + new StaticVoidMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::StaticVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, + StaticMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticMethodCallbackData* callbackData = + new StaticMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::StaticMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, + StaticVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticVoidMethodCallbackData* callbackData = + new StaticVoidMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::StaticVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, + StaticMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticMethodCallbackData* callbackData = + new StaticMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::StaticMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticVoidMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedVoidCallback; + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticVoidMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedVoidCallback; + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedCallback; + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedCallback; + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + const char* utf8name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes, + void* data) { + StaticAccessorCallbackData* callbackData = + new StaticAccessorCallbackData({getter, setter, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + Symbol name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes, + void* data) { + StaticAccessorCallbackData* callbackData = + new StaticAccessorCallbackData({getter, setter, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticGetterCallback getter, + typename ObjectWrap::StaticSetterCallback setter> +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = details::TemplatedCallback; + desc.setter = This::WrapStaticSetter(This::StaticSetterTag()); + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticGetterCallback getter, + typename ObjectWrap::StaticSetterCallback setter> +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + Symbol name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = details::TemplatedCallback; + desc.setter = This::WrapStaticSetter(This::StaticSetterTag()); + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.value = value; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticValue( + Symbol name, Napi::Value value, napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.value = value; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline Value ObjectWrap::OnCalledAsFunction( + const Napi::CallbackInfo& callbackInfo) { + NAPI_THROW( + TypeError::New(callbackInfo.Env(), + "Class constructors cannot be invoked without 'new'"), + Napi::Value()); +} + +template +inline void ObjectWrap::Finalize(Napi::Env /*env*/) {} + +template +inline void ObjectWrap::Finalize(BasicEnv /*env*/) {} + +template +inline napi_value ObjectWrap::ConstructorCallbackWrapper( + napi_env env, napi_callback_info info) { + napi_value new_target; + napi_status status = napi_get_new_target(env, info, &new_target); + if (status != napi_ok) return nullptr; + + bool isConstructCall = (new_target != nullptr); + if (!isConstructCall) { + return details::WrapCallback( + env, [&] { return T::OnCalledAsFunction(CallbackInfo(env, info)); }); + } + + napi_value wrapper = details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + T* instance = new T(callbackInfo); +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + instance->_construction_failed = false; +#else + if (callbackInfo.Env().IsExceptionPending()) { + // We need to clear the exception so that removing the wrap might work. + Error e = callbackInfo.Env().GetAndClearPendingException(); + delete instance; + e.ThrowAsJavaScriptException(); + } else { + instance->_construction_failed = false; + } +#endif // NODE_ADDON_API_CPP_EXCEPTIONS + return callbackInfo.This(); + }); + + return wrapper; +} + +template +inline napi_value ObjectWrap::StaticVoidMethodCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + StaticVoidMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->callback(callbackInfo); + return nullptr; + }); +} + +template +inline napi_value ObjectWrap::StaticMethodCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + StaticMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->callback(callbackInfo); + }); +} + +template +inline napi_value ObjectWrap::StaticGetterCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + StaticAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->getterCallback(callbackInfo); + }); +} + +template +inline napi_value ObjectWrap::StaticSetterCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback(env, [&] { + CallbackInfo callbackInfo(env, info); + StaticAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->setterCallback(callbackInfo, callbackInfo[0]); + return nullptr; + }); +} + +template +inline void ObjectWrap::FinalizeCallback(node_addon_api_basic_env env, + void* data, + void* /*hint*/) { + // If the child class does not override _any_ Finalize() method, `env` will be + // unused because of the constexpr guards. Explicitly reference it here to + // bypass compiler warnings. + (void)env; + T* instance = static_cast(data); + + // Prevent ~ObjectWrap from calling napi_remove_wrap. + // The instance->_ref should be deleted with napi_delete_reference in + // ~Reference. + instance->_finalized = true; + + // If class overrides the basic finalizer, execute it. + if constexpr (details::HasBasicFinalizer::value) { +#ifndef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + HandleScope scope(env); +#endif + + instance->Finalize(Napi::BasicEnv(env)); + } + + // If class overrides the (extended) finalizer, either schedule it or + // execute it immediately (depending on experimental features enabled). + if constexpr (details::HasExtendedFinalizer::value) { +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + // In experimental, attach via node_api_post_finalizer. + // `PostFinalizeCallback` is responsible for deleting the `T* instance`, + // after calling the user-provided finalizer. + napi_status status = + node_api_post_finalizer(env, PostFinalizeCallback, data, nullptr); + NAPI_FATAL_IF_FAILED(status, + "ObjectWrap::FinalizeCallback", + "node_api_post_finalizer failed"); +#else + // In non-experimental, this `FinalizeCallback` already executes from a + // non-basic environment. Execute the override directly. + // `PostFinalizeCallback` is responsible for deleting the `T* instance`, + // after calling the user-provided finalizer. + HandleScope scope(env); + PostFinalizeCallback(env, data, static_cast(nullptr)); +#endif + } + // If the instance does _not_ override the (extended) finalizer, delete the + // `T* instance` immediately. + else { + delete instance; + } +} + +template +inline void ObjectWrap::PostFinalizeCallback(napi_env env, + void* data, + void* /*hint*/) { + T* instance = static_cast(data); + instance->Finalize(Napi::Env(env)); + delete instance; +} + +template +template ::StaticSetterCallback method> +inline napi_value ObjectWrap::WrappedMethod( + napi_env env, napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback(env, [&] { + const CallbackInfo cbInfo(env, info); + // MSVC requires to copy 'method' function pointer to a local variable + // before invoking it. + auto m = method; + m(cbInfo, cbInfo[0]); + return nullptr; + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// HandleScope class +//////////////////////////////////////////////////////////////////////////////// + +inline HandleScope::HandleScope(napi_env env, napi_handle_scope scope) + : _env(env), _scope(scope) {} + +inline HandleScope::HandleScope(Napi::Env env) : _env(env) { + napi_status status = napi_open_handle_scope(_env, &_scope); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline HandleScope::~HandleScope() { + napi_status status = napi_close_handle_scope(_env, _scope); + NAPI_FATAL_IF_FAILED( + status, "HandleScope::~HandleScope", "napi_close_handle_scope"); +} + +inline HandleScope::operator napi_handle_scope() const { + return _scope; +} + +inline Napi::Env HandleScope::Env() const { + return Napi::Env(_env); +} + +//////////////////////////////////////////////////////////////////////////////// +// EscapableHandleScope class +//////////////////////////////////////////////////////////////////////////////// + +inline EscapableHandleScope::EscapableHandleScope( + napi_env env, napi_escapable_handle_scope scope) + : _env(env), _scope(scope) {} + +inline EscapableHandleScope::EscapableHandleScope(Napi::Env env) : _env(env) { + napi_status status = napi_open_escapable_handle_scope(_env, &_scope); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline EscapableHandleScope::~EscapableHandleScope() { + napi_status status = napi_close_escapable_handle_scope(_env, _scope); + NAPI_FATAL_IF_FAILED(status, + "EscapableHandleScope::~EscapableHandleScope", + "napi_close_escapable_handle_scope"); +} + +inline EscapableHandleScope::operator napi_escapable_handle_scope() const { + return _scope; +} + +inline Napi::Env EscapableHandleScope::Env() const { + return Napi::Env(_env); +} + +inline Value EscapableHandleScope::Escape(napi_value escapee) { + napi_value result; + napi_status status = napi_escape_handle(_env, _scope, escapee, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +#if (NAPI_VERSION > 2) +//////////////////////////////////////////////////////////////////////////////// +// CallbackScope class +//////////////////////////////////////////////////////////////////////////////// + +inline CallbackScope::CallbackScope(napi_env env, napi_callback_scope scope) + : _env(env), _scope(scope) {} + +inline CallbackScope::CallbackScope(napi_env env, napi_async_context context) + : _env(env) { + napi_status status = + napi_open_callback_scope(_env, Object::New(env), context, &_scope); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline CallbackScope::~CallbackScope() { + napi_status status = napi_close_callback_scope(_env, _scope); + NAPI_FATAL_IF_FAILED( + status, "CallbackScope::~CallbackScope", "napi_close_callback_scope"); +} + +inline CallbackScope::operator napi_callback_scope() const { + return _scope; +} + +inline Napi::Env CallbackScope::Env() const { + return Napi::Env(_env); +} +#endif + +//////////////////////////////////////////////////////////////////////////////// +// AsyncContext class +//////////////////////////////////////////////////////////////////////////////// + +inline AsyncContext::AsyncContext(napi_env env, const char* resource_name) + : AsyncContext(env, resource_name, Object::New(env)) {} + +inline AsyncContext::AsyncContext(napi_env env, + const char* resource_name, + const Object& resource) + : _env(env), _context(nullptr) { + napi_value resource_id; + napi_status status = napi_create_string_utf8( + _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + status = napi_async_init(_env, resource, resource_id, &_context); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline AsyncContext::~AsyncContext() { + if (_context != nullptr) { + napi_async_destroy(_env, _context); + _context = nullptr; + } +} + +inline AsyncContext::AsyncContext(AsyncContext&& other) { + _env = other._env; + other._env = nullptr; + _context = other._context; + other._context = nullptr; +} + +inline AsyncContext& AsyncContext::operator=(AsyncContext&& other) { + _env = other._env; + other._env = nullptr; + _context = other._context; + other._context = nullptr; + return *this; +} + +inline AsyncContext::operator napi_async_context() const { + return _context; +} + +inline Napi::Env AsyncContext::Env() const { + return Napi::Env(_env); +} + +//////////////////////////////////////////////////////////////////////////////// +// AsyncWorker class +//////////////////////////////////////////////////////////////////////////////// + +#if NAPI_HAS_THREADS + +inline AsyncWorker::AsyncWorker(const Function& callback) + : AsyncWorker(callback, "generic") {} + +inline AsyncWorker::AsyncWorker(const Function& callback, + const char* resource_name) + : AsyncWorker(callback, resource_name, Object::New(callback.Env())) {} + +inline AsyncWorker::AsyncWorker(const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncWorker( + Object::New(callback.Env()), callback, resource_name, resource) {} + +inline AsyncWorker::AsyncWorker(const Object& receiver, + const Function& callback) + : AsyncWorker(receiver, callback, "generic") {} + +inline AsyncWorker::AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name) + : AsyncWorker( + receiver, callback, resource_name, Object::New(callback.Env())) {} + +inline AsyncWorker::AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource) + : _env(callback.Env()), + _receiver(Napi::Persistent(receiver)), + _callback(Napi::Persistent(callback)), + _suppress_destruct(false) { + napi_value resource_id; + napi_status status = napi_create_string_latin1( + _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + status = napi_create_async_work(_env, + resource, + resource_id, + OnAsyncWorkExecute, + OnAsyncWorkComplete, + this, + &_work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline AsyncWorker::AsyncWorker(Napi::Env env) : AsyncWorker(env, "generic") {} + +inline AsyncWorker::AsyncWorker(Napi::Env env, const char* resource_name) + : AsyncWorker(env, resource_name, Object::New(env)) {} + +inline AsyncWorker::AsyncWorker(Napi::Env env, + const char* resource_name, + const Object& resource) + : _env(env), _receiver(), _callback(), _suppress_destruct(false) { + napi_value resource_id; + napi_status status = napi_create_string_latin1( + _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + status = napi_create_async_work(_env, + resource, + resource_id, + OnAsyncWorkExecute, + OnAsyncWorkComplete, + this, + &_work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline AsyncWorker::~AsyncWorker() { + if (_work != nullptr) { + napi_delete_async_work(_env, _work); + _work = nullptr; + } +} + +inline void AsyncWorker::Destroy() { + delete this; +} + +inline AsyncWorker::operator napi_async_work() const { + return _work; +} + +inline Napi::Env AsyncWorker::Env() const { + return Napi::Env(_env); +} + +inline void AsyncWorker::Queue() { + napi_status status = napi_queue_async_work(_env, _work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void AsyncWorker::Cancel() { + napi_status status = napi_cancel_async_work(_env, _work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline ObjectReference& AsyncWorker::Receiver() { + return _receiver; +} + +inline FunctionReference& AsyncWorker::Callback() { + return _callback; +} + +inline void AsyncWorker::SuppressDestruct() { + _suppress_destruct = true; +} + +inline void AsyncWorker::OnOK() { + if (!_callback.IsEmpty()) { + _callback.Call(_receiver.Value(), GetResult(_callback.Env())); + } +} + +inline void AsyncWorker::OnError(const Error& e) { + if (!_callback.IsEmpty()) { + _callback.Call(_receiver.Value(), + std::initializer_list{e.Value()}); + } +} + +inline void AsyncWorker::SetError(const std::string& error) { + _error = error; +} + +inline std::vector AsyncWorker::GetResult(Napi::Env /*env*/) { + return {}; +} +// The OnAsyncWorkExecute method receives an napi_env argument. However, do NOT +// use it within this method, as it does not run on the JavaScript thread and +// must not run any method that would cause JavaScript to run. In practice, +// this means that almost any use of napi_env will be incorrect. +inline void AsyncWorker::OnAsyncWorkExecute(napi_env env, void* asyncworker) { + AsyncWorker* self = static_cast(asyncworker); + self->OnExecute(env); +} +// The OnExecute method receives an napi_env argument. However, do NOT +// use it within this method, as it does not run on the JavaScript thread and +// must not run any method that would cause JavaScript to run. In practice, +// this means that almost any use of napi_env will be incorrect. +inline void AsyncWorker::OnExecute(Napi::Env /*DO_NOT_USE*/) { +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + try { + Execute(); + } catch (const std::exception& e) { + SetError(e.what()); + } +#else // NODE_ADDON_API_CPP_EXCEPTIONS + Execute(); +#endif // NODE_ADDON_API_CPP_EXCEPTIONS +} + +inline void AsyncWorker::OnAsyncWorkComplete(napi_env env, + napi_status status, + void* asyncworker) { + AsyncWorker* self = static_cast(asyncworker); + self->OnWorkComplete(env, status); +} +inline void AsyncWorker::OnWorkComplete(Napi::Env env, napi_status status) { + if (status != napi_cancelled) { + HandleScope scope(_env); + details::WrapCallback(env, [&] { + if (_error.size() == 0) { + OnOK(); + } else { + OnError(Error::New(_env, _error)); + } + return nullptr; + }); + } + if (!_suppress_destruct) { + Destroy(); + } +} + +#endif // NAPI_HAS_THREADS + +#if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) +//////////////////////////////////////////////////////////////////////////////// +// TypedThreadSafeFunction class +//////////////////////////////////////////////////////////////////////////////// + +// Starting with NAPI 5, the JavaScript function `func` parameter of +// `napi_create_threadsafe_function` is optional. +#if NAPI_VERSION > 4 +// static, with Callback [missing] Resource [missing] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + nullptr, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [missing] Resource [passed] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + nullptr, + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [missing] Resource [missing] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + auto fini = + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext; + napi_status status = + napi_create_threadsafe_function(env, + nullptr, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + fini, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [missing] Resource [passed] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + auto fini = + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext; + napi_status status = + napi_create_threadsafe_function(env, + nullptr, + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + fini, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} +#endif + +// static, with Callback [passed] Resource [missing] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + callback, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [passed] Resource [passed] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + callback, + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [passed] Resource [missing] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + auto fini = + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext; + napi_status status = + napi_create_threadsafe_function(env, + callback, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + fini, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with: Callback [passed] Resource [passed] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + CallbackType callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + auto fini = + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext; + napi_status status = napi_create_threadsafe_function( + env, + details::DefaultCallbackWrapper< + CallbackType, + TypedThreadSafeFunction>(env, + callback), + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + fini, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +template +inline TypedThreadSafeFunction:: + TypedThreadSafeFunction() + : _tsfn() {} + +template +inline TypedThreadSafeFunction:: + TypedThreadSafeFunction(napi_threadsafe_function tsfn) + : _tsfn(tsfn) {} + +template +inline TypedThreadSafeFunction:: +operator napi_threadsafe_function() const { + return _tsfn; +} + +template +inline napi_status +TypedThreadSafeFunction::BlockingCall( + DataType* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking); +} + +template +inline napi_status +TypedThreadSafeFunction::NonBlockingCall( + DataType* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking); +} + +template +inline void TypedThreadSafeFunction::Ref( + napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_ref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +template +inline void TypedThreadSafeFunction::Unref( + napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_unref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +template +inline napi_status +TypedThreadSafeFunction::Acquire() const { + return napi_acquire_threadsafe_function(_tsfn); +} + +template +inline napi_status +TypedThreadSafeFunction::Release() const { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_release); +} + +template +inline napi_status +TypedThreadSafeFunction::Abort() const { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort); +} + +template +inline ContextType* +TypedThreadSafeFunction::GetContext() const { + void* context; + napi_status status = napi_get_threadsafe_function_context(_tsfn, &context); + NAPI_FATAL_IF_FAILED(status, + "TypedThreadSafeFunction::GetContext", + "napi_get_threadsafe_function_context"); + return static_cast(context); +} + +// static +template +void TypedThreadSafeFunction::CallJsInternal( + napi_env env, napi_value jsCallback, void* context, void* data) { + details::CallJsWrapper( + env, jsCallback, context, data); +} + +#if NAPI_VERSION == 4 +// static +template +Napi::Function +TypedThreadSafeFunction::EmptyFunctionFactory( + Napi::Env env) { + return Napi::Function::New(env, [](const CallbackInfo& cb) {}); +} + +// static +template +Napi::Function +TypedThreadSafeFunction::FunctionOrEmpty( + Napi::Env env, Napi::Function& callback) { + if (callback.IsEmpty()) { + return EmptyFunctionFactory(env); + } + return callback; +} + +#else +// static +template +std::nullptr_t +TypedThreadSafeFunction::EmptyFunctionFactory( + Napi::Env /*env*/) { + return nullptr; +} + +// static +template +Napi::Function +TypedThreadSafeFunction::FunctionOrEmpty( + Napi::Env /*env*/, Napi::Function& callback) { + return callback; +} + +#endif + +//////////////////////////////////////////////////////////////////////////////// +// ThreadSafeFunction class +//////////////////////////////////////////////////////////////////////////////// + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount) { + return New( + env, callback, Object(), resourceName, maxQueueSize, initialThreadCount); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + context); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + finalizeCallback); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + finalizeCallback, + data); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback, + data); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + static_cast(nullptr) /* context */); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + context, + [](Env, ContextType*) {} /* empty finalizer */); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + static_cast(nullptr) /* context */, + finalizeCallback, + static_cast(nullptr) /* data */, + details::ThreadSafeFinalize::Wrapper); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + static_cast(nullptr) /* context */, + finalizeCallback, + data, + details::ThreadSafeFinalize:: + FinalizeWrapperWithData); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback) { + return New( + env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback, + static_cast(nullptr) /* data */, + details::ThreadSafeFinalize::FinalizeWrapperWithContext); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New( + env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback, + data, + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext); +} + +inline ThreadSafeFunction::ThreadSafeFunction() : _tsfn() {} + +inline ThreadSafeFunction::ThreadSafeFunction(napi_threadsafe_function tsfn) + : _tsfn(tsfn) {} + +inline ThreadSafeFunction::operator napi_threadsafe_function() const { + return _tsfn; +} + +inline napi_status ThreadSafeFunction::BlockingCall() const { + return CallInternal(nullptr, napi_tsfn_blocking); +} + +template <> +inline napi_status ThreadSafeFunction::BlockingCall(void* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking); +} + +template +inline napi_status ThreadSafeFunction::BlockingCall(Callback callback) const { + return CallInternal(new CallbackWrapper(callback), napi_tsfn_blocking); +} + +template +inline napi_status ThreadSafeFunction::BlockingCall(DataType* data, + Callback callback) const { + auto wrapper = [data, callback](Env env, Function jsCallback) { + callback(env, jsCallback, data); + }; + return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_blocking); +} + +inline napi_status ThreadSafeFunction::NonBlockingCall() const { + return CallInternal(nullptr, napi_tsfn_nonblocking); +} + +template <> +inline napi_status ThreadSafeFunction::NonBlockingCall(void* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking); +} + +template +inline napi_status ThreadSafeFunction::NonBlockingCall( + Callback callback) const { + return CallInternal(new CallbackWrapper(callback), napi_tsfn_nonblocking); +} + +template +inline napi_status ThreadSafeFunction::NonBlockingCall( + DataType* data, Callback callback) const { + auto wrapper = [data, callback](Env env, Function jsCallback) { + callback(env, jsCallback, data); + }; + return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_nonblocking); +} + +inline void ThreadSafeFunction::Ref(napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_ref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +inline void ThreadSafeFunction::Unref(napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_unref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +inline napi_status ThreadSafeFunction::Acquire() const { + return napi_acquire_threadsafe_function(_tsfn); +} + +inline napi_status ThreadSafeFunction::Release() const { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_release); +} + +inline napi_status ThreadSafeFunction::Abort() const { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort); +} + +inline ThreadSafeFunction::ConvertibleContext ThreadSafeFunction::GetContext() + const { + void* context; + napi_status status = napi_get_threadsafe_function_context(_tsfn, &context); + NAPI_FATAL_IF_FAILED(status, + "ThreadSafeFunction::GetContext", + "napi_get_threadsafe_function_context"); + return ConvertibleContext({context}); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data, + napi_finalize wrapper) { + static_assert(details::can_make_string::value || + std::is_convertible::value, + "Resource name should be convertible to the string type"); + + ThreadSafeFunction tsfn; + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + napi_status status = + napi_create_threadsafe_function(env, + callback, + resource, + Value::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + wrapper, + context, + CallJS, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, ThreadSafeFunction()); + } + + return tsfn; +} + +inline napi_status ThreadSafeFunction::CallInternal( + CallbackWrapper* callbackWrapper, + napi_threadsafe_function_call_mode mode) const { + napi_status status = + napi_call_threadsafe_function(_tsfn, callbackWrapper, mode); + if (status != napi_ok && callbackWrapper != nullptr) { + delete callbackWrapper; + } + + return status; +} + +// static +inline void ThreadSafeFunction::CallJS(napi_env env, + napi_value jsCallback, + void* /* context */, + void* data) { + if (env == nullptr && jsCallback == nullptr) { + return; + } + + details::WrapVoidCallback(env, [&]() { + if (data != nullptr) { + auto* callbackWrapper = static_cast(data); + (*callbackWrapper)(env, Function(env, jsCallback)); + delete callbackWrapper; + } else if (jsCallback != nullptr) { + Function(env, jsCallback).Call({}); + } + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// Async Progress Worker Base class +//////////////////////////////////////////////////////////////////////////////// +template +inline AsyncProgressWorkerBase::AsyncProgressWorkerBase( + const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource, + size_t queue_size) + : AsyncWorker(receiver, callback, resource_name, resource) { + // Fill all possible arguments to work around ambiguous + // ThreadSafeFunction::New signatures. + _tsfn = ThreadSafeFunction::New(callback.Env(), + callback, + resource, + resource_name, + queue_size, + /** initialThreadCount */ 1, + /** context */ this, + OnThreadSafeFunctionFinalize, + /** finalizeData */ this); +} + +#if NAPI_VERSION > 4 +template +inline AsyncProgressWorkerBase::AsyncProgressWorkerBase( + Napi::Env env, + const char* resource_name, + const Object& resource, + size_t queue_size) + : AsyncWorker(env, resource_name, resource) { + // TODO: Once the changes to make the callback optional for threadsafe + // functions are available on all versions we can remove the dummy Function + // here. + Function callback; + // Fill all possible arguments to work around ambiguous + // ThreadSafeFunction::New signatures. + _tsfn = ThreadSafeFunction::New(env, + callback, + resource, + resource_name, + queue_size, + /** initialThreadCount */ 1, + /** context */ this, + OnThreadSafeFunctionFinalize, + /** finalizeData */ this); +} +#endif + +template +inline AsyncProgressWorkerBase::~AsyncProgressWorkerBase() { + // Abort pending tsfn call. + // Don't send progress events after we've already completed. + // It's ok to call ThreadSafeFunction::Abort and ThreadSafeFunction::Release + // duplicated. + _tsfn.Abort(); +} + +template +inline void AsyncProgressWorkerBase::OnAsyncWorkProgress( + Napi::Env /* env */, Napi::Function /* jsCallback */, void* data) { + ThreadSafeData* tsd = static_cast(data); + tsd->asyncprogressworker()->OnWorkProgress(tsd->data()); + delete tsd; +} + +template +inline napi_status AsyncProgressWorkerBase::NonBlockingCall( + DataType* data) { + auto tsd = new AsyncProgressWorkerBase::ThreadSafeData(this, data); + auto ret = _tsfn.NonBlockingCall(tsd, OnAsyncWorkProgress); + if (ret != napi_ok) { + delete tsd; + } + return ret; +} + +template +inline void AsyncProgressWorkerBase::OnWorkComplete( + Napi::Env /* env */, napi_status status) { + _work_completed = true; + _complete_status = status; + _tsfn.Release(); +} + +template +inline void AsyncProgressWorkerBase::OnThreadSafeFunctionFinalize( + Napi::Env env, void* /* data */, AsyncProgressWorkerBase* context) { + if (context->_work_completed) { + context->AsyncWorker::OnWorkComplete(env, context->_complete_status); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Async Progress Worker class +//////////////////////////////////////////////////////////////////////////////// +template +inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback) + : AsyncProgressWorker(callback, "generic") {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback, + const char* resource_name) + : AsyncProgressWorker( + callback, resource_name, Object::New(callback.Env())) {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncProgressWorker( + Object::New(callback.Env()), callback, resource_name, resource) {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, + const Function& callback) + : AsyncProgressWorker(receiver, callback, "generic") {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name) + : AsyncProgressWorker( + receiver, callback, resource_name, Object::New(callback.Env())) {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncProgressWorkerBase(receiver, callback, resource_name, resource), + _asyncdata(nullptr), + _asyncsize(0), + _signaled(false) {} + +#if NAPI_VERSION > 4 +template +inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env) + : AsyncProgressWorker(env, "generic") {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env, + const char* resource_name) + : AsyncProgressWorker(env, resource_name, Object::New(env)) {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env, + const char* resource_name, + const Object& resource) + : AsyncProgressWorkerBase(env, resource_name, resource), + _asyncdata(nullptr), + _asyncsize(0) {} +#endif + +template +inline AsyncProgressWorker::~AsyncProgressWorker() { + { + std::lock_guard lock(this->_mutex); + _asyncdata = nullptr; + _asyncsize = 0; + } +} + +template +inline void AsyncProgressWorker::Execute() { + ExecutionProgress progress(this); + Execute(progress); +} + +template +inline void AsyncProgressWorker::OnWorkProgress(void*) { + T* data; + size_t size; + bool signaled; + { + std::lock_guard lock(this->_mutex); + data = this->_asyncdata; + size = this->_asyncsize; + signaled = this->_signaled; + this->_asyncdata = nullptr; + this->_asyncsize = 0; + this->_signaled = false; + } + + /** + * The callback of ThreadSafeFunction is not been invoked immediately on the + * callback of uv_async_t (uv io poll), rather the callback of TSFN is + * invoked on the right next uv idle callback. There are chances that during + * the deferring the signal of uv_async_t is been sent again, i.e. potential + * not coalesced two calls of the TSFN callback. + */ + if (data == nullptr && !signaled) { + return; + } + + this->OnProgress(data, size); + delete[] data; +} + +template +inline void AsyncProgressWorker::SendProgress_(const T* data, size_t count) { + T* new_data = new T[count]; + std::copy(data, data + count, new_data); + + T* old_data; + { + std::lock_guard lock(this->_mutex); + old_data = _asyncdata; + _asyncdata = new_data; + _asyncsize = count; + _signaled = false; + } + this->NonBlockingCall(nullptr); + + delete[] old_data; +} + +template +inline void AsyncProgressWorker::Signal() { + { + std::lock_guard lock(this->_mutex); + _signaled = true; + } + this->NonBlockingCall(static_cast(nullptr)); +} + +template +inline void AsyncProgressWorker::ExecutionProgress::Signal() const { + this->_worker->Signal(); +} + +template +inline void AsyncProgressWorker::ExecutionProgress::Send( + const T* data, size_t count) const { + _worker->SendProgress_(data, count); +} + +//////////////////////////////////////////////////////////////////////////////// +// Async Progress Queue Worker class +//////////////////////////////////////////////////////////////////////////////// +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Function& callback) + : AsyncProgressQueueWorker(callback, "generic") {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Function& callback, const char* resource_name) + : AsyncProgressQueueWorker( + callback, resource_name, Object::New(callback.Env())) {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Function& callback, const char* resource_name, const Object& resource) + : AsyncProgressQueueWorker( + Object::New(callback.Env()), callback, resource_name, resource) {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Object& receiver, const Function& callback) + : AsyncProgressQueueWorker(receiver, callback, "generic") {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Object& receiver, const Function& callback, const char* resource_name) + : AsyncProgressQueueWorker( + receiver, callback, resource_name, Object::New(callback.Env())) {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncProgressWorkerBase>( + receiver, + callback, + resource_name, + resource, + /** unlimited queue size */ 0) {} + +#if NAPI_VERSION > 4 +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(Napi::Env env) + : AsyncProgressQueueWorker(env, "generic") {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + Napi::Env env, const char* resource_name) + : AsyncProgressQueueWorker(env, resource_name, Object::New(env)) {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + Napi::Env env, const char* resource_name, const Object& resource) + : AsyncProgressWorkerBase>( + env, resource_name, resource, /** unlimited queue size */ 0) {} +#endif + +template +inline void AsyncProgressQueueWorker::Execute() { + ExecutionProgress progress(this); + Execute(progress); +} + +template +inline void AsyncProgressQueueWorker::OnWorkProgress( + std::pair* datapair) { + if (datapair == nullptr) { + return; + } + + T* data = datapair->first; + size_t size = datapair->second; + + this->OnProgress(data, size); + delete datapair; + delete[] data; +} + +template +inline void AsyncProgressQueueWorker::SendProgress_(const T* data, + size_t count) { + T* new_data = new T[count]; + std::copy(data, data + count, new_data); + + auto pair = new std::pair(new_data, count); + this->NonBlockingCall(pair); +} + +template +inline void AsyncProgressQueueWorker::Signal() const { + this->SendProgress_(static_cast(nullptr), 0); +} + +template +inline void AsyncProgressQueueWorker::OnWorkComplete(Napi::Env env, + napi_status status) { + // Draining queued items in TSFN. + AsyncProgressWorkerBase>::OnWorkComplete(env, status); +} + +template +inline void AsyncProgressQueueWorker::ExecutionProgress::Signal() const { + _worker->SendProgress_(static_cast(nullptr), 0); +} + +template +inline void AsyncProgressQueueWorker::ExecutionProgress::Send( + const T* data, size_t count) const { + _worker->SendProgress_(data, count); +} +#endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS + +//////////////////////////////////////////////////////////////////////////////// +// Memory Management class +//////////////////////////////////////////////////////////////////////////////// + +inline int64_t MemoryManagement::AdjustExternalMemory(BasicEnv env, + int64_t change_in_bytes) { + int64_t result; + napi_status status = + napi_adjust_external_memory(env, change_in_bytes, &result); + NAPI_FATAL_IF_FAILED(status, + "MemoryManagement::AdjustExternalMemory", + "napi_adjust_external_memory"); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// Version Management class +//////////////////////////////////////////////////////////////////////////////// + +inline uint32_t VersionManagement::GetNapiVersion(BasicEnv env) { + uint32_t result; + napi_status status = napi_get_version(env, &result); + NAPI_FATAL_IF_FAILED( + status, "VersionManagement::GetNapiVersion", "napi_get_version"); + return result; +} + +inline const napi_node_version* VersionManagement::GetNodeVersion( + BasicEnv env) { + const napi_node_version* result; + napi_status status = napi_get_node_version(env, &result); + NAPI_FATAL_IF_FAILED( + status, "VersionManagement::GetNodeVersion", "napi_get_node_version"); + return result; +} + +#if NAPI_VERSION > 5 +//////////////////////////////////////////////////////////////////////////////// +// Addon class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Object Addon::Init(Env env, Object exports) { + T* addon = new T(env, exports); + env.SetInstanceData(addon); + return addon->entry_point_; +} + +template +inline T* Addon::Unwrap(Object wrapper) { + return wrapper.Env().GetInstanceData(); +} + +template +inline void Addon::DefineAddon( + Object exports, const std::initializer_list& props) { + DefineProperties(exports, props); + entry_point_ = exports; +} + +template +inline Napi::Object Addon::DefineProperties( + Object object, const std::initializer_list& props) { + const napi_property_descriptor* properties = + reinterpret_cast(props.begin()); + size_t size = props.size(); + napi_status status = + napi_define_properties(object.Env(), object, size, properties); + NAPI_THROW_IF_FAILED(object.Env(), status, object); + for (size_t idx = 0; idx < size; idx++) + T::AttachPropData(object.Env(), object, &properties[idx]); + return object; +} +#endif // NAPI_VERSION > 5 + +#if NAPI_VERSION > 2 +template +Env::CleanupHook BasicEnv::AddCleanupHook(Hook hook, Arg* arg) { + return CleanupHook(*this, hook, arg); +} + +template +Env::CleanupHook BasicEnv::AddCleanupHook(Hook hook) { + return CleanupHook(*this, hook); +} + +template +Env::CleanupHook::CleanupHook() { + data = nullptr; +} + +template +Env::CleanupHook::CleanupHook(Napi::BasicEnv env, Hook hook) + : wrapper(Env::CleanupHook::Wrapper) { + data = new CleanupData{std::move(hook), nullptr}; + napi_status status = napi_add_env_cleanup_hook(env, wrapper, data); + if (status != napi_ok) { + delete data; + data = nullptr; + } +} + +template +Env::CleanupHook::CleanupHook(Napi::BasicEnv env, + Hook hook, + Arg* arg) + : wrapper(Env::CleanupHook::WrapperWithArg) { + data = new CleanupData{std::move(hook), arg}; + napi_status status = napi_add_env_cleanup_hook(env, wrapper, data); + if (status != napi_ok) { + delete data; + data = nullptr; + } +} + +template +bool Env::CleanupHook::Remove(BasicEnv env) { + napi_status status = napi_remove_env_cleanup_hook(env, wrapper, data); + delete data; + data = nullptr; + return status == napi_ok; +} + +template +bool Env::CleanupHook::IsEmpty() const { + return data == nullptr; +} +#endif // NAPI_VERSION > 2 + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER +template +inline void BasicEnv::PostFinalizer(FinalizerType finalizeCallback) const { + using T = void*; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + + napi_status status = node_api_post_finalizer( + _env, + details::FinalizeData::WrapperGCWithoutData, + static_cast(nullptr), + finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::PostFinalizer", "invalid arguments"); + } +} + +template +inline void BasicEnv::PostFinalizer(FinalizerType finalizeCallback, + T* data) const { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + + napi_status status = node_api_post_finalizer( + _env, + details::FinalizeData::WrapperGC, + data, + finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::PostFinalizer", "invalid arguments"); + } +} + +template +inline void BasicEnv::PostFinalizer(FinalizerType finalizeCallback, + T* data, + Hint* finalizeHint) const { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = node_api_post_finalizer( + _env, + details::FinalizeData::WrapperGCWithHint, + data, + finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_FATAL_IF_FAILED( + status, "BasicEnv::PostFinalizer", "invalid arguments"); + } +} +#endif // NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + +#ifdef NAPI_CPP_CUSTOM_NAMESPACE +} // namespace NAPI_CPP_CUSTOM_NAMESPACE +#endif + +} // namespace Napi + +#undef NAPI_NO_SANITIZE_VPTR + +#endif // SRC_NAPI_INL_H_ diff --git a/test/node-addon-api/napi.h b/test/node-addon-api/napi.h new file mode 100644 index 0000000..c534743 --- /dev/null +++ b/test/node-addon-api/napi.h @@ -0,0 +1,3463 @@ +#ifndef SRC_NAPI_H_ +#define SRC_NAPI_H_ + +#ifndef NAPI_HAS_THREADS +#if !defined(__wasm__) || (defined(__EMSCRIPTEN_PTHREADS__) || \ + (defined(__wasi__) && defined(_REENTRANT))) +#define NAPI_HAS_THREADS 1 +#else +#define NAPI_HAS_THREADS 0 +#endif +#endif + +#include +#include +#include +#include +#if NAPI_HAS_THREADS +#include +#endif // NAPI_HAS_THREADS +#include +#include +#include +#include +#include +#include + +// VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known +// good version) +#if !defined(_MSC_VER) || _MSC_FULL_VER >= 190024210 +#define NAPI_HAS_CONSTEXPR 1 +#endif + +// VS2013 does not support char16_t literal strings, so we'll work around it +// using wchar_t strings and casting them. This is safe as long as the character +// sizes are the same. +#if defined(_MSC_VER) && _MSC_VER <= 1800 +static_assert(sizeof(char16_t) == sizeof(wchar_t), + "Size mismatch between char16_t and wchar_t"); +#define NAPI_WIDE_TEXT(x) reinterpret_cast(L##x) +#else +#define NAPI_WIDE_TEXT(x) u##x +#endif + +// Backwards-compatibility to handle the rename of this macro definition, in +// case they are used within userland code. +#ifdef NAPI_CPP_EXCEPTIONS +#define NODE_ADDON_API_CPP_EXCEPTIONS +#endif +#if defined(NODE_ADDON_API_CPP_EXCEPTIONS) && !defined(NAPI_CPP_EXCEPTIONS) +#define NAPI_CPP_EXCEPTIONS +#endif +#ifdef NAPI_DISABLE_CPP_EXCEPTIONS +#define NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS +#endif +#if defined(NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS) && \ + !defined(NAPI_DISABLE_CPP_EXCEPTIONS) +#define NAPI_DISABLE_CPP_EXCEPTIONS +#endif + +// If C++ exceptions are not explicitly enabled or disabled, enable them +// if exceptions were enabled in the compiler settings. +#if !defined(NODE_ADDON_API_CPP_EXCEPTIONS) && \ + !defined(NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS) +#if defined(_CPPUNWIND) || defined(__EXCEPTIONS) +#define NODE_ADDON_API_CPP_EXCEPTIONS +#else +#error Exception support not detected. \ + Define either NODE_ADDON_API_CPP_EXCEPTIONS or NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS. +#endif +#endif + +// If C++ NODE_ADDON_API_CPP_EXCEPTIONS are enabled, NODE_ADDON_API_ENABLE_MAYBE +// should not be set +#if defined(NODE_ADDON_API_CPP_EXCEPTIONS) && \ + defined(NODE_ADDON_API_ENABLE_MAYBE) +#error NODE_ADDON_API_ENABLE_MAYBE should not be set when \ + NODE_ADDON_API_CPP_EXCEPTIONS is defined. +#endif + +#ifdef _NOEXCEPT +#define NAPI_NOEXCEPT _NOEXCEPT +#else +#define NAPI_NOEXCEPT noexcept +#endif + +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + +// When C++ exceptions are enabled, Errors are thrown directly. There is no need +// to return anything after the throw statements. The variadic parameter is an +// optional return value that is ignored. +// We need _VOID versions of the macros to avoid warnings resulting from +// leaving the NAPI_THROW_* `...` argument empty. + +#define NAPI_THROW(e, ...) throw e +#define NAPI_THROW_VOID(e) throw e + +#define NAPI_THROW_IF_FAILED(env, status, ...) \ + if ((status) != napi_ok) throw Napi::Error::New(env); + +#define NAPI_THROW_IF_FAILED_VOID(env, status) \ + if ((status) != napi_ok) throw Napi::Error::New(env); + +#else // NODE_ADDON_API_CPP_EXCEPTIONS + +// When C++ exceptions are disabled, Errors are thrown as JavaScript exceptions, +// which are pending until the callback returns to JS. The variadic parameter +// is an optional return value; usually it is an empty result. +// We need _VOID versions of the macros to avoid warnings resulting from +// leaving the NAPI_THROW_* `...` argument empty. + +#define NAPI_THROW(e, ...) \ + do { \ + (e).ThrowAsJavaScriptException(); \ + return __VA_ARGS__; \ + } while (0) + +#define NAPI_THROW_VOID(e) \ + do { \ + (e).ThrowAsJavaScriptException(); \ + return; \ + } while (0) + +#define NAPI_THROW_IF_FAILED(env, status, ...) \ + if ((status) != napi_ok) { \ + Napi::Error::New(env).ThrowAsJavaScriptException(); \ + return __VA_ARGS__; \ + } + +#define NAPI_THROW_IF_FAILED_VOID(env, status) \ + if ((status) != napi_ok) { \ + Napi::Error::New(env).ThrowAsJavaScriptException(); \ + return; \ + } + +#endif // NODE_ADDON_API_CPP_EXCEPTIONS + +#ifdef NODE_ADDON_API_ENABLE_MAYBE +#define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \ + NAPI_THROW_IF_FAILED(env, status, Napi::Nothing()) + +#define NAPI_RETURN_OR_THROW_IF_FAILED(env, status, result, type) \ + NAPI_MAYBE_THROW_IF_FAILED(env, status, type); \ + return Napi::Just(result); +#else +#define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \ + NAPI_THROW_IF_FAILED(env, status, type()) + +#define NAPI_RETURN_OR_THROW_IF_FAILED(env, status, result, type) \ + NAPI_MAYBE_THROW_IF_FAILED(env, status, type); \ + return result; +#endif + +#define NAPI_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete; +#define NAPI_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete; + +#define NAPI_DISALLOW_ASSIGN_COPY(CLASS) \ + NAPI_DISALLOW_ASSIGN(CLASS) \ + NAPI_DISALLOW_COPY(CLASS) + +#define NAPI_CHECK(condition, location, message) \ + do { \ + if (!(condition)) { \ + Napi::Error::Fatal((location), (message)); \ + } \ + } while (0) + +// Internal check helper. Be careful that the formatted message length should be +// max 255 size and null terminated. +#define NAPI_INTERNAL_CHECK(expr, location, ...) \ + do { \ + if (!(expr)) { \ + std::string msg = Napi::details::StringFormat(__VA_ARGS__); \ + Napi::Error::Fatal(location, msg.c_str()); \ + } \ + } while (0) + +#define NAPI_INTERNAL_CHECK_EQ(actual, expected, value_format, location) \ + do { \ + auto actual_value = (actual); \ + NAPI_INTERNAL_CHECK(actual_value == (expected), \ + location, \ + "Expected " #actual " to be equal to " #expected \ + ", but got " value_format ".", \ + actual_value); \ + } while (0) + +#define NAPI_FATAL_IF_FAILED(status, location, message) \ + NAPI_CHECK((status) == napi_ok, location, message) + +//////////////////////////////////////////////////////////////////////////////// +/// Node-API C++ Wrapper Classes +/// +/// These classes wrap the "Node-API" ABI-stable C APIs for Node.js, providing a +/// C++ object model and C++ exception-handling semantics with low overhead. +/// The wrappers are all header-only so that they do not affect the ABI. +//////////////////////////////////////////////////////////////////////////////// +namespace Napi { + +#ifdef NAPI_CPP_CUSTOM_NAMESPACE +// NAPI_CPP_CUSTOM_NAMESPACE can be #define'd per-addon to avoid symbol +// conflicts between different instances of node-addon-api + +// First dummy definition of the namespace to make sure that Napi::(name) still +// refers to the right things inside this file. +namespace NAPI_CPP_CUSTOM_NAMESPACE {} +using namespace NAPI_CPP_CUSTOM_NAMESPACE; + +namespace NAPI_CPP_CUSTOM_NAMESPACE { +#endif + +// Forward declarations +class Env; +class Value; +class Boolean; +class Number; +#if NAPI_VERSION > 5 +class BigInt; +#endif // NAPI_VERSION > 5 +#if (NAPI_VERSION > 4) +class Date; +#endif +class String; +class Object; +class Array; +class ArrayBuffer; +class Function; +class Error; +class PropertyDescriptor; +class CallbackInfo; +class TypedArray; +template +class TypedArrayOf; + +using Int8Array = + TypedArrayOf; ///< Typed-array of signed 8-bit integers +using Uint8Array = + TypedArrayOf; ///< Typed-array of unsigned 8-bit integers +using Int16Array = + TypedArrayOf; ///< Typed-array of signed 16-bit integers +using Uint16Array = + TypedArrayOf; ///< Typed-array of unsigned 16-bit integers +using Int32Array = + TypedArrayOf; ///< Typed-array of signed 32-bit integers +using Uint32Array = + TypedArrayOf; ///< Typed-array of unsigned 32-bit integers +using Float32Array = + TypedArrayOf; ///< Typed-array of 32-bit floating-point values +using Float64Array = + TypedArrayOf; ///< Typed-array of 64-bit floating-point values +#if NAPI_VERSION > 5 +using BigInt64Array = + TypedArrayOf; ///< Typed array of signed 64-bit integers +using BigUint64Array = + TypedArrayOf; ///< Typed array of unsigned 64-bit integers +#endif // NAPI_VERSION > 5 + +/// Defines the signature of a Node-API C++ module's registration callback +/// (init) function. +using ModuleRegisterCallback = Object (*)(Env env, Object exports); + +class MemoryManagement; + +/// A simple Maybe type, representing an object which may or may not have a +/// value. +/// +/// If an API method returns a Maybe<>, the API method can potentially fail +/// either because an exception is thrown, or because an exception is pending, +/// e.g. because a previous API call threw an exception that hasn't been +/// caught yet. In that case, a "Nothing" value is returned. +template +class Maybe { + public: + bool IsNothing() const; + bool IsJust() const; + + /// Short-hand for Unwrap(), which doesn't return a value. Could be used + /// where the actual value of the Maybe is not needed like Object::Set. + /// If this Maybe is nothing (empty), node-addon-api will crash the + /// process. + void Check() const; + + /// Return the value of type T contained in the Maybe. If this Maybe is + /// nothing (empty), node-addon-api will crash the process. + T Unwrap() const; + + /// Return the value of type T contained in the Maybe, or using a default + /// value if this Maybe is nothing (empty). + T UnwrapOr(const T& default_value) const; + + /// Converts this Maybe to a value of type T in the out. If this Maybe is + /// nothing (empty), `false` is returned and `out` is left untouched. + bool UnwrapTo(T* out) const; + + bool operator==(const Maybe& other) const; + bool operator!=(const Maybe& other) const; + + private: + Maybe(); + explicit Maybe(const T& t); + + bool _has_value; + T _value; + + template + friend Maybe Nothing(); + template + friend Maybe Just(const U& u); +}; + +template +inline Maybe Nothing(); + +template +inline Maybe Just(const T& t); + +#if defined(NODE_ADDON_API_ENABLE_MAYBE) +template +using MaybeOrValue = Maybe; +#else +template +using MaybeOrValue = T; +#endif + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER +using node_addon_api_basic_env = node_api_nogc_env; +using node_addon_api_basic_finalize = node_api_nogc_finalize; +#else +using node_addon_api_basic_env = napi_env; +using node_addon_api_basic_finalize = napi_finalize; +#endif + +/// Environment for Node-API values and operations. +/// +/// All Node-API values and operations must be associated with an environment. +/// An environment instance is always provided to callback functions; that +/// environment must then be used for any creation of Node-API values or other +/// Node-API operations within the callback. (Many methods infer the +/// environment from the `this` instance that the method is called on.) +/// +/// Multiple environments may co-exist in a single process or a thread. +/// +/// In the V8 JavaScript engine, a Node-API environment approximately +/// corresponds to an Isolate. +class BasicEnv { + private: + node_addon_api_basic_env _env; +#if NAPI_VERSION > 5 + template + static void DefaultFini(Env, T* data); + template + static void DefaultFiniWithHint(Env, DataType* data, HintType* hint); +#endif // NAPI_VERSION > 5 + public: + BasicEnv(node_addon_api_basic_env env); + + operator node_addon_api_basic_env() const; + + // Without these operator overloads, the error: + // + // Use of overloaded operator '==' is ambiguous (with operand types + // 'Napi::Env' and 'Napi::Env') + // + // ... occurs when comparing foo.Env() == bar.Env() or foo.Env() == nullptr + bool operator==(const BasicEnv& other) const { + return _env == other._env; + } + bool operator==(std::nullptr_t /*other*/) const { + return _env == nullptr; + } + +#if NAPI_VERSION > 2 + template + class CleanupHook; + + template + CleanupHook AddCleanupHook(Hook hook); + + template + CleanupHook AddCleanupHook(Hook hook, Arg* arg); +#endif // NAPI_VERSION > 2 + +#if NAPI_VERSION > 5 + template + T* GetInstanceData() const; + + template + using Finalizer = void (*)(Env, T*); + template fini = BasicEnv::DefaultFini> + void SetInstanceData(T* data) const; + + template + using FinalizerWithHint = void (*)(Env, DataType*, HintType*); + template fini = + BasicEnv::DefaultFiniWithHint> + void SetInstanceData(DataType* data, HintType* hint) const; +#endif // NAPI_VERSION > 5 + +#if NAPI_VERSION > 2 + template + class CleanupHook { + public: + CleanupHook(); + CleanupHook(BasicEnv env, Hook hook, Arg* arg); + CleanupHook(BasicEnv env, Hook hook); + bool Remove(BasicEnv env); + bool IsEmpty() const; + + private: + static inline void Wrapper(void* data) NAPI_NOEXCEPT; + static inline void WrapperWithArg(void* data) NAPI_NOEXCEPT; + + void (*wrapper)(void* arg); + struct CleanupData { + Hook hook; + Arg* arg; + } * data; + }; +#endif // NAPI_VERSION > 2 + +#if NAPI_VERSION > 8 + const char* GetModuleFileName() const; +#endif // NAPI_VERSION > 8 + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + template + inline void PostFinalizer(FinalizerType finalizeCallback) const; + + template + inline void PostFinalizer(FinalizerType finalizeCallback, T* data) const; + + template + inline void PostFinalizer(FinalizerType finalizeCallback, + T* data, + Hint* finalizeHint) const; +#endif // NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + + friend class Env; +}; + +class Env : public BasicEnv { + public: + Env(napi_env env); + + operator napi_env() const; + + Object Global() const; + Value Undefined() const; + Value Null() const; + + bool IsExceptionPending() const; + Error GetAndClearPendingException() const; + + MaybeOrValue RunScript(const char* utf8script) const; + MaybeOrValue RunScript(const std::string& utf8script) const; + MaybeOrValue RunScript(String script) const; +}; + +/// A JavaScript value of unknown type. +/// +/// For type-specific operations, convert to one of the Value subclasses using a +/// `To*` or `As()` method. The `To*` methods do type coercion; the `As()` +/// method does not. +/// +/// Napi::Value value = ... +/// if (!value.IsString()) throw Napi::TypeError::New(env, "Invalid +/// arg..."); Napi::String str = value.As(); // Cast to a +/// string value +/// +/// Napi::Value anotherValue = ... +/// bool isTruthy = anotherValue.ToBoolean(); // Coerce to a boolean value +class Value { + public: + Value(); ///< Creates a new _empty_ Value instance. + Value(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + /// Creates a JS value from a C++ primitive. + /// + /// `value` may be any of: + /// - bool + /// - Any integer type + /// - Any floating point type + /// - const char* (encoded using UTF-8, null-terminated) + /// - const char16_t* (encoded using UTF-16-LE, null-terminated) + /// - std::string (encoded using UTF-8) + /// - std::u16string + /// - napi::Value + /// - napi_value + template + static Value From(napi_env env, const T& value); + + static void CheckCast(napi_env env, napi_value value); + + /// Converts to a Node-API value primitive. + /// + /// If the instance is _empty_, this returns `nullptr`. + operator napi_value() const; + + /// Tests if this value strictly equals another value. + bool operator==(const Value& other) const; + + /// Tests if this value does not strictly equal another value. + bool operator!=(const Value& other) const; + + /// Tests if this value strictly equals another value. + bool StrictEquals(const Value& other) const; + + /// Gets the environment the value is associated with. + Napi::Env Env() const; + + /// Checks if the value is empty (uninitialized). + /// + /// An empty value is invalid, and most attempts to perform an operation on an + /// empty value will result in an exception. Note an empty value is distinct + /// from JavaScript `null` or `undefined`, which are valid values. + /// + /// When C++ exceptions are disabled at compile time, a method with a `Value` + /// return type may return an empty value to indicate a pending exception. So + /// when not using C++ exceptions, callers should check whether the value is + /// empty before attempting to use it. + bool IsEmpty() const; + + napi_valuetype Type() const; ///< Gets the type of the value. + + bool IsUndefined() + const; ///< Tests if a value is an undefined JavaScript value. + bool IsNull() const; ///< Tests if a value is a null JavaScript value. + bool IsBoolean() const; ///< Tests if a value is a JavaScript boolean. + bool IsNumber() const; ///< Tests if a value is a JavaScript number. +#if NAPI_VERSION > 5 + bool IsBigInt() const; ///< Tests if a value is a JavaScript bigint. +#endif // NAPI_VERSION > 5 +#if (NAPI_VERSION > 4) + bool IsDate() const; ///< Tests if a value is a JavaScript date. +#endif + bool IsString() const; ///< Tests if a value is a JavaScript string. + bool IsSymbol() const; ///< Tests if a value is a JavaScript symbol. + bool IsArray() const; ///< Tests if a value is a JavaScript array. + bool IsArrayBuffer() + const; ///< Tests if a value is a JavaScript array buffer. + bool IsTypedArray() const; ///< Tests if a value is a JavaScript typed array. + bool IsObject() const; ///< Tests if a value is a JavaScript object. + bool IsFunction() const; ///< Tests if a value is a JavaScript function. + bool IsPromise() const; ///< Tests if a value is a JavaScript promise. + bool IsDataView() const; ///< Tests if a value is a JavaScript data view. + bool IsBuffer() const; ///< Tests if a value is a Node buffer. + bool IsExternal() const; ///< Tests if a value is a pointer to external data. +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + bool IsSharedArrayBuffer() const; +#endif + + /// Casts to another type of `Napi::Value`, when the actual type is known or + /// assumed. + /// + /// This conversion does NOT coerce the type. Calling any methods + /// inappropriate for the actual value type will throw `Napi::Error`. + /// + /// If `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` is defined, this method + /// asserts that the actual type is the expected type. + template + T As() const; + + // Unsafe Value::As(), should be avoided. + template + T UnsafeAs() const; + + MaybeOrValue ToBoolean() + const; ///< Coerces a value to a JavaScript boolean. + MaybeOrValue ToNumber() + const; ///< Coerces a value to a JavaScript number. + MaybeOrValue ToString() + const; ///< Coerces a value to a JavaScript string. + MaybeOrValue ToObject() + const; ///< Coerces a value to a JavaScript object. + + protected: + /// !cond INTERNAL + napi_env _env; + napi_value _value; + /// !endcond +}; + +/// A JavaScript boolean value. +class Boolean : public Value { + public: + static Boolean New(napi_env env, ///< Node-API environment + bool value ///< Boolean value + ); + + static void CheckCast(napi_env env, napi_value value); + + Boolean(); ///< Creates a new _empty_ Boolean instance. + Boolean(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + operator bool() const; ///< Converts a Boolean value to a boolean primitive. + bool Value() const; ///< Converts a Boolean value to a boolean primitive. +}; + +/// A JavaScript number value. +class Number : public Value { + public: + static Number New(napi_env env, ///< Node-API environment + double value ///< Number value + ); + + static void CheckCast(napi_env env, napi_value value); + + Number(); ///< Creates a new _empty_ Number instance. + Number(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + operator int32_t() + const; ///< Converts a Number value to a 32-bit signed integer value. + operator uint32_t() + const; ///< Converts a Number value to a 32-bit unsigned integer value. + operator int64_t() + const; ///< Converts a Number value to a 64-bit signed integer value. + operator float() + const; ///< Converts a Number value to a 32-bit floating-point value. + operator double() + const; ///< Converts a Number value to a 64-bit floating-point value. + + int32_t Int32Value() + const; ///< Converts a Number value to a 32-bit signed integer value. + uint32_t Uint32Value() + const; ///< Converts a Number value to a 32-bit unsigned integer value. + int64_t Int64Value() + const; ///< Converts a Number value to a 64-bit signed integer value. + float FloatValue() + const; ///< Converts a Number value to a 32-bit floating-point value. + double DoubleValue() + const; ///< Converts a Number value to a 64-bit floating-point value. +}; + +#if NAPI_VERSION > 5 +/// A JavaScript bigint value. +class BigInt : public Value { + public: + static BigInt New(napi_env env, ///< Node-API environment + int64_t value ///< Number value + ); + static BigInt New(napi_env env, ///< Node-API environment + uint64_t value ///< Number value + ); + + /// Creates a new BigInt object using a specified sign bit and a + /// specified list of digits/words. + /// The resulting number is calculated as: + /// (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...) + static BigInt New(napi_env env, ///< Node-API environment + int sign_bit, ///< Sign bit. 1 if negative. + size_t word_count, ///< Number of words in array + const uint64_t* words ///< Array of words + ); + + static void CheckCast(napi_env env, napi_value value); + + BigInt(); ///< Creates a new _empty_ BigInt instance. + BigInt(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + int64_t Int64Value(bool* lossless) + const; ///< Converts a BigInt value to a 64-bit signed integer value. + uint64_t Uint64Value(bool* lossless) + const; ///< Converts a BigInt value to a 64-bit unsigned integer value. + + size_t WordCount() const; ///< The number of 64-bit words needed to store + ///< the result of ToWords(). + + /// Writes the contents of this BigInt to a specified memory location. + /// `sign_bit` must be provided and will be set to 1 if this BigInt is + /// negative. + /// `*word_count` has to 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 (i.e. the return value of `WordCount()`). + void ToWords(int* sign_bit, size_t* word_count, uint64_t* words); +}; +#endif // NAPI_VERSION > 5 + +#if (NAPI_VERSION > 4) +/// A JavaScript date value. +class Date : public Value { + public: + /// Creates a new Date value from a double primitive. + static Date New(napi_env env, ///< Node-API environment + double value ///< Number value + ); + + /// Creates a new Date value from a std::chrono::system_clock::time_point. + static Date New( + napi_env env, ///< Node-API environment + std::chrono::system_clock::time_point time_point ///< Time point value + ); + + static void CheckCast(napi_env env, napi_value value); + + Date(); ///< Creates a new _empty_ Date instance. + Date(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. + operator double() const; ///< Converts a Date value to double primitive + + double ValueOf() const; ///< Converts a Date value to a double primitive. +}; +#endif + +/// A JavaScript string or symbol value (that can be used as a property name). +class Name : public Value { + public: + static void CheckCast(napi_env env, napi_value value); + + Name(); ///< Creates a new _empty_ Name instance. + Name(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. +}; + +/// A JavaScript string value. +class String : public Name { + public: + /// Creates a new String value from a UTF-8 encoded C++ string. + static String New(napi_env env, ///< Node-API environment + const std::string& value ///< UTF-8 encoded C++ string + ); + + /// Creates a new String value from a UTF-16 encoded C++ string. + static String New(napi_env env, ///< Node-API environment + const std::u16string& value ///< UTF-16 encoded C++ string + ); + + /// Creates a new String value from a UTF-8 encoded C++ string view. + static String New(napi_env env, ///< Node-API environment + std::string_view value ///< UTF-8 encoded C++ string view + ); + + /// Creates a new String value from a UTF-8 encoded C string. + static String New( + napi_env env, ///< Node-API environment + const char* value ///< UTF-8 encoded null-terminated C string + ); + + /// Creates a new String value from a UTF-16 encoded C string. + static String New( + napi_env env, ///< Node-API environment + const char16_t* value ///< UTF-16 encoded null-terminated C string + ); + + /// Creates a new String value from a UTF-8 encoded C string with specified + /// length. + static String New(napi_env env, ///< Node-API environment + const char* value, ///< UTF-8 encoded C string (not + ///< necessarily null-terminated) + size_t length ///< length of the string in bytes + ); + + /// Creates a new String value from a UTF-16 encoded C string with specified + /// length. + static String New( + napi_env env, ///< Node-API environment + const char16_t* value, ///< UTF-16 encoded C string (not necessarily + ///< null-terminated) + size_t length ///< Length of the string in 2-byte code units + ); + + /// Creates a new String based on the original object's type. + /// + /// `value` may be any of: + /// - const char* (encoded using UTF-8, null-terminated) + /// - const char16_t* (encoded using UTF-16-LE, null-terminated) + /// - std::string (encoded using UTF-8) + /// - std::u16string + template + static String From(napi_env env, const T& value); + + static void CheckCast(napi_env env, napi_value value); + + String(); ///< Creates a new _empty_ String instance. + String(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + operator std::string() + const; ///< Converts a String value to a UTF-8 encoded C++ string. + operator std::u16string() + const; ///< Converts a String value to a UTF-16 encoded C++ string. + std::string Utf8Value() + const; ///< Converts a String value to a UTF-8 encoded C++ string. + std::u16string Utf16Value() + const; ///< Converts a String value to a UTF-16 encoded C++ string. +}; + +namespace details { + +// This overload set must mirror the non-template Symbol::For overloads. +struct string_convertible_probe { + static void select(const std::string&); + static void select(std::string_view); + static void select(const char*); + static void select(String); + static void select(napi_value); +}; + +template +struct has_unambiguous_string_convertible_overload : std::false_type {}; + +template +struct has_unambiguous_string_convertible_overload< + T, + std::void_t()))>> + : std::true_type {}; + +// Enable the template overload only for string-like arguments that have no +// unique best match among the non-template Symbol::For overloads. +// +// Exclude nullptr because it matches the pointer overloads equally well and +// cannot safely initialize a std::string_view. +template +using enable_if_ambiguous_string_convertible_t = + std::enable_if_t> && + std::is_convertible_v && + std::is_convertible_v && + !has_unambiguous_string_convertible_overload::value, + int>; + +} // namespace details + +/// A JavaScript symbol value. +class Symbol : public Name { + public: + /// Creates a new Symbol value with an optional description. + static Symbol New( + napi_env env, ///< Node-API environment + const char* description = + nullptr ///< Optional UTF-8 encoded null-terminated C string + /// describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< Node-API environment + const std::string& + description ///< UTF-8 encoded C++ string describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< Node-API environment + std::string_view + description ///< UTF-8 encoded C++ string view describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New(napi_env env, ///< Node-API environment + String description ///< String value describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< Node-API environment + napi_value description ///< String value describing the symbol + ); + + /// Get a public Symbol (e.g. Symbol.iterator). + static MaybeOrValue WellKnown(napi_env, const std::string& name); + + // Create a symbol in the global registry, UTF-8 Encoded cpp string + static MaybeOrValue For(napi_env env, const std::string& description); + + // Create a symbol in the global registry, UTF-8 encoded cpp string view + static MaybeOrValue For(napi_env env, std::string_view description); + + // Resolve otherwise ambiguous string-like arguments through the + // std::string_view overload + template = 0> + static MaybeOrValue For(napi_env env, T&& description); + + // Create a symbol in the global registry, C style string (null terminated) + static MaybeOrValue For(napi_env env, const char* description); + + // Create a symbol in the global registry, String value describing the symbol + static MaybeOrValue For(napi_env env, String description); + + // Create a symbol in the global registry, napi_value describing the symbol + static MaybeOrValue For(napi_env env, napi_value description); + + static void CheckCast(napi_env env, napi_value value); + + Symbol(); ///< Creates a new _empty_ Symbol instance. + Symbol(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. +}; + +class TypeTaggable : public Value { + public: +#if NAPI_VERSION >= 8 + void TypeTag(const napi_type_tag* type_tag) const; + bool CheckTypeTag(const napi_type_tag* type_tag) const; +#endif // NAPI_VERSION >= 8 + protected: + TypeTaggable(); + TypeTaggable(napi_env env, napi_value value); +}; + +/// A JavaScript object value. +class Object : public TypeTaggable { + public: + /// Enables property and element assignments using indexing syntax. + /// + /// This is a convenient helper to get and set object properties. As + /// getting and setting object properties may throw with JavaScript + /// exceptions, it is notable that these operations may fail. + /// When NODE_ADDON_API_ENABLE_MAYBE is defined, the process will abort + /// on JavaScript exceptions. + /// + /// Example: + /// + /// Napi::Value propertyValue = object1['A']; + /// object2['A'] = propertyValue; + /// Napi::Value elementValue = array[0]; + /// array[1] = elementValue; + template + class PropertyLValue { + public: + /// Converts an L-value to a value. + operator Value() const; + + /// Assigns a value to the property. The type of value can be + /// anything supported by `Object::Set`. + template + PropertyLValue& operator=(ValueType value); + + /// Converts an L-value to a value. For convenience. + Value AsValue() const; + + private: + PropertyLValue() = delete; + PropertyLValue(Object object, Key key); + napi_env _env; + napi_value _object; + Key _key; + + friend class Napi::Object; + }; + + /// Creates a new Object value. + static Object New(napi_env env ///< Node-API environment + ); + + static void CheckCast(napi_env env, napi_value value); + + Object(); ///< Creates a new _empty_ Object instance. + Object(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + /// Gets or sets a named property. + PropertyLValue operator[]( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ); + + /// Gets or sets a named property. + PropertyLValue operator[]( + const std::string& utf8name ///< UTF-8 encoded property name + ); + + /// Gets or sets an indexed property or array element. + PropertyLValue operator[]( + uint32_t index /// Property / element index + ); + + /// Gets or sets an indexed property or array element. + PropertyLValue operator[](Value index /// Property / element index + ) const; + + /// Gets a named property. + MaybeOrValue operator[]( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Gets a named property. + MaybeOrValue operator[]( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Gets an indexed property or array element. + MaybeOrValue operator[](uint32_t index ///< Property / element index + ) const; + + /// Checks whether a property is present. + MaybeOrValue Has(napi_value key ///< Property key primitive + ) const; + + /// Checks whether a property is present. + MaybeOrValue Has(Value key ///< Property key + ) const; + + /// Checks whether a named property is present. + MaybeOrValue Has( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Checks whether a named property is present. + MaybeOrValue Has( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty(napi_value key ///< Property key primitive + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty(Value key ///< Property key + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Gets a property. + MaybeOrValue Get(napi_value key ///< Property key primitive + ) const; + + /// Gets a property. + MaybeOrValue Get(Value key ///< Property key + ) const; + + /// Gets a named property. + MaybeOrValue Get( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Gets a named property. + MaybeOrValue Get( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Sets a property. + template + MaybeOrValue Set(napi_value key, ///< Property key primitive + const ValueType& value ///< Property value primitive + ) const; + + /// Sets a property. + template + MaybeOrValue Set(Value key, ///< Property key + const ValueType& value ///< Property value + ) const; + + /// Sets a named property. + template + MaybeOrValue Set( + const char* utf8name, ///< UTF-8 encoded null-terminated property name + const ValueType& value) const; + + /// Sets a named property. + template + MaybeOrValue Set( + const std::string& utf8name, ///< UTF-8 encoded property name + const ValueType& value ///< Property value primitive + ) const; + + /// Delete property. + MaybeOrValue Delete(napi_value key ///< Property key primitive + ) const; + + /// Delete property. + MaybeOrValue Delete(Value key ///< Property key + ) const; + + /// Delete property. + MaybeOrValue Delete( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Delete property. + MaybeOrValue Delete( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Checks whether an indexed property is present. + MaybeOrValue Has(uint32_t index ///< Property / element index + ) const; + + /// Gets an indexed property or array element. + MaybeOrValue Get(uint32_t index ///< Property / element index + ) const; + + /// Sets an indexed property or array element. + template + MaybeOrValue Set(uint32_t index, ///< Property / element index + const ValueType& value ///< Property value primitive + ) const; + + /// Deletes an indexed property or array element. + MaybeOrValue Delete(uint32_t index ///< Property / element index + ) const; + + /// This operation can fail in case of Proxy.[[OwnPropertyKeys]] and + /// Proxy.[[GetOwnProperty]] calling into JavaScript. See: + /// - + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys + /// - + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p + MaybeOrValue GetPropertyNames() const; ///< Get all property names + + /// Defines a property on the object. + /// + /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling + /// into JavaScript. See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc + MaybeOrValue DefineProperty( + const PropertyDescriptor& + property ///< Descriptor for the property to be defined + ) const; + + /// Defines properties on the object. + /// + /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling + /// into JavaScript. See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc + MaybeOrValue DefineProperties( + const std::initializer_list& properties + ///< List of descriptors for the properties to be defined + ) const; + + /// Defines properties on the object. + /// + /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling + /// into JavaScript. See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc + MaybeOrValue DefineProperties( + const std::vector& properties + ///< Vector of descriptors for the properties to be defined + ) const; + + /// Checks if an object is an instance created by a constructor function. + /// + /// This is equivalent to the JavaScript `instanceof` operator. + /// + /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into + /// JavaScript. + /// See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof + MaybeOrValue InstanceOf( + const Function& constructor ///< Constructor function + ) const; + + template + inline void AddFinalizer(Finalizer finalizeCallback, T* data) const; + + template + inline void AddFinalizer(Finalizer finalizeCallback, + T* data, + Hint* finalizeHint) const; + +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + class const_iterator; + + inline const_iterator begin() const; + + inline const_iterator end() const; + + class iterator; + + inline iterator begin(); + + inline iterator end(); +#endif // NODE_ADDON_API_CPP_EXCEPTIONS + +#if NAPI_VERSION >= 8 + /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into + /// JavaScript. + /// See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof + MaybeOrValue Freeze() const; + /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into + /// JavaScript. + /// See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof + MaybeOrValue Seal() const; +#endif // NAPI_VERSION >= 8 + + MaybeOrValue GetPrototype() const; + +#ifdef NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE + MaybeOrValue SetPrototype(const Object& value) const; +#endif +}; + +template +class External : public TypeTaggable { + public: + static External New(napi_env env, T* data); + + // Finalizer must implement `void operator()(Env env, T* data)`. + template + static External New(napi_env env, T* data, Finalizer finalizeCallback); + // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + template + static External New(napi_env env, + T* data, + Finalizer finalizeCallback, + Hint* finalizeHint); + + static void CheckCast(napi_env env, napi_value value); + + External(); + External(napi_env env, napi_value value); + + T* Data() const; +}; + +class Array : public Object { + public: + static Array New(napi_env env); + static Array New(napi_env env, size_t length); + + static void CheckCast(napi_env env, napi_value value); + + Array(); + Array(napi_env env, napi_value value); + + uint32_t Length() const; +}; + +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS +class Object::const_iterator { + private: + enum class Type { BEGIN, END }; + + inline const_iterator(const Object* object, const Type type); + + public: + inline const_iterator& operator++(); + + inline bool operator==(const const_iterator& other) const; + + inline bool operator!=(const const_iterator& other) const; + + inline const std::pair> operator*() + const; + + private: + const Napi::Object* _object; + Array _keys; + uint32_t _index; + + friend class Object; +}; + +class Object::iterator { + private: + enum class Type { BEGIN, END }; + + inline iterator(Object* object, const Type type); + + public: + inline iterator& operator++(); + + inline bool operator==(const iterator& other) const; + + inline bool operator!=(const iterator& other) const; + + inline std::pair> operator*(); + + private: + Napi::Object* _object; + Array _keys; + uint32_t _index; + + friend class Object; +}; +#endif // NODE_ADDON_API_CPP_EXCEPTIONS + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +class SharedArrayBuffer : public Object { + public: + SharedArrayBuffer(); + SharedArrayBuffer(napi_env env, napi_value value); + + static SharedArrayBuffer New(napi_env env, size_t byteLength); + + static void CheckCast(napi_env env, napi_value value); + + void* Data(); + size_t ByteLength(); +}; +#endif + +/// A JavaScript array buffer value. +class ArrayBuffer : public Object { + public: + /// Creates a new ArrayBuffer instance over a new automatically-allocated + /// buffer. + static ArrayBuffer New( + napi_env env, ///< Node-API environment + size_t byteLength ///< Length of the buffer to be allocated, in bytes + ); + +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength ///< Length of the external buffer to be used by the + ///< array, in bytes + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + template + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength, ///< Length of the external buffer to be used by the + ///< array, + /// in bytes + Finalizer finalizeCallback ///< Function to be called when the array + ///< buffer is destroyed; + /// must implement `void operator()(Env env, + /// void* externalData)` + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + template + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength, ///< Length of the external buffer to be used by the + ///< array, + /// in bytes + Finalizer finalizeCallback, ///< Function to be called when the array + ///< buffer is destroyed; + /// must implement `void operator()(Env + /// env, void* externalData, Hint* hint)` + Hint* finalizeHint ///< Hint (second parameter) to be passed to the + ///< finalize callback + ); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + + static void CheckCast(napi_env env, napi_value value); + + ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance. + ArrayBuffer(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + void* Data(); ///< Gets a pointer to the data buffer. + size_t ByteLength(); ///< Gets the length of the array buffer in bytes. + +#if NAPI_VERSION >= 7 + bool IsDetached() const; + void Detach(); +#endif // NAPI_VERSION >= 7 +}; + +/// A JavaScript typed-array value with unknown array type. +/// +/// For type-specific operations, cast to a `TypedArrayOf` instance using the +/// `As()` method: +/// +/// Napi::TypedArray array = ... +/// if (t.TypedArrayType() == napi_int32_array) { +/// Napi::Int32Array int32Array = t.As(); +/// } +class TypedArray : public Object { + public: + static void CheckCast(napi_env env, napi_value value); + + TypedArray(); ///< Creates a new _empty_ TypedArray instance. + TypedArray(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + napi_typedarray_type TypedArrayType() + const; ///< Gets the type of this typed-array. + + // Gets the backing `ArrayBuffer`. + // + // If this `TypedArray` is not backed by an `ArrayBuffer`, this method will + // terminate the process with a fatal error when using + // `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` or exhibit undefined behavior + // otherwise. Use `Buffer()` instead to get the backing buffer without + // assuming its type. + Napi::ArrayBuffer ArrayBuffer() const; + + // Gets the backing buffer (an `ArrayBuffer` or `SharedArrayBuffer`). + // + // Use `IsArrayBuffer()` or `IsSharedArrayBuffer()` to check the type of the + // backing buffer prior to casting with `As()`. + Napi::Value Buffer() const; + + uint8_t ElementSize() + const; ///< Gets the size in bytes of one element in the array. + size_t ElementLength() const; ///< Gets the number of elements in the array. + size_t ByteOffset() + const; ///< Gets the offset into the buffer where the array starts. + size_t ByteLength() const; ///< Gets the length of the array in bytes. + + protected: + /// !cond INTERNAL + napi_typedarray_type _type; + size_t _length; + + TypedArray(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length); + + template + static +#if defined(NAPI_HAS_CONSTEXPR) + constexpr +#endif + napi_typedarray_type + TypedArrayTypeForPrimitiveType() { + return std::is_same::value ? napi_int8_array + : std::is_same::value ? napi_uint8_array + : std::is_same::value ? napi_int16_array + : std::is_same::value ? napi_uint16_array + : std::is_same::value ? napi_int32_array + : std::is_same::value ? napi_uint32_array + : std::is_same::value ? napi_float32_array + : std::is_same::value ? napi_float64_array +#if NAPI_VERSION > 5 + : std::is_same::value ? napi_bigint64_array + : std::is_same::value ? napi_biguint64_array +#endif // NAPI_VERSION > 5 + : napi_int8_array; + } + /// !endcond +}; + +/// A JavaScript typed-array value with known array type. +/// +/// Note while it is possible to create and access Uint8 "clamped" arrays using +/// this class, the _clamping_ behavior is only applied in JavaScript. +template +class TypedArrayOf : public TypedArray { + public: + /// Creates a new TypedArray instance over a new automatically-allocated array + /// buffer. + /// + /// The array type parameter can normally be omitted (because it is inferred + /// from the template parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< Node-API environment + size_t elementLength, ///< Length of the created array, as a number of + ///< elements +#if defined(NAPI_HAS_CONSTEXPR) + napi_typedarray_type type = + TypedArray::TypedArrayTypeForPrimitiveType() +#else + napi_typedarray_type type +#endif + ///< Type of array, if different from the default array type for the + ///< template parameter T. + ); + + /// Creates a new TypedArray instance over a provided array buffer. + /// + /// The array type parameter can normally be omitted (because it is inferred + /// from the template parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< Node-API environment + size_t elementLength, ///< Length of the created array, as a number of + ///< elements + Napi::ArrayBuffer arrayBuffer, ///< Backing array buffer instance to use + size_t bufferOffset, ///< Offset into the array buffer where the + ///< typed-array starts +#if defined(NAPI_HAS_CONSTEXPR) + napi_typedarray_type type = + TypedArray::TypedArrayTypeForPrimitiveType() +#else + napi_typedarray_type type +#endif + ///< Type of array, if different from the default array type for the + ///< template parameter T. + ); + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + /// Creates a new TypedArray instance over a provided SharedArrayBuffer. + /// + /// The array type parameter can normally be omitted (because it is inferred + /// from the template parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< Node-API environment + size_t elementLength, ///< Length of the created array, as a number of + ///< elements + Napi::SharedArrayBuffer + arrayBuffer, ///< Backing shared array buffer instance to use + size_t bufferOffset, ///< Offset into the array buffer where the + ///< typed-array starts +#if defined(NAPI_HAS_CONSTEXPR) + napi_typedarray_type type = + TypedArray::TypedArrayTypeForPrimitiveType() +#else + napi_typedarray_type type +#endif + ///< Type of array, if different from the default array type for the + ///< template parameter T. + ); +#endif + + static void CheckCast(napi_env env, napi_value value); + + TypedArrayOf(); ///< Creates a new _empty_ TypedArrayOf instance. + TypedArrayOf(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + T& operator[](size_t index); ///< Gets or sets an element in the array. + const T& operator[](size_t index) const; ///< Gets an element in the array. + + /// Gets a pointer to the array's backing buffer. + /// + /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, + /// because the typed-array may have a non-zero `ByteOffset()` into the + /// `ArrayBuffer`. + T* Data(); + + /// Gets a pointer to the array's backing buffer. + /// + /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, + /// because the typed-array may have a non-zero `ByteOffset()` into the + /// `ArrayBuffer`. + const T* Data() const; + + private: + T* _data; + + TypedArrayOf(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length, + T* data); +}; + +/// The DataView provides a low-level interface for reading/writing multiple +/// number types in an ArrayBuffer irrespective of the platform's endianness. +class DataView : public Object { + public: + static DataView New(napi_env env, Napi::ArrayBuffer arrayBuffer); + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset); + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength); + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + static DataView New(napi_env env, Napi::SharedArrayBuffer arrayBuffer); + static DataView New(napi_env env, + Napi::SharedArrayBuffer arrayBuffer, + size_t byteOffset); + static DataView New(napi_env env, + Napi::SharedArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength); +#endif + + static void CheckCast(napi_env env, napi_value value); + + DataView(); ///< Creates a new _empty_ DataView instance. + DataView(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + // Gets the backing `ArrayBuffer`. + // + // If this `DataView` is not backed by an `ArrayBuffer`, this method will + // terminate the process with a fatal error when using + // `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` or exhibit undefined behavior + // otherwise. Use `Buffer()` instead to get the backing buffer without + // assuming its type. + Napi::ArrayBuffer ArrayBuffer() const; + + // Gets the backing buffer (an `ArrayBuffer` or `SharedArrayBuffer`). + // + // Use `IsArrayBuffer()` or `IsSharedArrayBuffer()` to check the type of the + // backing buffer prior to casting with `As()`. + Napi::Value Buffer() const; + size_t ByteOffset() + const; ///< Gets the offset into the buffer where the array starts. + size_t ByteLength() const; ///< Gets the length of the array in bytes. + + void* Data() const; + + float GetFloat32(size_t byteOffset) const; + double GetFloat64(size_t byteOffset) const; + int8_t GetInt8(size_t byteOffset) const; + int16_t GetInt16(size_t byteOffset) const; + int32_t GetInt32(size_t byteOffset) const; + uint8_t GetUint8(size_t byteOffset) const; + uint16_t GetUint16(size_t byteOffset) const; + uint32_t GetUint32(size_t byteOffset) const; + + void SetFloat32(size_t byteOffset, float value) const; + void SetFloat64(size_t byteOffset, double value) const; + void SetInt8(size_t byteOffset, int8_t value) const; + void SetInt16(size_t byteOffset, int16_t value) const; + void SetInt32(size_t byteOffset, int32_t value) const; + void SetUint8(size_t byteOffset, uint8_t value) const; + void SetUint16(size_t byteOffset, uint16_t value) const; + void SetUint32(size_t byteOffset, uint32_t value) const; + + private: + template + T ReadData(size_t byteOffset) const; + + template + void WriteData(size_t byteOffset, T value) const; + + void* _data{}; + size_t _length{}; +}; + +class Function : public Object { + public: + using VoidCallback = void (*)(const CallbackInfo& info); + using Callback = Value (*)(const CallbackInfo& info); + + template + static Function New(napi_env env, + const char* utf8name = nullptr, + void* data = nullptr); + + template + static Function New(napi_env env, + const char* utf8name = nullptr, + void* data = nullptr); + + template + static Function New(napi_env env, + const std::string& utf8name, + void* data = nullptr); + + template + static Function New(napi_env env, + const std::string& utf8name, + void* data = nullptr); + + /// Callable must implement operator() accepting a const CallbackInfo& + /// and return either void or Value. + template + static Function New(napi_env env, + Callable cb, + const char* utf8name = nullptr, + void* data = nullptr); + /// Callable must implement operator() accepting a const CallbackInfo& + /// and return either void or Value. + template + static Function New(napi_env env, + Callable cb, + const std::string& utf8name, + void* data = nullptr); + + static void CheckCast(napi_env env, napi_value value); + + Function(); + Function(napi_env env, napi_value value); + + MaybeOrValue operator()( + const std::initializer_list& args) const; + + MaybeOrValue Call(const std::initializer_list& args) const; + MaybeOrValue Call(const std::vector& args) const; + MaybeOrValue Call(const std::vector& args) const; + MaybeOrValue Call(size_t argc, const napi_value* args) const; + MaybeOrValue Call(napi_value recv, + const std::initializer_list& args) const; + MaybeOrValue Call(napi_value recv, + const std::vector& args) const; + MaybeOrValue Call(napi_value recv, + const std::vector& args) const; + MaybeOrValue Call(napi_value recv, + size_t argc, + const napi_value* args) const; + + MaybeOrValue MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback(napi_value recv, + const std::vector& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback(napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context = nullptr) const; + + MaybeOrValue New(const std::initializer_list& args) const; + MaybeOrValue New(const std::vector& args) const; + MaybeOrValue New(size_t argc, const napi_value* args) const; +}; + +class Promise : public Object { + public: + class Deferred { + public: + static Deferred New(napi_env env); + Deferred(napi_env env); + + Napi::Promise Promise() const; + Napi::Env Env() const; + + void Resolve(napi_value value) const; + void Reject(napi_value value) const; + + private: + napi_env _env; + napi_deferred _deferred; + napi_value _promise; + }; + + static void CheckCast(napi_env env, napi_value value); + + Promise(); + Promise(napi_env env, napi_value value); + + MaybeOrValue Then(napi_value onFulfilled) const; + MaybeOrValue Then(napi_value onFulfilled, + napi_value onRejected) const; + MaybeOrValue Catch(napi_value onRejected) const; + + MaybeOrValue Then(const Function& onFulfilled) const; + MaybeOrValue Then(const Function& onFulfilled, + const Function& onRejected) const; + MaybeOrValue Catch(const Function& onRejected) const; +}; + +template +class Buffer : public Uint8Array { + public: + static Buffer New(napi_env env, size_t length); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + static Buffer New(napi_env env, T* data, size_t length); + + // Finalizer must implement `void operator()(Env env, T* data)`. + template + static Buffer New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback); + // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + template + static Buffer New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + + static Buffer NewOrCopy(napi_env env, T* data, size_t length); + // Finalizer must implement `void operator()(Env env, T* data)`. + template + static Buffer NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback); + // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + template + static Buffer NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint); + + static Buffer Copy(napi_env env, const T* data, size_t length); + + static void CheckCast(napi_env env, napi_value value); + + Buffer(); + Buffer(napi_env env, napi_value value); + size_t Length() const; + T* Data() const; + + private: +}; + +/// Holds a counted reference to a value; initially a weak reference unless +/// otherwise specified, may be changed to/from a strong reference by adjusting +/// the refcount. +/// +/// The referenced value is not immediately destroyed when the reference count +/// is zero; it is merely then eligible for garbage-collection if there are no +/// other references to the value. +template +class Reference { + public: + static Reference New(const T& value, uint32_t initialRefcount = 0); + + Reference(); + Reference(napi_env env, napi_ref ref); + ~Reference(); + + // A reference can be moved but cannot be copied. + Reference(Reference&& other); + Reference& operator=(Reference&& other); + NAPI_DISALLOW_ASSIGN(Reference) + + operator napi_ref() const; + bool operator==(const Reference& other) const; + bool operator!=(const Reference& other) const; + + Napi::Env Env() const; + bool IsEmpty() const; + + // Note when getting the value of a Reference it is usually correct to do so + // within a HandleScope so that the value handle gets cleaned up efficiently. + T Value() const; + + uint32_t Ref() const; + uint32_t Unref() const; + void Reset(); + void Reset(const T& value, uint32_t refcount = 0); + + // Call this on a reference that is declared as static data, to prevent its + // destructor from running at program shutdown time, which would attempt to + // reset the reference when the environment is no longer valid. Avoid using + // this if at all possible. If you do need to use static data, MAKE SURE to + // warn your users that your addon is NOT threadsafe. + void SuppressDestruct(); + + protected: + Reference(const Reference&); + + /// !cond INTERNAL + napi_env _env; + napi_ref _ref; + /// !endcond + + private: + bool _suppressDestruct; +}; + +class ObjectReference : public Reference { + public: + ObjectReference(); + ObjectReference(napi_env env, napi_ref ref); + + // A reference can be moved but cannot be copied. + ObjectReference(Reference&& other); + ObjectReference& operator=(Reference&& other); + ObjectReference(ObjectReference&& other); + ObjectReference& operator=(ObjectReference&& other); + NAPI_DISALLOW_ASSIGN(ObjectReference) + + MaybeOrValue Get(const char* utf8name) const; + MaybeOrValue Get(const std::string& utf8name) const; + MaybeOrValue Set(const char* utf8name, napi_value value) const; + MaybeOrValue Set(const char* utf8name, Napi::Value value) const; + MaybeOrValue Set(const char* utf8name, const char* utf8value) const; + MaybeOrValue Set(const char* utf8name, bool boolValue) const; + MaybeOrValue Set(const char* utf8name, double numberValue) const; + MaybeOrValue Set(const std::string& utf8name, napi_value value) const; + MaybeOrValue Set(const std::string& utf8name, Napi::Value value) const; + MaybeOrValue Set(const std::string& utf8name, + const std::string& utf8value) const; + MaybeOrValue Set(const std::string& utf8name, bool boolValue) const; + MaybeOrValue Set(const std::string& utf8name, double numberValue) const; + + MaybeOrValue Get(uint32_t index) const; + MaybeOrValue Set(uint32_t index, const napi_value value) const; + MaybeOrValue Set(uint32_t index, const Napi::Value value) const; + MaybeOrValue Set(uint32_t index, const char* utf8value) const; + MaybeOrValue Set(uint32_t index, const std::string& utf8value) const; + MaybeOrValue Set(uint32_t index, bool boolValue) const; + MaybeOrValue Set(uint32_t index, double numberValue) const; + + protected: + ObjectReference(const ObjectReference&); +}; + +class FunctionReference : public Reference { + public: + FunctionReference(); + FunctionReference(napi_env env, napi_ref ref); + + // A reference can be moved but cannot be copied. + FunctionReference(Reference&& other); + FunctionReference& operator=(Reference&& other); + FunctionReference(FunctionReference&& other); + FunctionReference& operator=(FunctionReference&& other); + NAPI_DISALLOW_ASSIGN_COPY(FunctionReference) + + MaybeOrValue operator()( + const std::initializer_list& args) const; + + MaybeOrValue Call( + const std::initializer_list& args) const; + MaybeOrValue Call(const std::vector& args) const; + MaybeOrValue Call( + napi_value recv, const std::initializer_list& args) const; + MaybeOrValue Call(napi_value recv, + const std::vector& args) const; + MaybeOrValue Call(napi_value recv, + size_t argc, + const napi_value* args) const; + + MaybeOrValue MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback( + napi_value recv, + const std::vector& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback( + napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context = nullptr) const; + + MaybeOrValue New(const std::initializer_list& args) const; + MaybeOrValue New(const std::vector& args) const; +}; + +// Shortcuts to creating a new reference with inferred type and refcount = 0. +template +Reference Weak(T value); +ObjectReference Weak(Object value); +FunctionReference Weak(Function value); + +// Shortcuts to creating a new reference with inferred type and refcount = 1. +template +Reference Persistent(T value); +ObjectReference Persistent(Object value); +FunctionReference Persistent(Function value); + +/// A persistent reference to a JavaScript error object. Use of this class +/// depends somewhat on whether C++ exceptions are enabled at compile time. +/// +/// ### Handling Errors With C++ Exceptions +/// +/// If C++ exceptions are enabled, then the `Error` class extends +/// `std::exception` and enables integrated error-handling for C++ exceptions +/// and JavaScript exceptions. +/// +/// If a Node-API call fails without executing any JavaScript code (for +/// example due to an invalid argument), then the Node-API wrapper +/// automatically converts and throws the error as a C++ exception of type +/// `Napi::Error`. Or if a JavaScript function called by C++ code via Node-API +/// throws a JavaScript exception, then the Node-API wrapper automatically +/// converts and throws it as a C++ exception of type `Napi::Error`. +/// +/// If a C++ exception of type `Napi::Error` escapes from a Node-API C++ +/// callback, then the Node-API wrapper automatically converts and throws it +/// as a JavaScript exception. Therefore, catching a C++ exception of type +/// `Napi::Error` prevents a JavaScript exception from being thrown. +/// +/// #### Example 1A - Throwing a C++ exception: +/// +/// Napi::Env env = ... +/// throw Napi::Error::New(env, "Example exception"); +/// +/// Following C++ statements will not be executed. The exception will bubble +/// up as a C++ exception of type `Napi::Error`, until it is either caught +/// while still in C++, or else automatically propagated as a JavaScript +/// exception when the callback returns to JavaScript. +/// +/// #### Example 2A - Propagating a Node-API C++ exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); +/// +/// Following C++ statements will not be executed. The exception will bubble +/// up as a C++ exception of type `Napi::Error`, until it is either caught +/// while still in C++, or else automatically propagated as a JavaScript +/// exception when the callback returns to JavaScript. +/// +/// #### Example 3A - Handling a Node-API C++ exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result; +/// try { +/// result = jsFunctionThatThrows({ arg1, arg2 }); +/// } catch (const Napi::Error& e) { +/// cerr << "Caught JavaScript exception: " + e.what(); +/// } +/// +/// Since the exception was caught here, it will not be propagated as a +/// JavaScript exception. +/// +/// ### Handling Errors Without C++ Exceptions +/// +/// If C++ exceptions are disabled (by defining +/// `NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS`) then this class does not extend +/// `std::exception`, and APIs in the `Napi` namespace do not throw C++ +/// exceptions when they fail. Instead, they raise _pending_ JavaScript +/// exceptions and return _empty_ `Value`s. Calling code should check +/// `Value::IsEmpty()` before attempting to use a returned value, and may use +/// methods on the `Env` class to check for, get, and clear a pending JavaScript +/// exception. If the pending exception is not cleared, it will be thrown when +/// the native callback returns to JavaScript. +/// +/// #### Example 1B - Throwing a JS exception +/// +/// Napi::Env env = ... +/// Napi::Error::New(env, "Example +/// exception").ThrowAsJavaScriptException(); return; +/// +/// After throwing a JS exception, the code should generally return +/// immediately from the native callback, after performing any necessary +/// cleanup. +/// +/// #### Example 2B - Propagating a Node-API JS exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); +/// if (result.IsEmpty()) return; +/// +/// An empty value result from a Node-API call indicates an error occurred, +/// and a JavaScript exception is pending. To let the exception propagate, the +/// code should generally return immediately from the native callback, after +/// performing any necessary cleanup. +/// +/// #### Example 3B - Handling a Node-API JS exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); +/// if (result.IsEmpty()) { +/// Napi::Error e = env.GetAndClearPendingException(); +/// cerr << "Caught JavaScript exception: " + e.Message(); +/// } +/// +/// Since the exception was cleared here, it will not be propagated as a +/// JavaScript exception after the native callback returns. +class Error : public ObjectReference +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + , + public std::exception +#endif // NODE_ADDON_API_CPP_EXCEPTIONS +{ + public: + static Error New(napi_env env); + static Error New(napi_env env, const char* message); + static Error New(napi_env env, const std::string& message); + + static NAPI_NO_RETURN void Fatal(const char* location, const char* message); + + Error(); + Error(napi_env env, napi_value value); + + // An error can be moved or copied. + Error(Error&& other); + Error& operator=(Error&& other); + Error(const Error&); + Error& operator=(const Error&); + + const std::string& Message() const NAPI_NOEXCEPT; + void ThrowAsJavaScriptException() const; + + Object Value() const; + +#ifdef NODE_ADDON_API_CPP_EXCEPTIONS + const char* what() const NAPI_NOEXCEPT override; +#endif // NODE_ADDON_API_CPP_EXCEPTIONS + + protected: + /// !cond INTERNAL + using create_error_fn = napi_status (*)(napi_env envb, + napi_value code, + napi_value msg, + napi_value* result); + + template + static TError New(napi_env env, + const char* message, + size_t length, + create_error_fn create_error); + /// !endcond + + private: + static inline const char* ERROR_WRAP_VALUE() NAPI_NOEXCEPT; + mutable std::string _message; +}; + +class TypeError : public Error { + public: + static TypeError New(napi_env env, const char* message); + static TypeError New(napi_env env, const std::string& message); + + TypeError(); + TypeError(napi_env env, napi_value value); +}; + +class RangeError : public Error { + public: + static RangeError New(napi_env env, const char* message); + static RangeError New(napi_env env, const std::string& message); + + RangeError(); + RangeError(napi_env env, napi_value value); +}; + +#if NAPI_VERSION > 8 +class SyntaxError : public Error { + public: + static SyntaxError New(napi_env env, const char* message); + static SyntaxError New(napi_env env, const std::string& message); + + SyntaxError(); + SyntaxError(napi_env env, napi_value value); +}; +#endif // NAPI_VERSION > 8 + +class CallbackInfo { + public: + CallbackInfo(napi_env env, napi_callback_info info); + ~CallbackInfo(); + + // Disallow copying to prevent multiple free of _dynamicArgs + NAPI_DISALLOW_ASSIGN_COPY(CallbackInfo) + + Napi::Env Env() const; + Value NewTarget() const; + bool IsConstructCall() const; + size_t Length() const; + const Value operator[](size_t index) const; + Value This() const; + void* Data() const; + void SetData(void* data); + explicit operator napi_callback_info() const; + + private: + const size_t _staticArgCount = 6; + napi_env _env; + napi_callback_info _info; + napi_value _this; + size_t _argc; + napi_value* _argv; + napi_value _staticArgs[6]{}; + napi_value* _dynamicArgs; + void* _data; +}; + +class PropertyDescriptor { + public: + using GetterCallback = Napi::Value (*)(const Napi::CallbackInfo& info); + using SetterCallback = void (*)(const Napi::CallbackInfo& info); + +#ifndef NODE_ADDON_API_DISABLE_DEPRECATED + template + static PropertyDescriptor Accessor( + const char* utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + napi_value name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Name name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + napi_value name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + const char* utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + napi_value name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Name name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED + + template + static PropertyDescriptor Accessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + Name name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + Name name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Napi::Env env, + Napi::Object object, + Name name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor Value( + const char* utf8name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value( + const std::string& utf8name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value( + napi_value name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value( + Name name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + + PropertyDescriptor(napi_property_descriptor desc); + + operator napi_property_descriptor&(); + operator const napi_property_descriptor&() const; + + private: + napi_property_descriptor _desc; +}; + +/// Property descriptor for use with `ObjectWrap::DefineClass()`. +/// +/// This is different from the standalone `PropertyDescriptor` because it is +/// specific to each `ObjectWrap` subclass. This prevents using descriptors +/// from a different class when defining a new class (preventing the callbacks +/// from having incorrect `this` pointers). +template +class ClassPropertyDescriptor { + public: + ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {} + + operator napi_property_descriptor&() { return _desc; } + operator const napi_property_descriptor&() const { return _desc; } + + private: + napi_property_descriptor _desc; +}; + +template +struct MethodCallbackData { + TCallback callback; + void* data; +}; + +template +struct AccessorCallbackData { + TGetterCallback getterCallback; + TSetterCallback setterCallback; + void* data; +}; + +template +class InstanceWrap { + public: + using InstanceVoidMethodCallback = void (T::*)(const CallbackInfo& info); + using InstanceMethodCallback = Napi::Value (T::*)(const CallbackInfo& info); + using InstanceGetterCallback = Napi::Value (T::*)(const CallbackInfo& info); + using InstanceSetterCallback = void (T::*)(const CallbackInfo& info, + const Napi::Value& value); + + using PropertyDescriptor = ClassPropertyDescriptor; + + static PropertyDescriptor InstanceMethod( + const char* utf8name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod( + const char* utf8name, + InstanceMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod( + Symbol name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod( + Symbol name, + InstanceMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceAccessor( + const char* utf8name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceAccessor( + Symbol name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceAccessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceAccessor( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor InstanceValue( + Symbol name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + + protected: + static void AttachPropData(napi_env env, + napi_value value, + const napi_property_descriptor* prop); + + private: + using This = InstanceWrap; + + using InstanceVoidMethodCallbackData = + MethodCallbackData; + using InstanceMethodCallbackData = + MethodCallbackData; + using InstanceAccessorCallbackData = + AccessorCallbackData; + + static napi_value InstanceVoidMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value InstanceMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value InstanceGetterCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value InstanceSetterCallbackWrapper(napi_env env, + napi_callback_info info); + + template + static napi_value WrappedMethod(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT; + + template + struct SetterTag {}; + + template + static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { + return &This::WrappedMethod; + } + static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { + return nullptr; + } +}; + +/// Base class to be extended by C++ classes exposed to JavaScript; each C++ +/// class instance gets "wrapped" by a JavaScript object that is managed by this +/// class. +/// +/// At initialization time, the `DefineClass()` method must be used to +/// hook up the accessor and method callbacks. It takes a list of +/// property descriptors, which can be constructed via the various +/// static methods on the base class. +/// +/// #### Example: +/// +/// class Example: public Napi::ObjectWrap { +/// public: +/// static void Initialize(Napi::Env& env, Napi::Object& target) { +/// Napi::Function constructor = DefineClass(env, "Example", { +/// InstanceAccessor<&Example::GetSomething, +/// &Example::SetSomething>("value"), +/// InstanceMethod<&Example::DoSomething>("doSomething"), +/// }); +/// target.Set("Example", constructor); +/// } +/// +/// Example(const Napi::CallbackInfo& info); // Constructor +/// Napi::Value GetSomething(const Napi::CallbackInfo& info); +/// void SetSomething(const Napi::CallbackInfo& info, const Napi::Value& +/// value); Napi::Value DoSomething(const Napi::CallbackInfo& info); +/// } +template +class ObjectWrap : public InstanceWrap, public Reference { + public: + ObjectWrap(const CallbackInfo& callbackInfo); + virtual ~ObjectWrap(); + + static T* Unwrap(Object wrapper); + + // Methods exposed to JavaScript must conform to one of these callback + // signatures. + using StaticVoidMethodCallback = void (*)(const CallbackInfo& info); + using StaticMethodCallback = Napi::Value (*)(const CallbackInfo& info); + using StaticGetterCallback = Napi::Value (*)(const CallbackInfo& info); + using StaticSetterCallback = void (*)(const CallbackInfo& info, + const Napi::Value& value); + + using PropertyDescriptor = ClassPropertyDescriptor; + + static Function DefineClass( + Napi::Env env, + const char* utf8name, + const std::initializer_list& properties, + void* data = nullptr); + static Function DefineClass(Napi::Env env, + const char* utf8name, + const std::vector& properties, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + const char* utf8name, + StaticVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + const char* utf8name, + StaticMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + Symbol name, + StaticVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + Symbol name, + StaticMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticAccessor( + const char* utf8name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticAccessor( + Symbol name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticAccessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticAccessor( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor StaticValue( + Symbol name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static Napi::Value OnCalledAsFunction(const Napi::CallbackInfo& callbackInfo); + virtual void Finalize(Napi::Env env); + virtual void Finalize(BasicEnv env); + + private: + using This = ObjectWrap; + + static napi_value ConstructorCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticVoidMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticGetterCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticSetterCallbackWrapper(napi_env env, + napi_callback_info info); + static void FinalizeCallback(node_addon_api_basic_env env, + void* data, + void* hint); + + static void PostFinalizeCallback(napi_env env, void* data, void* hint); + + static Function DefineClass(Napi::Env env, + const char* utf8name, + const size_t props_count, + const napi_property_descriptor* props, + void* data = nullptr); + + using StaticVoidMethodCallbackData = + MethodCallbackData; + using StaticMethodCallbackData = MethodCallbackData; + + using StaticAccessorCallbackData = + AccessorCallbackData; + + template + static napi_value WrappedMethod(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT; + + template + struct StaticSetterTag {}; + + template + static napi_callback WrapStaticSetter(StaticSetterTag) NAPI_NOEXCEPT { + return &This::WrappedMethod; + } + static napi_callback WrapStaticSetter(StaticSetterTag) + NAPI_NOEXCEPT { + return nullptr; + } + + bool _construction_failed = true; + bool _finalized = false; +}; + +class HandleScope { + public: + HandleScope(napi_env env, napi_handle_scope scope); + explicit HandleScope(Napi::Env env); + ~HandleScope(); + + // Disallow copying to prevent double close of napi_handle_scope + NAPI_DISALLOW_ASSIGN_COPY(HandleScope) + + operator napi_handle_scope() const; + + Napi::Env Env() const; + + private: + napi_env _env; + napi_handle_scope _scope; +}; + +class EscapableHandleScope { + public: + EscapableHandleScope(napi_env env, napi_escapable_handle_scope scope); + explicit EscapableHandleScope(Napi::Env env); + ~EscapableHandleScope(); + + // Disallow copying to prevent double close of napi_escapable_handle_scope + NAPI_DISALLOW_ASSIGN_COPY(EscapableHandleScope) + + operator napi_escapable_handle_scope() const; + + Napi::Env Env() const; + Value Escape(napi_value escapee); + + private: + napi_env _env; + napi_escapable_handle_scope _scope; +}; + +#if (NAPI_VERSION > 2) +class CallbackScope { + public: + CallbackScope(napi_env env, napi_callback_scope scope); + CallbackScope(napi_env env, napi_async_context context); + virtual ~CallbackScope(); + + // Disallow copying to prevent double close of napi_callback_scope + NAPI_DISALLOW_ASSIGN_COPY(CallbackScope) + + operator napi_callback_scope() const; + + Napi::Env Env() const; + + private: + napi_env _env; + napi_callback_scope _scope; +}; +#endif + +class AsyncContext { + public: + explicit AsyncContext(napi_env env, const char* resource_name); + explicit AsyncContext(napi_env env, + const char* resource_name, + const Object& resource); + virtual ~AsyncContext(); + + AsyncContext(AsyncContext&& other); + AsyncContext& operator=(AsyncContext&& other); + NAPI_DISALLOW_ASSIGN_COPY(AsyncContext) + + operator napi_async_context() const; + + Napi::Env Env() const; + + private: + napi_env _env; + napi_async_context _context; +}; + +#if NAPI_HAS_THREADS +class AsyncWorker { + public: + virtual ~AsyncWorker(); + + NAPI_DISALLOW_ASSIGN_COPY(AsyncWorker) + + operator napi_async_work() const; + + Napi::Env Env() const; + + void Queue(); + void Cancel(); + void SuppressDestruct(); + + ObjectReference& Receiver(); + FunctionReference& Callback(); + + virtual void OnExecute(Napi::Env env); + virtual void OnWorkComplete(Napi::Env env, napi_status status); + + protected: + explicit AsyncWorker(const Function& callback); + explicit AsyncWorker(const Function& callback, const char* resource_name); + explicit AsyncWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncWorker(const Object& receiver, const Function& callback); + explicit AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + + explicit AsyncWorker(Napi::Env env); + explicit AsyncWorker(Napi::Env env, const char* resource_name); + explicit AsyncWorker(Napi::Env env, + const char* resource_name, + const Object& resource); + + virtual void Execute() = 0; + virtual void OnOK(); + virtual void OnError(const Error& e); + virtual void Destroy(); + virtual std::vector GetResult(Napi::Env env); + + void SetError(const std::string& error); + + private: + static inline void OnAsyncWorkExecute(napi_env env, void* asyncworker); + static inline void OnAsyncWorkComplete(napi_env env, + napi_status status, + void* asyncworker); + + napi_env _env; + napi_async_work _work; + ObjectReference _receiver; + FunctionReference _callback; + std::string _error; + bool _suppress_destruct; +}; +#endif // NAPI_HAS_THREADS + +#if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) +class ThreadSafeFunction { + public: + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data); + + ThreadSafeFunction(); + ThreadSafeFunction(napi_threadsafe_function tsFunctionValue); + + operator napi_threadsafe_function() const; + + // This API may be called from any thread. + napi_status BlockingCall() const; + + // This API may be called from any thread. + template + napi_status BlockingCall(Callback callback) const; + + // This API may be called from any thread. + template + napi_status BlockingCall(DataType* data, Callback callback) const; + + // This API may be called from any thread. + napi_status NonBlockingCall() const; + + // This API may be called from any thread. + template + napi_status NonBlockingCall(Callback callback) const; + + // This API may be called from any thread. + template + napi_status NonBlockingCall(DataType* data, Callback callback) const; + + // This API may only be called from the main thread. + void Ref(napi_env env) const; + + // This API may only be called from the main thread. + void Unref(napi_env env) const; + + // This API may be called from any thread. + napi_status Acquire() const; + + // This API may be called from any thread. + napi_status Release() const; + + // This API may be called from any thread. + napi_status Abort() const; + + struct ConvertibleContext { + template + operator T*() { + return static_cast(context); + } + void* context; + }; + + // This API may be called from any thread. + ConvertibleContext GetContext() const; + + private: + using CallbackWrapper = std::function; + + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data, + napi_finalize wrapper); + + napi_status CallInternal(CallbackWrapper* callbackWrapper, + napi_threadsafe_function_call_mode mode) const; + + static void CallJS(napi_env env, + napi_value jsCallback, + void* context, + void* data); + + napi_threadsafe_function _tsfn; +}; + +// A TypedThreadSafeFunction by default has no context (nullptr) and can +// accept any type (void) to its CallJs. +template +class TypedThreadSafeFunction { + public: + // This API may only be called from the main thread. + // Helper function that returns nullptr if running Node-API 5+, otherwise a + // non-empty, no-op Function. This provides the ability to specify at + // compile-time a callback parameter to `New` that safely does no action + // when targeting _any_ Node-API version. +#if NAPI_VERSION > 4 + static std::nullptr_t EmptyFunctionFactory(Napi::Env env); +#else + static Napi::Function EmptyFunctionFactory(Napi::Env env); +#endif + static Napi::Function FunctionOrEmpty(Napi::Env env, + Napi::Function& callback); + +#if NAPI_VERSION > 4 + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [missing] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [passed] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [missing] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [passed] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); +#endif + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [missing] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [passed] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [missing] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [passed] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + CallbackType callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + TypedThreadSafeFunction(); + TypedThreadSafeFunction(napi_threadsafe_function tsFunctionValue); + + operator napi_threadsafe_function() const; + + // This API may be called from any thread. + napi_status BlockingCall(DataType* data = nullptr) const; + + // This API may be called from any thread. + napi_status NonBlockingCall(DataType* data = nullptr) const; + + // This API may only be called from the main thread. + void Ref(napi_env env) const; + + // This API may only be called from the main thread. + void Unref(napi_env env) const; + + // This API may be called from any thread. + napi_status Acquire() const; + + // This API may be called from any thread. + napi_status Release() const; + + // This API may be called from any thread. + napi_status Abort() const; + + // This API may be called from any thread. + ContextType* GetContext() const; + + private: + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data, + napi_finalize wrapper); + + static void CallJsInternal(napi_env env, + napi_value jsCallback, + void* context, + void* data); + + protected: + napi_threadsafe_function _tsfn; +}; +template +class AsyncProgressWorkerBase : public AsyncWorker { + public: + virtual void OnWorkProgress(DataType* data) = 0; + class ThreadSafeData { + public: + ThreadSafeData(AsyncProgressWorkerBase* asyncprogressworker, DataType* data) + : _asyncprogressworker(asyncprogressworker), _data(data) {} + + AsyncProgressWorkerBase* asyncprogressworker() { + return _asyncprogressworker; + } + DataType* data() { return _data; } + + private: + AsyncProgressWorkerBase* _asyncprogressworker; + DataType* _data; + }; + void OnWorkComplete(Napi::Env env, napi_status status) override; + + protected: + explicit AsyncProgressWorkerBase(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource, + size_t queue_size = 1); + virtual ~AsyncProgressWorkerBase(); + +// Optional callback of Napi::ThreadSafeFunction only available after +// NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 +#if NAPI_VERSION > 4 + explicit AsyncProgressWorkerBase(Napi::Env env, + const char* resource_name, + const Object& resource, + size_t queue_size = 1); +#endif + + static inline void OnAsyncWorkProgress(Napi::Env env, + Napi::Function jsCallback, + void* data); + + napi_status NonBlockingCall(DataType* data); + + private: + ThreadSafeFunction _tsfn; + bool _work_completed = false; + napi_status _complete_status; + static inline void OnThreadSafeFunctionFinalize( + Napi::Env env, void* data, AsyncProgressWorkerBase* context); +}; + +template +class AsyncProgressWorker : public AsyncProgressWorkerBase { + public: + virtual ~AsyncProgressWorker(); + + class ExecutionProgress { + friend class AsyncProgressWorker; + + public: + void Signal() const; + void Send(const T* data, size_t count) const; + + private: + explicit ExecutionProgress(AsyncProgressWorker* worker) : _worker(worker) {} + AsyncProgressWorker* const _worker; + }; + + void OnWorkProgress(void*) override; + + protected: + explicit AsyncProgressWorker(const Function& callback); + explicit AsyncProgressWorker(const Function& callback, + const char* resource_name); + explicit AsyncProgressWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + +// Optional callback of Napi::ThreadSafeFunction only available after +// NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 +#if NAPI_VERSION > 4 + explicit AsyncProgressWorker(Napi::Env env); + explicit AsyncProgressWorker(Napi::Env env, const char* resource_name); + explicit AsyncProgressWorker(Napi::Env env, + const char* resource_name, + const Object& resource); +#endif + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void OnProgress(const T* data, size_t count) = 0; + + private: + void Execute() override; + void Signal(); + void SendProgress_(const T* data, size_t count); + + std::mutex _mutex; + T* _asyncdata; + size_t _asyncsize; + bool _signaled; +}; + +template +class AsyncProgressQueueWorker + : public AsyncProgressWorkerBase> { + public: + virtual ~AsyncProgressQueueWorker(){}; + + class ExecutionProgress { + friend class AsyncProgressQueueWorker; + + public: + void Signal() const; + void Send(const T* data, size_t count) const; + + private: + explicit ExecutionProgress(AsyncProgressQueueWorker* worker) + : _worker(worker) {} + AsyncProgressQueueWorker* const _worker; + }; + + void OnWorkComplete(Napi::Env env, napi_status status) override; + void OnWorkProgress(std::pair*) override; + + protected: + explicit AsyncProgressQueueWorker(const Function& callback); + explicit AsyncProgressQueueWorker(const Function& callback, + const char* resource_name); + explicit AsyncProgressQueueWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + +// Optional callback of Napi::ThreadSafeFunction only available after +// NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 +#if NAPI_VERSION > 4 + explicit AsyncProgressQueueWorker(Napi::Env env); + explicit AsyncProgressQueueWorker(Napi::Env env, const char* resource_name); + explicit AsyncProgressQueueWorker(Napi::Env env, + const char* resource_name, + const Object& resource); +#endif + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void OnProgress(const T* data, size_t count) = 0; + + private: + void Execute() override; + void Signal() const; + void SendProgress_(const T* data, size_t count); +}; +#endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS + +// Memory management. +class MemoryManagement { + public: + static int64_t AdjustExternalMemory(BasicEnv env, int64_t change_in_bytes); +}; + +// Version management +class VersionManagement { + public: + static uint32_t GetNapiVersion(BasicEnv env); + static const napi_node_version* GetNodeVersion(BasicEnv env); +}; + +#if NAPI_VERSION > 5 +template +class Addon : public InstanceWrap { + public: + static inline Object Init(Env env, Object exports); + static T* Unwrap(Object wrapper); + + protected: + using AddonProp = ClassPropertyDescriptor; + void DefineAddon(Object exports, + const std::initializer_list& props); + Napi::Object DefineProperties(Object object, + const std::initializer_list& props); + + private: + Object entry_point_; +}; +#endif // NAPI_VERSION > 5 + +#ifdef NAPI_CPP_CUSTOM_NAMESPACE +} // namespace NAPI_CPP_CUSTOM_NAMESPACE +#endif + +} // namespace Napi + +// Inline implementations of all the above class methods are included here. +#include "napi-inl.h" + +#endif // SRC_NAPI_H_ diff --git a/test/node-addon-api/test/.gitignore b/test/node-addon-api/test/.gitignore new file mode 100644 index 0000000..95464d3 --- /dev/null +++ b/test/node-addon-api/test/.gitignore @@ -0,0 +1,2 @@ +build/ +src/ diff --git a/test/node-addon-api/test/README.md b/test/node-addon-api/test/README.md new file mode 100644 index 0000000..7ea20d7 --- /dev/null +++ b/test/node-addon-api/test/README.md @@ -0,0 +1,91 @@ +# Writing Tests + +There are multiple flavors of node-addon-api test builds that cover different +build flags defined in `napi.h`: + +1. c++ exceptions enabled, +2. c++ exceptions disabled, +3. c++ exceptions disabled, and `NODE_ADDON_API_ENABLE_MAYBE` defined. + +Functions in node-addon-api that call into JavaScript can have different +declared return types to reflect build flavor settings. For example, +`Napi::Object::Set` returns `bool` when `NODE_ADDON_API_ENABLE_MAYBE` +is not defined, and `Napi::Maybe` when `NODE_ADDON_API_ENABLE_MAYBE` +is defined. In source code, return type variants are defined as +`Napi::MaybeOrValue<>` to prevent the duplication of most of the code base. + +To properly test these build flavors, all values returned by a function defined +to return `Napi::MaybeOrValue<>` should be tested by using one of the following +test helpers to handle possible JavaScript exceptions. + +There are three test helper functions to conveniently convert +`Napi::MaybeOrValue<>` values to raw values. + +## MaybeUnwrap + +```cpp +template +T MaybeUnwrap(MaybeOrValue maybe); +``` + +Converts `MaybeOrValue` to `T` by checking that `MaybeOrValue` is NOT an +empty `Maybe`. + +Returns the original value if `NODE_ADDON_API_ENABLE_MAYBE` is not defined. + +Example: + +```cpp +Object obj = info[0].As(); +// we are sure the parameters should not throw +Value value = MaybeUnwrap(obj->Get("foobar")); +``` + +## MaybeUnwrapOr + +```cpp +template +T MaybeUnwrapOr(MaybeOrValue maybe, const T& default_value = T()); +``` + +Converts `MaybeOrValue` to `T` by getting the value that wrapped by the +`Maybe` or return the `default_value` if the `Maybe` is empty. + +Returns the original value if `NODE_ADDON_API_ENABLE_MAYBE` is not defined. + +Example: + +```cpp +Value CallWithArgs(const CallbackInfo& info) { + Function func = info[0].As(); + // We don't care if the operation is throwing or not, just return it back to node-addon-api + return MaybeUnwrapOr( + func.Call(std::initializer_list{info[1], info[2], info[3]})); +} +``` + +## MaybeUnwrapTo + +```cpp +template +bool MaybeUnwrapTo(MaybeOrValue maybe, T* out); +``` + +Converts `MaybeOrValue` to `T` by getting the value that wrapped by the +e`Maybe` or return `false` if the Maybe is empty + +Copies the `value` to `out` when `NODE_ADDON_API_ENABLE_MAYBE` is not defined + +Example: + +```cpp +Object opts = info[0].As(); +bool hasProperty = false; +// The check may throw, but we are going to suppress that. +if (MaybeUnwrapTo(opts.Has("blocking"), &hasProperty)) { + isBlocking = hasProperty && + MaybeUnwrap(MaybeUnwrap(opts.Get("blocking")).ToBoolean()); +} else { + env.GetAndClearPendingException(); +} +``` diff --git a/test/node-addon-api/test/addon.cc b/test/node-addon-api/test/addon.cc new file mode 100644 index 0000000..1ec9343 --- /dev/null +++ b/test/node-addon-api/test/addon.cc @@ -0,0 +1,44 @@ +#if (NAPI_VERSION > 5) +#include +#include "napi.h" + +namespace { + +class TestAddon : public Napi::Addon { + public: + inline TestAddon(Napi::Env env, Napi::Object exports) { + DefineAddon( + exports, + {InstanceMethod("increment", &TestAddon::Increment), + InstanceValue( + "subObject", + DefineProperties( + Napi::Object::New(env), + {InstanceMethod("decrement", &TestAddon::Decrement)}))}); + } + + ~TestAddon() { fprintf(stderr, "TestAddon::~TestAddon\n"); } + + private: + Napi::Value Increment(const Napi::CallbackInfo& info) { + return Napi::Number::New(info.Env(), ++value); + } + + Napi::Value Decrement(const Napi::CallbackInfo& info) { + return Napi::Number::New(info.Env(), --value); + } + + uint32_t value = 42; +}; + +Napi::Value CreateAddon(const Napi::CallbackInfo& info) { + return TestAddon::Init(info.Env(), Napi::Object::New(info.Env())); +} + +} // end of anonymous namespace + +Napi::Object InitAddon(Napi::Env env) { + return Napi::Function::New(env, "CreateAddon"); +} + +#endif // (NAPI_VERSION > 5) diff --git a/test/node-addon-api/test/addon.js b/test/node-addon-api/test/addon.js new file mode 100644 index 0000000..c326b68 --- /dev/null +++ b/test/node-addon-api/test/addon.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = require('./common').runTestInChildProcess({ + suite: 'addon', + testName: 'workingCode', + expectedStderr: ['TestAddon::~TestAddon'] +}); diff --git a/test/node-addon-api/test/addon_data.cc b/test/node-addon-api/test/addon_data.cc new file mode 100644 index 0000000..2a62ebd --- /dev/null +++ b/test/node-addon-api/test/addon_data.cc @@ -0,0 +1,98 @@ +#if (NAPI_VERSION > 5) +#include +#include "napi.h" +#include "test_helper.h" + +// An overly elaborate way to get/set a boolean stored in the instance data: +// 0. The constructor for JS `VerboseIndicator` instances, which have a private +// member named "verbose", is stored in the instance data. +// 1. Add a property named "verbose" onto exports served by a getter/setter. +// 2. The getter returns an object of type VerboseIndicator, which itself has a +// property named "verbose", also served by a getter/setter: +// * The getter returns a boolean, indicating whether "verbose" is set. +// * The setter sets "verbose" on the instance data. +// 3. The setter sets "verbose" on the instance data. + +class Addon { + public: + class VerboseIndicator : public Napi::ObjectWrap { + public: + VerboseIndicator(const Napi::CallbackInfo& info) + : Napi::ObjectWrap(info) { + info.This().As()["verbose"] = Napi::Boolean::New( + info.Env(), info.Env().GetInstanceData()->verbose); + } + + Napi::Value Getter(const Napi::CallbackInfo& info) { + return Napi::Boolean::New(info.Env(), + info.Env().GetInstanceData()->verbose); + } + + void Setter(const Napi::CallbackInfo& info, const Napi::Value& val) { + info.Env().GetInstanceData()->verbose = val.As(); + } + + static Napi::FunctionReference Init(Napi::Env env) { + return Napi::Persistent(DefineClass( + env, + "VerboseIndicator", + {InstanceAccessor<&VerboseIndicator::Getter, + &VerboseIndicator::Setter>("verbose")})); + } + }; + + static Napi::Value Getter(const Napi::CallbackInfo& info) { + return MaybeUnwrap( + info.Env().GetInstanceData()->VerboseIndicator.New({})); + } + + static void Setter(const Napi::CallbackInfo& info) { + info.Env().GetInstanceData()->verbose = info[0].As(); + } + + Addon(Napi::Env env) : VerboseIndicator(VerboseIndicator::Init(env)) {} + ~Addon() { + if (verbose) { + fprintf(stderr, "addon_data: Addon::~Addon\n"); + } + } + + static void DeleteAddon(Napi::Env, Addon* addon, uint32_t* hint) { + delete addon; + fprintf(stderr, "hint: %u\n", *hint); + delete hint; + } + + static Napi::Object Init(Napi::Env env, Napi::Value jshint) { + if (!jshint.IsNumber()) { + NAPI_THROW(Napi::Error::New(env, "Expected number"), Napi::Object()); + } + uint32_t hint = jshint.As(); + if (hint == 0) + env.SetInstanceData(new Addon(env)); + else + env.SetInstanceData(new Addon(env), + new uint32_t(hint)); + Napi::Object result = Napi::Object::New(env); + result.DefineProperties({ + Napi::PropertyDescriptor::Accessor("verbose"), + }); + + return result; + } + + private: + bool verbose = false; + Napi::FunctionReference VerboseIndicator; +}; + +// We use an addon factory so we can cover both the case where there is an +// instance data hint and the case where there isn't. +static Napi::Value AddonFactory(const Napi::CallbackInfo& info) { + return Addon::Init(info.Env(), info[0]); +} + +Napi::Object InitAddonData(Napi::Env env) { + return Napi::Function::New(env, AddonFactory); +} +#endif // (NAPI_VERSION > 5) diff --git a/test/node-addon-api/test/addon_data.js b/test/node-addon-api/test/addon_data.js new file mode 100644 index 0000000..900aa32 --- /dev/null +++ b/test/node-addon-api/test/addon_data.js @@ -0,0 +1,24 @@ +'use strict'; + +const common = require('./common'); + +module.exports = common.runTest(test); + +async function test () { + await common.runTestInChildProcess({ + suite: 'addon_data', + testName: 'workingCode' + }); + + await common.runTestInChildProcess({ + suite: 'addon_data', + testName: 'cleanupWithoutHint', + expectedStderr: ['addon_data: Addon::~Addon'] + }); + + await common.runTestInChildProcess({ + suite: 'addon_data', + testName: 'cleanupWithHint', + expectedStderr: ['addon_data: Addon::~Addon', 'hint: 42'] + }); +} diff --git a/test/node-addon-api/test/array_buffer.cc b/test/node-addon-api/test/array_buffer.cc new file mode 100644 index 0000000..2b07bd2 --- /dev/null +++ b/test/node-addon-api/test/array_buffer.cc @@ -0,0 +1,243 @@ +#include "napi.h" + +using namespace Napi; + +namespace { + +const size_t testLength = 4; +uint8_t testData[testLength]; +int finalizeCount = 0; + +void InitData(uint8_t* data, size_t length) { + for (size_t i = 0; i < length; i++) { + data[i] = static_cast(i); + } +} + +bool VerifyData(uint8_t* data, size_t length) { + for (size_t i = 0; i < length; i++) { + if (data[i] != static_cast(i)) { + return false; + } + } + return true; +} + +Value CreateBuffer(const CallbackInfo& info) { + ArrayBuffer buffer = ArrayBuffer::New(info.Env(), testLength); + + if (buffer.ByteLength() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + InitData(static_cast(buffer.Data()), testLength); + return buffer; +} + +Value CreateExternalBuffer(const CallbackInfo& info) { + finalizeCount = 0; + + ArrayBuffer buffer = ArrayBuffer::New(info.Env(), testData, testLength); + + if (buffer.ByteLength() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + if (buffer.Data() != testData) { + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); + return Value(); + } + + InitData(testData, testLength); + return buffer; +} + +Value CreateExternalBufferWithFinalize(const CallbackInfo& info) { + finalizeCount = 0; + + uint8_t* data = new uint8_t[testLength]; + + ArrayBuffer buffer = ArrayBuffer::New( + info.Env(), data, testLength, [](Env /*env*/, void* finalizeData) { + delete[] static_cast(finalizeData); + finalizeCount++; + }); + + if (buffer.ByteLength() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + if (buffer.Data() != data) { + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); + return Value(); + } + + InitData(data, testLength); + return buffer; +} + +Value CreateExternalBufferWithFinalizeHint(const CallbackInfo& info) { + finalizeCount = 0; + + uint8_t* data = new uint8_t[testLength]; + + char* hint = nullptr; + ArrayBuffer buffer = ArrayBuffer::New( + info.Env(), + data, + testLength, + [](Env /*env*/, void* finalizeData, char* /*finalizeHint*/) { + delete[] static_cast(finalizeData); + finalizeCount++; + }, + hint); + + if (buffer.ByteLength() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + if (buffer.Data() != data) { + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); + return Value(); + } + + InitData(data, testLength); + return buffer; +} + +void CheckBuffer(const CallbackInfo& info) { + if (!info[0].IsArrayBuffer()) { + Error::New(info.Env(), "A buffer was expected.") + .ThrowAsJavaScriptException(); + return; + } + + ArrayBuffer buffer = info[0].As(); + + if (buffer.ByteLength() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return; + } + + if (!VerifyData(static_cast(buffer.Data()), testLength)) { + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); + return; + } +} + +Value GetFinalizeCount(const CallbackInfo& info) { + return Number::New(info.Env(), finalizeCount); +} + +Value CreateBufferWithConstructor(const CallbackInfo& info) { + ArrayBuffer buffer = ArrayBuffer::New(info.Env(), testLength); + if (buffer.ByteLength() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + InitData(static_cast(buffer.Data()), testLength); + ArrayBuffer buffer2(info.Env(), buffer); + return buffer2; +} + +Value CheckEmptyBuffer(const CallbackInfo& info) { + ArrayBuffer buffer; + return Boolean::New(info.Env(), buffer.IsEmpty()); +} + +void CheckDetachUpdatesData(const CallbackInfo& info) { + if (!info[0].IsArrayBuffer()) { + Error::New(info.Env(), "A buffer was expected.") + .ThrowAsJavaScriptException(); + return; + } + + ArrayBuffer buffer = info[0].As(); + + // This potentially causes the buffer to cache its data pointer and length. + buffer.Data(); + buffer.ByteLength(); + +#if NAPI_VERSION >= 7 + if (buffer.IsDetached()) { + Error::New(info.Env(), "Buffer should not be detached.") + .ThrowAsJavaScriptException(); + return; + } +#endif + + if (info.Length() == 2) { + // Detach externally (in JavaScript). + if (!info[1].IsFunction()) { + Error::New(info.Env(), "A function was expected.") + .ThrowAsJavaScriptException(); + return; + } + + Function detach = info[1].As(); + detach.Call({}); + } else { +#if NAPI_VERSION >= 7 + // Detach directly. + buffer.Detach(); +#else + return; +#endif + } + +#if NAPI_VERSION >= 7 + if (!buffer.IsDetached()) { + Error::New(info.Env(), "Buffer should be detached.") + .ThrowAsJavaScriptException(); + return; + } +#endif + + if (buffer.Data() != nullptr) { + Error::New(info.Env(), "Incorrect data pointer.") + .ThrowAsJavaScriptException(); + return; + } + + if (buffer.ByteLength() != 0) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return; + } +} + +} // end anonymous namespace + +Object InitArrayBuffer(Env env) { + Object exports = Object::New(env); + + exports["createBuffer"] = Function::New(env, CreateBuffer); + exports["createExternalBuffer"] = Function::New(env, CreateExternalBuffer); + exports["createExternalBufferWithFinalize"] = + Function::New(env, CreateExternalBufferWithFinalize); + exports["createExternalBufferWithFinalizeHint"] = + Function::New(env, CreateExternalBufferWithFinalizeHint); + exports["checkBuffer"] = Function::New(env, CheckBuffer); + exports["getFinalizeCount"] = Function::New(env, GetFinalizeCount); + exports["createBufferWithConstructor"] = + Function::New(env, CreateBufferWithConstructor); + exports["checkEmptyBuffer"] = Function::New(env, CheckEmptyBuffer); + exports["checkDetachUpdatesData"] = + Function::New(env, CheckDetachUpdatesData); + + return exports; +} diff --git a/test/node-addon-api/test/array_buffer.js b/test/node-addon-api/test/array_buffer.js new file mode 100644 index 0000000..2b1caac --- /dev/null +++ b/test/node-addon-api/test/array_buffer.js @@ -0,0 +1,72 @@ +'use strict'; + +const assert = require('assert'); +const testUtil = require('./testUtil'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + return testUtil.runGCTests([ + 'Internal ArrayBuffer', + () => { + const test = binding.arraybuffer.createBuffer(); + binding.arraybuffer.checkBuffer(test); + assert.ok(test instanceof ArrayBuffer); + + const test2 = test.slice(0); + binding.arraybuffer.checkBuffer(test2); + }, + + 'External ArrayBuffer', + () => { + const test = binding.arraybuffer.createExternalBuffer(); + binding.arraybuffer.checkBuffer(test); + assert.ok(test instanceof ArrayBuffer); + assert.strictEqual(0, binding.arraybuffer.getFinalizeCount()); + }, + + () => assert.strictEqual(0, binding.arraybuffer.getFinalizeCount()), + + 'External ArrayBuffer with finalizer', + () => { + const test = binding.arraybuffer.createExternalBufferWithFinalize(); + binding.arraybuffer.checkBuffer(test); + assert.ok(test instanceof ArrayBuffer); + assert.strictEqual(0, binding.arraybuffer.getFinalizeCount()); + }, + + () => assert.strictEqual(1, binding.arraybuffer.getFinalizeCount()), + + 'External ArrayBuffer with finalizer hint', + () => { + const test = binding.arraybuffer.createExternalBufferWithFinalizeHint(); + binding.arraybuffer.checkBuffer(test); + assert.ok(test instanceof ArrayBuffer); + assert.strictEqual(0, binding.arraybuffer.getFinalizeCount()); + }, + + () => assert.strictEqual(1, binding.arraybuffer.getFinalizeCount()), + + 'ArrayBuffer with constructor', + () => { + assert.strictEqual(true, binding.arraybuffer.checkEmptyBuffer()); + const test = binding.arraybuffer.createBufferWithConstructor(); + binding.arraybuffer.checkBuffer(test); + assert.ok(test instanceof ArrayBuffer); + }, + + 'ArrayBuffer updates data pointer and length when detached', + () => { + // Detach the ArrayBuffer in JavaScript. + + // quickjs-napi: no WebAssembly; ArrayBuffer.prototype.transfer + // detaches the buffer from JavaScript as well. + const ab = new ArrayBuffer(65536); + binding.arraybuffer.checkDetachUpdatesData(ab, () => ab.transfer()); + + // Let C++ detach the ArrayBuffer. + const extBuffer = binding.arraybuffer.createExternalBuffer(); + binding.arraybuffer.checkDetachUpdatesData(extBuffer); + } + ]); +} diff --git a/test/node-addon-api/test/async_context.cc b/test/node-addon-api/test/async_context.cc new file mode 100644 index 0000000..be2e1d9 --- /dev/null +++ b/test/node-addon-api/test/async_context.cc @@ -0,0 +1,36 @@ +#include "napi.h" + +using namespace Napi; + +namespace { + +static void MakeCallback(const CallbackInfo& info) { + Function callback = info[0].As(); + Object resource = info[1].As(); + AsyncContext context(info.Env(), "async_context_test", resource); + callback.MakeCallback( + Object::New(info.Env()), std::initializer_list{}, context); +} + +static void MakeCallbackNoResource(const CallbackInfo& info) { + Function callback = info[0].As(); + AsyncContext context(info.Env(), "async_context_no_res_test"); + callback.MakeCallback( + Object::New(info.Env()), std::initializer_list{}, context); +} + +static Boolean AssertAsyncContextReturnCorrectEnv(const CallbackInfo& info) { + AsyncContext context(info.Env(), "empty_context_test"); + return Boolean::New(info.Env(), context.Env() == info.Env()); +} +} // end anonymous namespace + +Object InitAsyncContext(Env env) { + Object exports = Object::New(env); + exports["makeCallback"] = Function::New(env, MakeCallback); + exports["makeCallbackNoResource"] = + Function::New(env, MakeCallbackNoResource); + exports["asyncCxtReturnCorrectEnv"] = + Function::New(env, AssertAsyncContextReturnCorrectEnv); + return exports; +} diff --git a/test/node-addon-api/test/async_context.js b/test/node-addon-api/test/async_context.js new file mode 100644 index 0000000..8f54e9c --- /dev/null +++ b/test/node-addon-api/test/async_context.js @@ -0,0 +1,122 @@ +'use strict'; + +const assert = require('assert'); +const common = require('./common'); + +// we only check async hooks on 8.x an higher were +// they are closer to working properly +const nodeVersion = process.versions.node.split('.')[0]; +let asyncHooks; +function checkAsyncHooks () { + if (false) { // quickjs-napi: no async_hooks + if (asyncHooks === undefined) { + asyncHooks = require('async_hooks'); + } + return true; + } + return false; +} + +module.exports = common.runTest(test); + +function installAsyncHooksForTest (resName) { + return new Promise((resolve, reject) => { + let id; + const events = []; + /** + * TODO(legendecas): investigate why resolving & disabling hooks in + * destroy callback causing crash with case 'callbackscope.js'. + */ + let destroyed = false; + const hook = asyncHooks.createHook({ + init (asyncId, type, triggerAsyncId, resource) { + if (id === undefined && type === resName) { + id = asyncId; + events.push({ eventName: 'init', type, triggerAsyncId, resource }); + } + }, + before (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'before' }); + } + }, + after (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'after' }); + } + }, + destroy (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'destroy' }); + destroyed = true; + } + } + }).enable(); + + const interval = setInterval(() => { + if (destroyed) { + hook.disable(); + clearInterval(interval); + resolve(events); + } + }, 10); + }); +} + +async function makeCallbackWithResource (binding) { + const hooks = installAsyncHooksForTest('async_context_test'); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + binding.asynccontext.makeCallback(common.mustCall(), { foo: 'foo' }); + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'async_context_test', + triggerAsyncId, + resource: { foo: 'foo' } + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + resolve(); + }); +} + +async function makeCallbackWithoutResource (binding) { + const hooks = installAsyncHooksForTest('async_context_no_res_test'); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + binding.asynccontext.makeCallbackNoResource(common.mustCall()); + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'async_context_no_res_test', + triggerAsyncId, + resource: { } + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + resolve(); + }); +} + +function assertAsyncContextReturnsCorrectEnv (binding) { + assert.strictEqual(binding.asynccontext.asyncCxtReturnCorrectEnv(), true); +} + +async function test (binding) { + if (!checkAsyncHooks()) { + return; + } + + await makeCallbackWithResource(binding); + await makeCallbackWithoutResource(binding); + assertAsyncContextReturnsCorrectEnv(binding); +} diff --git a/test/node-addon-api/test/async_progress_queue_worker.cc b/test/node-addon-api/test/async_progress_queue_worker.cc new file mode 100644 index 0000000..90ff881 --- /dev/null +++ b/test/node-addon-api/test/async_progress_queue_worker.cc @@ -0,0 +1,248 @@ +#include "napi.h" + +#include +#include +#include +#include + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +struct ProgressData { + int32_t progress; +}; + +class TestWorkerWithNoCb : public AsyncProgressQueueWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 1: { + Function cb = info[0].As(); + TestWorkerWithNoCb* worker = new TestWorkerWithNoCb(info.Env(), cb); + worker->Queue(); + } break; + + case 2: { + std::string resName = info[0].As(); + Function cb = info[1].As(); + TestWorkerWithNoCb* worker = + new TestWorkerWithNoCb(info.Env(), resName.c_str(), cb); + worker->Queue(); + } break; + + case 3: { + std::string resName = info[0].As(); + Object resObject = info[1].As(); + Function cb = info[2].As(); + TestWorkerWithNoCb* worker = + new TestWorkerWithNoCb(info.Env(), resName.c_str(), resObject, cb); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress& progress) override { + ProgressData data{1}; + progress.Send(&data, 1); + } + + void OnProgress(const ProgressData*, size_t /* count */) override { + _cb.Call({}); + } + + private: + TestWorkerWithNoCb(Napi::Env env, Function cb) + : AsyncProgressQueueWorker(env) { + _cb.Reset(cb, 1); + } + TestWorkerWithNoCb(Napi::Env env, const char* resourceName, Function cb) + : AsyncProgressQueueWorker(env, resourceName) { + _cb.Reset(cb, 1); + } + TestWorkerWithNoCb(Napi::Env env, + const char* resourceName, + const Object& resourceObject, + Function cb) + : AsyncProgressQueueWorker(env, resourceName, resourceObject) { + _cb.Reset(cb, 1); + } + FunctionReference _cb; +}; + +class TestWorkerWithRecv : public AsyncProgressQueueWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 2: { + Object recv = info[0].As(); + Function cb = info[1].As(); + TestWorkerWithRecv* worker = new TestWorkerWithRecv(recv, cb); + worker->Queue(); + } break; + + case 3: { + Object recv = info[0].As(); + Function cb = info[1].As(); + std::string resName = info[2].As(); + TestWorkerWithRecv* worker = + new TestWorkerWithRecv(recv, cb, resName.c_str()); + worker->Queue(); + } break; + + case 4: { + Object recv = info[0].As(); + Function cb = info[1].As(); + std::string resName = info[2].As(); + Object resObject = info[3].As(); + TestWorkerWithRecv* worker = + new TestWorkerWithRecv(recv, cb, resName.c_str(), resObject); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress&) override {} + + void OnProgress(const ProgressData*, size_t /* count */) override {} + + private: + TestWorkerWithRecv(const Object& recv, const Function& cb) + : AsyncProgressQueueWorker(recv, cb) {} + TestWorkerWithRecv(const Object& recv, + const Function& cb, + const char* resourceName) + : AsyncProgressQueueWorker(recv, cb, resourceName) {} + TestWorkerWithRecv(const Object& recv, + const Function& cb, + const char* resourceName, + const Object& resourceObject) + : AsyncProgressQueueWorker(recv, cb, resourceName, resourceObject) {} +}; + +class TestWorkerWithCb : public AsyncProgressQueueWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 1: { + Function cb = info[0].As(); + TestWorkerWithCb* worker = new TestWorkerWithCb(cb); + worker->Queue(); + } break; + + case 2: { + Function cb = info[0].As(); + std::string asyncResName = info[1].As(); + TestWorkerWithCb* worker = + new TestWorkerWithCb(cb, asyncResName.c_str()); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress&) override {} + + void OnProgress(const ProgressData*, size_t /* count */) override {} + + private: + TestWorkerWithCb(Function cb) : AsyncProgressQueueWorker(cb) {} + TestWorkerWithCb(Function cb, const char* res_name) + : AsyncProgressQueueWorker(cb, res_name) {} +}; + +class TestWorker : public AsyncProgressQueueWorker { + public: + static Napi::Value CreateWork(const CallbackInfo& info) { + int32_t times = info[0].As().Int32Value(); + Function cb = info[1].As(); + Function progress = info[2].As(); + + TestWorker* worker = new TestWorker( + cb, progress, "TestResource", Object::New(info.Env()), times); + + return Napi::External::New(info.Env(), worker); + } + + static void QueueWork(const CallbackInfo& info) { + auto wrap = info[0].As>(); + auto worker = wrap.Data(); + worker->Queue(); + } + + protected: + void Execute(const ExecutionProgress& progress) override { + using namespace std::chrono_literals; + std::this_thread::sleep_for(1s); + + if (_times < 0) { + SetError("test error"); + } else { + progress.Signal(); + } + ProgressData data{0}; + for (int32_t idx = 0; idx < _times; idx++) { + data.progress = idx; + progress.Send(&data, 1); + } + } + + void OnProgress(const ProgressData* data, size_t count) override { + Napi::Env env = Env(); + _test_case_count++; + if (!_js_progress_cb.IsEmpty()) { + if (_test_case_count == 1) { + if (count != 0) { + SetError("expect 0 count of data on 1st call"); + } + } else { + Number progress = Number::New(env, data->progress); + _js_progress_cb.Call(Receiver().Value(), {progress}); + } + } + } + + private: + TestWorker(Function cb, + Function progress, + const char* resource_name, + const Object& resource, + int32_t times) + : AsyncProgressQueueWorker(cb, resource_name, resource), _times(times) { + _js_progress_cb.Reset(progress, 1); + } + + int32_t _times; + size_t _test_case_count = 0; + FunctionReference _js_progress_cb; +}; + +} // namespace + +Object InitAsyncProgressQueueWorker(Env env) { + Object exports = Object::New(env); + exports["createWork"] = Function::New(env, TestWorker::CreateWork); + exports["queueWork"] = Function::New(env, TestWorker::QueueWork); + exports["runWorkerNoCb"] = Function::New(env, TestWorkerWithNoCb::DoWork); + exports["runWorkerWithRecv"] = Function::New(env, TestWorkerWithRecv::DoWork); + exports["runWorkerWithCb"] = Function::New(env, TestWorkerWithCb::DoWork); + return exports; +} + +#endif diff --git a/test/node-addon-api/test/async_progress_queue_worker.js b/test/node-addon-api/test/async_progress_queue_worker.js new file mode 100644 index 0000000..28134b0 --- /dev/null +++ b/test/node-addon-api/test/async_progress_queue_worker.js @@ -0,0 +1,180 @@ +'use strict'; + +const common = require('./common'); +const assert = require('assert'); + +module.exports = common.runTest(test); +const nodeVersion = process.versions.node.split('.')[0]; + +let asyncHooks; +function checkAsyncHooks () { + if (false) { // quickjs-napi: no async_hooks + if (asyncHooks === undefined) { + asyncHooks = require('async_hooks'); + } + return true; + } + return false; +} + +async function test ({ asyncprogressqueueworker }) { + await success(asyncprogressqueueworker); + await fail(asyncprogressqueueworker); + + await asyncProgressWorkerCallbackOverloads(asyncprogressqueueworker.runWorkerWithCb); + await asyncProgressWorkerRecvOverloads(asyncprogressqueueworker.runWorkerWithRecv); + await asyncProgressWorkerNoCbOverloads(asyncprogressqueueworker.runWorkerNoCb); +} + +async function asyncProgressWorkerCallbackOverloads (bindingFunction) { + bindingFunction(common.mustCall()); + if (!checkAsyncHooks()) { + return; + } + + const hooks = common.installAysncHooks('cbResources'); + + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + bindingFunction(common.mustCall(), 'cbResources'); + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'cbResources', + triggerAsyncId, + resource: {} + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + resolve(); + }).catch((err) => reject(err)); + }); +} + +async function asyncProgressWorkerRecvOverloads (bindingFunction) { + const recvObject = { + a: 4 + }; + + function cb () { + assert.strictEqual(this.a, recvObject.a); + } + + bindingFunction(recvObject, common.mustCall(cb)); + if (!checkAsyncHooks()) { + return; + } + const asyncResources = [ + { resName: 'cbRecvResources', resObject: {} }, + { resName: 'cbRecvResourcesObject', resObject: { foo: 'bar' } } + ]; + + for (const asyncResource of asyncResources) { + const asyncResName = asyncResource.resName; + const asyncResObject = asyncResource.resObject; + + const hooks = common.installAysncHooks(asyncResource.resName); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + if (Object.keys(asyncResObject).length === 0) { + bindingFunction(recvObject, common.mustCall(cb), asyncResName); + } else { + bindingFunction(recvObject, common.mustCall(cb), asyncResName, asyncResObject); + } + + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: asyncResName, + triggerAsyncId, + resource: asyncResObject + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + resolve(); + }).catch((err) => reject(err)); + }); + } +} + +async function asyncProgressWorkerNoCbOverloads (bindingFunction) { + bindingFunction(common.mustCall()); + if (!checkAsyncHooks()) { + return; + } + const asyncResources = [ + { resName: 'noCbResources', resObject: {} }, + { resName: 'noCbResourcesObject', resObject: { foo: 'bar' } } + ]; + + for (const asyncResource of asyncResources) { + const asyncResName = asyncResource.resName; + const asyncResObject = asyncResource.resObject; + + const hooks = common.installAysncHooks(asyncResource.resName); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + if (Object.keys(asyncResObject).length === 0) { + bindingFunction(asyncResName, common.mustCall(() => {})); + } else { + bindingFunction(asyncResName, asyncResObject, common.mustCall(() => {})); + } + + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: asyncResName, + triggerAsyncId, + resource: asyncResObject + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + resolve(); + }).catch((err) => reject(err)); + }); + } +} + +function success (binding) { + return new Promise((resolve, reject) => { + const expected = [0, 1, 2, 3]; + const actual = []; + const worker = binding.createWork(expected.length, + common.mustCall((err) => { + if (err) { + reject(err); + } else { + // All queued items shall be invoked before complete callback. + assert.deepEqual(actual, expected); + resolve(); + } + }), + common.mustCall((_progress) => { + actual.push(_progress); + }, expected.length) + ); + binding.queueWork(worker); + }); +} + +function fail (binding) { + return new Promise((resolve, reject) => { + const worker = binding.createWork(-1, + common.mustCall((err) => { + assert.throws(() => { throw err; }, /test error/); + resolve(); + }), + common.mustNotCall() + ); + binding.queueWork(worker); + }); +} diff --git a/test/node-addon-api/test/async_progress_worker.cc b/test/node-addon-api/test/async_progress_worker.cc new file mode 100644 index 0000000..17aaef3 --- /dev/null +++ b/test/node-addon-api/test/async_progress_worker.cc @@ -0,0 +1,357 @@ +#include "napi.h" + +#include +#include +#include +#include +#include + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +struct ProgressData { + size_t progress; +}; + +class TestWorkerWithNoCb : public AsyncProgressWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 1: { + Function cb = info[0].As(); + TestWorkerWithNoCb* worker = new TestWorkerWithNoCb(info.Env(), cb); + worker->Queue(); + } break; + + case 2: { + std::string resName = info[0].As(); + Function cb = info[1].As(); + TestWorkerWithNoCb* worker = + new TestWorkerWithNoCb(info.Env(), resName.c_str(), cb); + worker->Queue(); + } break; + + case 3: { + std::string resName = info[0].As(); + Object resObject = info[1].As(); + Function cb = info[2].As(); + TestWorkerWithNoCb* worker = + new TestWorkerWithNoCb(info.Env(), resName.c_str(), resObject, cb); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress& progress) override { + ProgressData data{1}; + progress.Send(&data, 1); + } + + void OnProgress(const ProgressData*, size_t /* count */) override { + _cb.Call({}); + } + + private: + TestWorkerWithNoCb(Napi::Env env, Function cb) : AsyncProgressWorker(env) { + _cb.Reset(cb, 1); + } + TestWorkerWithNoCb(Napi::Env env, const char* resourceName, Function cb) + : AsyncProgressWorker(env, resourceName) { + _cb.Reset(cb, 1); + } + TestWorkerWithNoCb(Napi::Env env, + const char* resourceName, + const Object& resourceObject, + Function cb) + : AsyncProgressWorker(env, resourceName, resourceObject) { + _cb.Reset(cb, 1); + } + FunctionReference _cb; +}; + +class TestWorkerWithRecv : public AsyncProgressWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 2: { + Object recv = info[0].As(); + Function cb = info[1].As(); + TestWorkerWithRecv* worker = new TestWorkerWithRecv(recv, cb); + worker->Queue(); + } break; + + case 3: { + Object recv = info[0].As(); + Function cb = info[1].As(); + std::string resName = info[2].As(); + TestWorkerWithRecv* worker = + new TestWorkerWithRecv(recv, cb, resName.c_str()); + worker->Queue(); + } break; + + case 4: { + Object recv = info[0].As(); + Function cb = info[1].As(); + std::string resName = info[2].As(); + Object resObject = info[3].As(); + TestWorkerWithRecv* worker = + new TestWorkerWithRecv(recv, cb, resName.c_str(), resObject); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress&) override {} + + void OnProgress(const ProgressData*, size_t /* count */) override {} + + private: + TestWorkerWithRecv(const Object& recv, const Function& cb) + : AsyncProgressWorker(recv, cb) {} + TestWorkerWithRecv(const Object& recv, + const Function& cb, + const char* resourceName) + : AsyncProgressWorker(recv, cb, resourceName) {} + TestWorkerWithRecv(const Object& recv, + const Function& cb, + const char* resourceName, + const Object& resourceObject) + : AsyncProgressWorker(recv, cb, resourceName, resourceObject) {} +}; + +class TestWorkerWithCb : public AsyncProgressWorker { + public: + static void DoWork(const CallbackInfo& info) { + switch (info.Length()) { + case 1: { + Function cb = info[0].As(); + TestWorkerWithCb* worker = new TestWorkerWithCb(cb); + worker->Queue(); + } break; + + case 2: { + Function cb = info[0].As(); + std::string asyncResName = info[1].As(); + TestWorkerWithCb* worker = + new TestWorkerWithCb(cb, asyncResName.c_str()); + worker->Queue(); + } break; + + default: + + break; + } + } + + protected: + void Execute(const ExecutionProgress&) override {} + + void OnProgress(const ProgressData*, size_t /* count */) override {} + + private: + TestWorkerWithCb(Function cb) : AsyncProgressWorker(cb) {} + TestWorkerWithCb(Function cb, const char* res_name) + : AsyncProgressWorker(cb, res_name) {} +}; + +class TestWorker : public AsyncProgressWorker { + public: + static void DoWork(const CallbackInfo& info) { + int32_t times = info[0].As().Int32Value(); + Function cb = info[1].As(); + Function progress = info[2].As(); + + TestWorker* worker = + new TestWorker(cb, progress, "TestResource", Object::New(info.Env())); + worker->_times = times; + worker->Queue(); + } + + protected: + void Execute(const ExecutionProgress& progress) override { + if (_times < 0) { + SetError("test error"); + } + ProgressData data{0}; + + for (int32_t idx = 0; idx < _times; idx++) { + data.progress = idx; + progress.Send(&data, 1); + + { + std::unique_lock lk(_cvm); + _cv.wait(lk, [this] { return dataSent; }); + dataSent = false; + } + } + } + + void OnProgress(const ProgressData* data, size_t /* count */) override { + Napi::Env env = Env(); + if (!_progress.IsEmpty()) { + Number progress = Number::New(env, data->progress); + _progress.MakeCallback(Receiver().Value(), {progress}); + } + + { + std::lock_guard lk(_cvm); + dataSent = true; + _cv.notify_one(); + } + } + + private: + TestWorker(Function cb, + Function progress, + const char* resource_name, + const Object& resource) + : AsyncProgressWorker(cb, resource_name, resource) { + _progress.Reset(progress, 1); + } + + bool dataSent = false; + std::condition_variable _cv; + std::mutex _cvm; + int32_t _times; + FunctionReference _progress; +}; + +class MalignWorker : public AsyncProgressWorker { + public: + static void DoWork(const CallbackInfo& info) { + Function cb = info[0].As(); + Function progress = info[1].As(); + + MalignWorker* worker = + new MalignWorker(cb, progress, "TestResource", Object::New(info.Env())); + worker->Queue(); + } + + protected: + void Execute(const ExecutionProgress& progress) override { + { + std::unique_lock lock(_cvm); + // Testing a nullptr send is acceptable. + progress.Send(nullptr, 0); + _cv.wait(lock, [this] { return _test_case_count == 1; }); + } + { + std::unique_lock lock(_cvm); + progress.Signal(); + _cv.wait(lock, [this] { return _test_case_count == 2; }); + } + // Testing busy looping on send doesn't trigger unexpected empty data + // OnProgress call. + for (size_t i = 0; i < 1000000; i++) { + ProgressData data{0}; + progress.Send(&data, 1); + } + } + + void OnProgress(const ProgressData* /* data */, size_t count) override { + Napi::Env env = Env(); + { + std::lock_guard lock(_cvm); + _test_case_count++; + } + bool error = false; + Napi::String reason = Napi::String::New(env, "No error"); + if (_test_case_count <= 2 && count != 0) { + error = true; + reason = + Napi::String::New(env, "expect 0 count of data on 1st and 2nd call"); + } + if (_test_case_count > 2 && count != 1) { + error = true; + reason = Napi::String::New( + env, "expect 1 count of data on non-1st and non-2nd call"); + } + _progress.MakeCallback(Receiver().Value(), + {Napi::Boolean::New(env, error), reason}); + _cv.notify_one(); + } + + private: + MalignWorker(Function cb, + Function progress, + const char* resource_name, + const Object& resource) + : AsyncProgressWorker(cb, resource_name, resource) { + _progress.Reset(progress, 1); + } + + size_t _test_case_count = 0; + std::condition_variable _cv; + std::mutex _cvm; + FunctionReference _progress; +}; + +// Calling a Signal after a SendProgress should not clear progress data +class SignalAfterProgressTestWorker : public AsyncProgressWorker { + public: + static void DoWork(const CallbackInfo& info) { + Function cb = info[0].As(); + Function progress = info[1].As(); + + SignalAfterProgressTestWorker* worker = new SignalAfterProgressTestWorker( + cb, progress, "TestResource", Object::New(info.Env())); + worker->Queue(); + } + + protected: + void Execute(const ExecutionProgress& progress) override { + ProgressData data{0}; + progress.Send(&data, 1); + progress.Signal(); + } + + void OnProgress(const ProgressData* /* data */, size_t count) override { + Napi::Env env = Env(); + bool error = false; + Napi::String reason = Napi::String::New(env, "No error"); + if (count != 1) { + error = true; + reason = Napi::String::New(env, "expect 1 count of data"); + } + _progress.MakeCallback(Receiver().Value(), + {Napi::Boolean::New(env, error), reason}); + } + + private: + SignalAfterProgressTestWorker(Function cb, + Function progress, + const char* resource_name, + const Object& resource) + : AsyncProgressWorker(cb, resource_name, resource) { + _progress.Reset(progress, 1); + } + FunctionReference _progress; +}; +} // namespace + +Object InitAsyncProgressWorker(Env env) { + Object exports = Object::New(env); + exports["doWork"] = Function::New(env, TestWorker::DoWork); + exports["doMalignTest"] = Function::New(env, MalignWorker::DoWork); + exports["doSignalAfterProgressTest"] = + Function::New(env, SignalAfterProgressTestWorker::DoWork); + exports["runWorkerNoCb"] = Function::New(env, TestWorkerWithNoCb::DoWork); + exports["runWorkerWithRecv"] = Function::New(env, TestWorkerWithRecv::DoWork); + exports["runWorkerWithCb"] = Function::New(env, TestWorkerWithCb::DoWork); + return exports; +} + +#endif diff --git a/test/node-addon-api/test/async_progress_worker.js b/test/node-addon-api/test/async_progress_worker.js new file mode 100644 index 0000000..8bc07aa --- /dev/null +++ b/test/node-addon-api/test/async_progress_worker.js @@ -0,0 +1,200 @@ +'use strict'; + +const common = require('./common'); +const assert = require('assert'); + +module.exports = common.runTest(test); +const nodeVersion = process.versions.node.split('.')[0]; + +let asyncHooks; +function checkAsyncHooks () { + if (false) { // quickjs-napi: no async_hooks + if (asyncHooks === undefined) { + asyncHooks = require('async_hooks'); + } + return true; + } + return false; +} + +async function test ({ asyncprogressworker }) { + await success(asyncprogressworker); + await fail(asyncprogressworker); + await signalTest(asyncprogressworker.doMalignTest); + await signalTest(asyncprogressworker.doSignalAfterProgressTest); + + await asyncProgressWorkerCallbackOverloads(asyncprogressworker.runWorkerWithCb); + await asyncProgressWorkerRecvOverloads(asyncprogressworker.runWorkerWithRecv); + await asyncProgressWorkerNoCbOverloads(asyncprogressworker.runWorkerNoCb); +} + +async function asyncProgressWorkerCallbackOverloads (bindingFunction) { + bindingFunction(common.mustCall()); + if (!checkAsyncHooks()) { + return; + } + + const hooks = common.installAysncHooks('cbResources'); + + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + bindingFunction(common.mustCall(), 'cbResources'); + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'cbResources', + triggerAsyncId, + resource: {} + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + resolve(); + }); +} + +async function asyncProgressWorkerRecvOverloads (bindingFunction) { + const recvObject = { + a: 4 + }; + + function cb () { + assert.strictEqual(this.a, recvObject.a); + } + + bindingFunction(recvObject, common.mustCall(cb)); + if (!checkAsyncHooks()) { + return; + } + const asyncResources = [ + { resName: 'cbRecvResources', resObject: {} }, + { resName: 'cbRecvResourcesObject', resObject: { foo: 'bar' } } + ]; + + for (const asyncResource of asyncResources) { + const asyncResName = asyncResource.resName; + const asyncResObject = asyncResource.resObject; + + const hooks = common.installAysncHooks(asyncResource.resName); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + if (Object.keys(asyncResObject).length === 0) { + bindingFunction(recvObject, common.mustCall(cb), asyncResName); + } else { + bindingFunction(recvObject, common.mustCall(cb), asyncResName, asyncResObject); + } + + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: asyncResName, + triggerAsyncId, + resource: asyncResObject + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + resolve(); + }); + } +} + +async function asyncProgressWorkerNoCbOverloads (bindingFunction) { + bindingFunction(common.mustCall(() => {})); + if (!checkAsyncHooks()) { + return; + } + const asyncResources = [ + { resName: 'noCbResources', resObject: {} }, + { resName: 'noCbResourcesObject', resObject: { foo: 'bar' } } + ]; + + for (const asyncResource of asyncResources) { + const asyncResName = asyncResource.resName; + const asyncResObject = asyncResource.resObject; + + const hooks = common.installAysncHooks(asyncResource.resName); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve, reject) => { + if (Object.keys(asyncResObject).length === 0) { + bindingFunction(asyncResName, common.mustCall(() => {})); + } else { + bindingFunction(asyncResName, asyncResObject, common.mustCall(() => {})); + } + + hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: asyncResName, + triggerAsyncId, + resource: asyncResObject + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + resolve(); + }); + } +} + +function success (binding) { + return new Promise((resolve, reject) => { + const expected = [0, 1, 2, 3]; + const actual = []; + binding.doWork(expected.length, + common.mustCall((err) => { + if (err) { + reject(err); + } + }), + common.mustCall((_progress) => { + actual.push(_progress); + if (actual.length === expected.length) { + assert.deepEqual(actual, expected); + resolve(); + } + }, expected.length) + ); + }); +} + +function fail (binding) { + return new Promise((resolve) => { + binding.doWork(-1, + common.mustCall((err) => { + assert.throws(() => { throw err; }, /test error/); + resolve(); + }), + common.mustNotCall() + ); + }); +} + +function signalTest (bindingFunction) { + return new Promise((resolve, reject) => { + bindingFunction( + common.mustCall((err) => { + if (err) { + return reject(err); + } + resolve(); + }), + common.mustCallAtLeast((error, reason) => { + try { + assert(!error, reason); + } catch (e) { + reject(e); + } + }, 1) + ); + }); +} diff --git a/test/node-addon-api/test/async_worker.cc b/test/node-addon-api/test/async_worker.cc new file mode 100644 index 0000000..34044e9 --- /dev/null +++ b/test/node-addon-api/test/async_worker.cc @@ -0,0 +1,341 @@ +#include +#include +#include +#include +#include "assert.h" +#include "napi.h" + +using namespace Napi; + +class TestWorkerWithUserDefRecv : public AsyncWorker { + public: + static void DoWork(const CallbackInfo& info) { + Object recv = info[0].As(); + Function cb = info[1].As(); + + TestWorkerWithUserDefRecv* worker = new TestWorkerWithUserDefRecv(recv, cb); + worker->Queue(); + } + + static void DoWorkWithAsyncRes(const CallbackInfo& info) { + Object recv = info[0].As(); + Function cb = info[1].As(); + Value resource = info[2]; + + TestWorkerWithUserDefRecv* worker = nullptr; + if (resource == info.Env().Null()) { + worker = new TestWorkerWithUserDefRecv(recv, cb, "TestResource"); + } else { + worker = new TestWorkerWithUserDefRecv( + recv, cb, "TestResource", resource.As()); + } + + worker->Queue(); + } + + protected: + void Execute() override {} + + private: + TestWorkerWithUserDefRecv(const Object& recv, const Function& cb) + : AsyncWorker(recv, cb) {} + TestWorkerWithUserDefRecv(const Object& recv, + const Function& cb, + const char* resource_name) + : AsyncWorker(recv, cb, resource_name) {} + TestWorkerWithUserDefRecv(const Object& recv, + const Function& cb, + const char* resource_name, + const Object& resource) + : AsyncWorker(recv, cb, resource_name, resource) {} +}; + +// Using default std::allocator impl, but assuming user can define their own +// allocate/deallocate methods +class CustomAllocWorker : public AsyncWorker { + using Allocator = std::allocator; + + public: + CustomAllocWorker(Function& cb) : AsyncWorker(cb){}; + static void DoWork(const CallbackInfo& info) { + Function cb = info[0].As(); + Allocator allocator; + CustomAllocWorker* newWorker = allocator.allocate(1); + std::allocator_traits::construct(allocator, newWorker, cb); + newWorker->Queue(); + } + + protected: + void Execute() override {} + void Destroy() override { + assert(this->_secretVal == 24); + Allocator allocator; + std::allocator_traits::destroy(allocator, this); + allocator.deallocate(this, 1); + } + + private: + int _secretVal = 24; +}; + +class TestWorker : public AsyncWorker { + public: + static void DoWork(const CallbackInfo& info) { + bool succeed = info[0].As(); + Object resource = info[1].As(); + Function cb = info[2].As(); + Value data = info[3]; + + TestWorker* worker = nullptr; + if (resource == info.Env().Null()) { + worker = new TestWorker(cb, "TestResource"); + } else { + worker = new TestWorker(cb, "TestResource", resource); + } + + worker->Receiver().Set("data", data); + worker->_succeed = succeed; + worker->Queue(); + } + + protected: + void Execute() override { + if (!_succeed) { + SetError("test error"); + } + } + + private: + TestWorker(Function cb, const char* resource_name, const Object& resource) + : AsyncWorker(cb, resource_name, resource) {} + TestWorker(Function cb, const char* resource_name) + : AsyncWorker(cb, resource_name) {} + bool _succeed{}; +}; + +class TestWorkerWithResult : public AsyncWorker { + public: + static void DoWork(const CallbackInfo& info) { + bool succeed = info[0].As(); + Object resource = info[1].As(); + Function cb = info[2].As(); + Value data = info[3]; + + TestWorkerWithResult* worker = + new TestWorkerWithResult(cb, "TestResource", resource); + worker->Receiver().Set("data", data); + worker->_succeed = succeed; + worker->Queue(); + } + + protected: + void Execute() override { + if (!_succeed) { + SetError("test error"); + } + } + + std::vector GetResult(Napi::Env env) override { + return {Boolean::New(env, _succeed), + String::New(env, _succeed ? "ok" : "error")}; + } + + private: + TestWorkerWithResult(Function cb, + const char* resource_name, + const Object& resource) + : AsyncWorker(cb, resource_name, resource) {} + bool _succeed{}; +}; + +class TestWorkerNoCallback : public AsyncWorker { + public: + static Value DoWork(const CallbackInfo& info) { + bool succeed = info[0].As(); + + TestWorkerNoCallback* worker = new TestWorkerNoCallback(info.Env()); + worker->_succeed = succeed; + worker->Queue(); + return worker->_deferred.Promise(); + } + + static Value DoWorkWithAsyncRes(const CallbackInfo& info) { + napi_env env = info.Env(); + bool succeed = info[0].As(); + Object resource = info[1].As(); + + TestWorkerNoCallback* worker = nullptr; + if (resource == info.Env().Null()) { + worker = new TestWorkerNoCallback(env, "TestResource"); + } else { + worker = new TestWorkerNoCallback(env, "TestResource", resource); + } + worker->_succeed = succeed; + worker->Queue(); + return worker->_deferred.Promise(); + } + + protected: + void Execute() override {} + virtual void OnOK() override { _deferred.Resolve(Env().Undefined()); } + virtual void OnError(const Napi::Error& /* e */) override { + _deferred.Reject(Env().Undefined()); + } + + private: + TestWorkerNoCallback(Napi::Env env) + : AsyncWorker(env), _deferred(Napi::Promise::Deferred::New(env)) {} + + TestWorkerNoCallback(napi_env env, const char* resource_name) + : AsyncWorker(env, resource_name), + _deferred(Napi::Promise::Deferred::New(env)) {} + + TestWorkerNoCallback(napi_env env, + const char* resource_name, + const Object& resource) + : AsyncWorker(env, resource_name, resource), + _deferred(Napi::Promise::Deferred::New(env)) {} + Promise::Deferred _deferred; + bool _succeed{}; +}; + +class EchoWorker : public AsyncWorker { + public: + EchoWorker(Function& cb, std::string& echo) : AsyncWorker(cb), echo(echo) {} + ~EchoWorker() {} + + void Execute() override { + // Simulate cpu heavy task + std::this_thread::sleep_for(std::chrono::milliseconds(30)); + } + + void OnOK() override { + HandleScope scope(Env()); + Callback().Call({Env().Null(), String::New(Env(), echo)}); + } + + private: + std::string echo; +}; + +class FailCancelWorker : public AsyncWorker { + private: + bool taskIsRunning = false; + std::mutex mu; + std::condition_variable taskStartingCv; + void NotifyJSThreadTaskHasStarted() { + { + std::lock_guard lk(mu); + taskIsRunning = true; + taskStartingCv.notify_one(); + } + } + + public: + FailCancelWorker(Function& cb) : AsyncWorker(cb) {} + ~FailCancelWorker() {} + + void WaitForWorkerTaskToStart() { + std::unique_lock lk(mu); + taskStartingCv.wait(lk, [this] { return taskIsRunning; }); + taskIsRunning = false; + } + + static void DoCancel(const CallbackInfo& info) { + Function cb = info[0].As(); + + FailCancelWorker* cancelWorker = new FailCancelWorker(cb); + cancelWorker->Queue(); + cancelWorker->WaitForWorkerTaskToStart(); + +#ifdef NAPI_CPP_EXCEPTIONS + try { + cancelWorker->Cancel(); + } catch (Napi::Error&) { + Napi::Error::New(info.Env(), "Unable to cancel async worker tasks") + .ThrowAsJavaScriptException(); + } +#else + cancelWorker->Cancel(); +#endif + } + + void Execute() override { + NotifyJSThreadTaskHasStarted(); + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + + void OnOK() override {} + + void OnError(const Error&) override {} +}; + +class CancelWorker : public AsyncWorker { + public: + CancelWorker(Function& cb) : AsyncWorker(cb) {} + ~CancelWorker() {} + + static void DoWork(const CallbackInfo& info) { + Function cb = info[0].As(); + std::string echo = info[1].As(); + int threadNum = info[2].As().Uint32Value(); + + for (int i = 0; i < threadNum; i++) { + AsyncWorker* worker = new EchoWorker(cb, echo); + worker->Queue(); + assert(worker->Env() == info.Env()); + } + + AsyncWorker* cancelWorker = new CancelWorker(cb); + cancelWorker->Queue(); + +#ifdef NAPI_CPP_EXCEPTIONS + try { + cancelWorker->Cancel(); + } catch (Napi::Error&) { + Napi::Error::New(info.Env(), "Unable to cancel async worker tasks") + .ThrowAsJavaScriptException(); + } +#else + cancelWorker->Cancel(); +#endif + } + + void Execute() override { + // Simulate cpu heavy task + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + + void OnOK() override { + Napi::Error::New(this->Env(), + "OnOk should not be invoked on successful cancellation") + .ThrowAsJavaScriptException(); + } + + void OnError(const Error&) override { + Napi::Error::New(this->Env(), + "OnError should not be invoked on successful cancellation") + .ThrowAsJavaScriptException(); + } +}; + +Object InitAsyncWorker(Env env) { + Object exports = Object::New(env); + exports["doWorkRecv"] = Function::New(env, TestWorkerWithUserDefRecv::DoWork); + exports["doWithRecvAsyncRes"] = + Function::New(env, TestWorkerWithUserDefRecv::DoWorkWithAsyncRes); + exports["doWork"] = Function::New(env, TestWorker::DoWork); + exports["doWorkAsyncResNoCallback"] = + Function::New(env, TestWorkerNoCallback::DoWorkWithAsyncRes); + exports["doWorkNoCallback"] = + Function::New(env, TestWorkerNoCallback::DoWork); + exports["doWorkWithResult"] = + Function::New(env, TestWorkerWithResult::DoWork); + exports["tryCancelQueuedWork"] = Function::New(env, CancelWorker::DoWork); + + exports["expectCancelToFail"] = + Function::New(env, FailCancelWorker::DoCancel); + exports["expectCustomAllocWorkerToDealloc"] = + Function::New(env, CustomAllocWorker::DoWork); + return exports; +} diff --git a/test/node-addon-api/test/async_worker.js b/test/node-addon-api/test/async_worker.js new file mode 100644 index 0000000..b13f20b --- /dev/null +++ b/test/node-addon-api/test/async_worker.js @@ -0,0 +1,265 @@ +'use strict'; +const assert = require('assert'); +const common = require('./common'); + +// we only check async hooks on 8.x an higher were +// they are closer to working properly +const nodeVersion = process.versions.node.split('.')[0]; +let asyncHooks; +function checkAsyncHooks () { + if (false) { // quickjs-napi: no async_hooks + if (asyncHooks === undefined) { + asyncHooks = require('async_hooks'); + } + return true; + } + return false; +} + +module.exports = common.runTest(test); + +function installAsyncHooksForTest () { + return new Promise((resolve, reject) => { + let id; + const events = []; + /** + * TODO(legendecas): investigate why resolving & disabling hooks in + * destroy callback causing crash with case 'callbackscope.js'. + */ + let destroyed = false; + const interval = setInterval(() => { + if (destroyed) { + hook.disable(); + clearInterval(interval); + resolve(events); + } + }, 10); + + const hook = asyncHooks.createHook({ + init (asyncId, type, triggerAsyncId, resource) { + if (id === undefined && type === 'TestResource') { + id = asyncId; + events.push({ eventName: 'init', type, triggerAsyncId, resource }); + } + }, + before (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'before' }); + } + }, + after (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'after' }); + } + }, + destroy (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'destroy' }); + destroyed = true; + } + } + }).enable(); + }); +} + +async function test (binding) { + const libUvThreadCount = Number(process.env.UV_THREADPOOL_SIZE || 4); + binding.asyncworker.tryCancelQueuedWork(() => {}, 'echoString', libUvThreadCount); + + let taskFailed = false; + try { + binding.asyncworker.expectCancelToFail(() => {}); + } catch (e) { + taskFailed = true; + } + + assert.equal(taskFailed, true, 'We expect task cancellation to fail'); + + if (!checkAsyncHooks()) { + binding.asyncworker.expectCustomAllocWorkerToDealloc(() => {}); + + await new Promise((resolve) => { + const obj = { data: 'test data' }; + binding.asyncworker.doWorkRecv(obj, function (e) { + assert.strictEqual(typeof e, 'undefined'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }); + }); + + await new Promise((resolve) => { + // quickjs-napi: {} instead of null, as in the async_hooks path + binding.asyncworker.doWork(true, {}, function (e) { + assert.strictEqual(typeof e, 'undefined'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }, 'test data'); + }); + + await new Promise((resolve) => { + binding.asyncworker.doWork(false, {}, function (e) { + assert.ok(e instanceof Error); + assert.strictEqual(e.message, 'test error'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }, 'test data'); + }); + + await new Promise((resolve) => { + binding.asyncworker.doWorkWithResult(true, {}, function (succeed, succeedString) { + assert(arguments.length === 2); + assert(succeed); + assert(succeedString === 'ok'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }, 'test data'); + }); + + return; + } + + { + const hooks = installAsyncHooksForTest(); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve) => { + const recvObj = { data: 'test data' }; + binding.asyncworker.doWithRecvAsyncRes(recvObj, function (e) { + assert.strictEqual(typeof e, 'undefined'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }, { foo: 'fooBar' }); + }); + + await hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'TestResource', + triggerAsyncId, + resource: { foo: 'fooBar' } + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + } + + { + const hooks = installAsyncHooksForTest(); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve) => { + const recvObj = { data: 'test data' }; + binding.asyncworker.doWithRecvAsyncRes(recvObj, function (e) { + assert.strictEqual(typeof e, 'undefined'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }, null); + }); + + await hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'TestResource', + triggerAsyncId, + resource: { } + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + } + + { + const hooks = installAsyncHooksForTest(); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve) => { + binding.asyncworker.doWork(true, { foo: 'foo' }, function (e) { + assert.strictEqual(typeof e, 'undefined'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }, 'test data'); + }); + + await hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'TestResource', + triggerAsyncId, + resource: { foo: 'foo' } + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + } + + { + const hooks = installAsyncHooksForTest(); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve) => { + binding.asyncworker.doWorkWithResult(true, { foo: 'foo' }, + function (succeed, succeedString) { + assert(arguments.length === 2); + assert(succeed); + assert(succeedString === 'ok'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }, 'test data'); + }); + + await hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'TestResource', + triggerAsyncId, + resource: { foo: 'foo' } + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + } + + { + const hooks = installAsyncHooksForTest(); + const triggerAsyncId = asyncHooks.executionAsyncId(); + await new Promise((resolve) => { + binding.asyncworker.doWork(false, { foo: 'foo' }, function (e) { + assert.ok(e instanceof Error); + assert.strictEqual(e.message, 'test error'); + assert.strictEqual(typeof this, 'object'); + assert.strictEqual(this.data, 'test data'); + resolve(); + }, 'test data'); + }); + + await hooks.then(actual => { + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'TestResource', + triggerAsyncId, + resource: { foo: 'foo' } + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + }).catch(common.mustNotCall()); + } +} diff --git a/test/node-addon-api/test/async_worker_nocallback.js b/test/node-addon-api/test/async_worker_nocallback.js new file mode 100644 index 0000000..2f848c4 --- /dev/null +++ b/test/node-addon-api/test/async_worker_nocallback.js @@ -0,0 +1,19 @@ +'use strict'; + +const common = require('./common'); + +module.exports = common.runTest(test); + +async function test (binding) { + await binding.asyncworker.doWorkAsyncResNoCallback(true, {}) + .then(common.mustCall()).catch(common.mustNotCall()); + + await binding.asyncworker.doWorkAsyncResNoCallback(false, {}) + .then(common.mustNotCall()).catch(common.mustCall()); + + await binding.asyncworker.doWorkNoCallback(false) + .then(common.mustNotCall()).catch(common.mustCall()); + + await binding.asyncworker.doWorkNoCallback(true) + .then(common.mustNotCall()).catch(common.mustCall()); +} diff --git a/test/node-addon-api/test/async_worker_persistent.cc b/test/node-addon-api/test/async_worker_persistent.cc new file mode 100644 index 0000000..90349ae --- /dev/null +++ b/test/node-addon-api/test/async_worker_persistent.cc @@ -0,0 +1,63 @@ +#include "napi.h" + +// A variant of TestWorker wherein destruction is suppressed. That is, instances +// are not destroyed during the `OnOK` callback. They must be explicitly +// destroyed. + +using namespace Napi; + +namespace { + +class PersistentTestWorker : public AsyncWorker { + public: + static PersistentTestWorker* current_worker; + static void DoWork(const CallbackInfo& info) { + bool succeed = info[0].As(); + Function cb = info[1].As(); + + PersistentTestWorker* worker = new PersistentTestWorker(cb, "TestResource"); + current_worker = worker; + + worker->SuppressDestruct(); + worker->_succeed = succeed; + worker->Queue(); + } + + static Value GetWorkerGone(const CallbackInfo& info) { + return Boolean::New(info.Env(), current_worker == nullptr); + } + + static void DeleteWorker(const CallbackInfo& info) { + (void)info; + delete current_worker; + } + + ~PersistentTestWorker() { current_worker = nullptr; } + + protected: + void Execute() override { + if (!_succeed) { + SetError("test error"); + } + } + + private: + PersistentTestWorker(Function cb, const char* resource_name) + : AsyncWorker(cb, resource_name) {} + + bool _succeed; +}; + +PersistentTestWorker* PersistentTestWorker::current_worker = nullptr; + +} // end of anonymous namespace + +Object InitPersistentAsyncWorker(Env env) { + Object exports = Object::New(env); + exports["doWork"] = Function::New(env, PersistentTestWorker::DoWork); + exports.DefineProperty(PropertyDescriptor::Accessor( + env, exports, "workerGone", PersistentTestWorker::GetWorkerGone)); + exports["deleteWorker"] = + Function::New(env, PersistentTestWorker::DeleteWorker); + return exports; +} diff --git a/test/node-addon-api/test/async_worker_persistent.js b/test/node-addon-api/test/async_worker_persistent.js new file mode 100644 index 0000000..d3ce11e --- /dev/null +++ b/test/node-addon-api/test/async_worker_persistent.js @@ -0,0 +1,24 @@ +'use strict'; + +const assert = require('assert'); + +function test (binding, succeed) { + return new Promise((resolve) => + // Can't pass an arrow function to doWork because that results in an + // undefined context inside its body when the function gets called. + binding.doWork(succeed, function (e) { + setImmediate(() => { + // If the work is supposed to fail, make sure there's an error. + assert.strictEqual(succeed || e.message === 'test error', true); + assert.strictEqual(binding.workerGone, false); + binding.deleteWorker(); + assert.strictEqual(binding.workerGone, true); + resolve(); + }); + })); +} + +module.exports = require('./common').runTest(async binding => { + await test(binding.persistentasyncworker, false); + await test(binding.persistentasyncworker, true); +}); diff --git a/test/node-addon-api/test/basic_types/array.cc b/test/node-addon-api/test/basic_types/array.cc new file mode 100644 index 0000000..6482c61 --- /dev/null +++ b/test/node-addon-api/test/basic_types/array.cc @@ -0,0 +1,40 @@ +#include "napi.h" + +using namespace Napi; + +Value CreateArray(const CallbackInfo& info) { + if (info.Length() > 0) { + size_t length = info[0].As().Uint32Value(); + return Array::New(info.Env(), length); + } else { + return Array::New(info.Env()); + } +} + +Value GetLength(const CallbackInfo& info) { + Array array = info[0].As(); + return Number::New(info.Env(), static_cast(array.Length())); +} + +Value GetElement(const CallbackInfo& info) { + Array array = info[0].As(); + size_t index = info[1].As().Uint32Value(); + return array[index]; +} + +void SetElement(const CallbackInfo& info) { + Array array = info[0].As(); + size_t index = info[1].As().Uint32Value(); + array[index] = info[2].As(); +} + +Object InitBasicTypesArray(Env env) { + Object exports = Object::New(env); + + exports["createArray"] = Function::New(env, CreateArray); + exports["getLength"] = Function::New(env, GetLength); + exports["get"] = Function::New(env, GetElement); + exports["set"] = Function::New(env, SetElement); + + return exports; +} diff --git a/test/node-addon-api/test/basic_types/array.js b/test/node-addon-api/test/basic_types/array.js new file mode 100644 index 0000000..a4bb69a --- /dev/null +++ b/test/node-addon-api/test/basic_types/array.js @@ -0,0 +1,34 @@ +'use strict'; +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + // create empty array + const array = binding.basic_types_array.createArray(); + assert.strictEqual(binding.basic_types_array.getLength(array), 0); + + // create array with length + const arrayWithLength = binding.basic_types_array.createArray(10); + assert.strictEqual(binding.basic_types_array.getLength(arrayWithLength), 10); + + // set function test + binding.basic_types_array.set(array, 0, 10); + binding.basic_types_array.set(array, 1, 'test'); + binding.basic_types_array.set(array, 2, 3.0); + + // check length after set data + assert.strictEqual(binding.basic_types_array.getLength(array), 3); + + // get function test + assert.strictEqual(binding.basic_types_array.get(array, 0), 10); + assert.strictEqual(binding.basic_types_array.get(array, 1), 'test'); + assert.strictEqual(binding.basic_types_array.get(array, 2), 3.0); + + // overwrite test + binding.basic_types_array.set(array, 0, 5); + assert.strictEqual(binding.basic_types_array.get(array, 0), 5); + + // out of index test + assert.strictEqual(binding.basic_types_array.get(array, 5), undefined); +} diff --git a/test/node-addon-api/test/basic_types/boolean.cc b/test/node-addon-api/test/basic_types/boolean.cc new file mode 100644 index 0000000..9e67eed --- /dev/null +++ b/test/node-addon-api/test/basic_types/boolean.cc @@ -0,0 +1,40 @@ +#include "napi.h" + +using namespace Napi; + +Value CreateBoolean(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].As().Value()); +} + +Value CreateEmptyBoolean(const CallbackInfo& info) { + Boolean* boolean = new Boolean(); + return Boolean::New(info.Env(), boolean->IsEmpty()); +} + +Value CreateBooleanFromExistingValue(const CallbackInfo& info) { + Boolean boolean(info.Env(), info[0].As()); + return Boolean::New(info.Env(), boolean.Value()); +} + +Value CreateBooleanFromPrimitive(const CallbackInfo& info) { + bool boolean = info[0].As(); + return Boolean::New(info.Env(), boolean); +} + +Value OperatorBool(const CallbackInfo& info) { + Boolean boolean(info.Env(), info[0].As()); + return Boolean::New(info.Env(), static_cast(boolean)); +} + +Object InitBasicTypesBoolean(Env env) { + Object exports = Object::New(env); + + exports["createBoolean"] = Function::New(env, CreateBoolean); + exports["createEmptyBoolean"] = Function::New(env, CreateEmptyBoolean); + exports["createBooleanFromExistingValue"] = + Function::New(env, CreateBooleanFromExistingValue); + exports["createBooleanFromPrimitive"] = + Function::New(env, CreateBooleanFromPrimitive); + exports["operatorBool"] = Function::New(env, OperatorBool); + return exports; +} diff --git a/test/node-addon-api/test/basic_types/boolean.js b/test/node-addon-api/test/basic_types/boolean.js new file mode 100644 index 0000000..61f005e --- /dev/null +++ b/test/node-addon-api/test/basic_types/boolean.js @@ -0,0 +1,34 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + const bool1 = binding.basic_types_boolean.createBoolean(true); + assert.strictEqual(bool1, true); + + const bool2 = binding.basic_types_boolean.createBoolean(false); + assert.strictEqual(bool2, false); + + const emptyBoolean = binding.basic_types_boolean.createEmptyBoolean(); + assert.strictEqual(emptyBoolean, true); + + const bool3 = binding.basic_types_boolean.createBooleanFromExistingValue(true); + assert.strictEqual(bool3, true); + + const bool4 = binding.basic_types_boolean.createBooleanFromExistingValue(false); + assert.strictEqual(bool4, false); + + const bool5 = binding.basic_types_boolean.createBooleanFromPrimitive(true); + assert.strictEqual(bool5, true); + + const bool6 = binding.basic_types_boolean.createBooleanFromPrimitive(false); + assert.strictEqual(bool6, false); + + const bool7 = binding.basic_types_boolean.operatorBool(true); + assert.strictEqual(bool7, true); + + const bool8 = binding.basic_types_boolean.operatorBool(false); + assert.strictEqual(bool8, false); +} diff --git a/test/node-addon-api/test/basic_types/number.cc b/test/node-addon-api/test/basic_types/number.cc new file mode 100644 index 0000000..ee5c815 --- /dev/null +++ b/test/node-addon-api/test/basic_types/number.cc @@ -0,0 +1,105 @@ +#include + +#include "napi.h" + +using namespace Napi; + +Value ToInt32(const CallbackInfo& info) { + return Number::New(info.Env(), info[0].As().Int32Value()); +} + +Value ToUint32(const CallbackInfo& info) { + return Number::New(info.Env(), info[0].As().Uint32Value()); +} + +Value ToInt64(const CallbackInfo& info) { + return Number::New(info.Env(), + static_cast(info[0].As().Int64Value())); +} + +Value ToFloat(const CallbackInfo& info) { + return Number::New(info.Env(), info[0].As().FloatValue()); +} + +Value ToDouble(const CallbackInfo& info) { + return Number::New(info.Env(), info[0].As().DoubleValue()); +} + +Value MinFloat(const CallbackInfo& info) { + return Number::New(info.Env(), FLT_MIN); +} + +Value MaxFloat(const CallbackInfo& info) { + return Number::New(info.Env(), FLT_MAX); +} + +Value MinDouble(const CallbackInfo& info) { + return Number::New(info.Env(), DBL_MIN); +} + +Value MaxDouble(const CallbackInfo& info) { + return Number::New(info.Env(), DBL_MAX); +} + +Value OperatorInt32(const CallbackInfo& info) { + Number number = info[0].As(); + return Boolean::New(info.Env(), + number.Int32Value() == static_cast(number)); +} + +Value OperatorUint32(const CallbackInfo& info) { + Number number = info[0].As(); + return Boolean::New(info.Env(), + number.Uint32Value() == static_cast(number)); +} + +Value OperatorInt64(const CallbackInfo& info) { + Number number = info[0].As(); + return Boolean::New(info.Env(), + number.Int64Value() == static_cast(number)); +} + +Value OperatorFloat(const CallbackInfo& info) { + Number number = info[0].As(); + return Boolean::New(info.Env(), + number.FloatValue() == static_cast(number)); +} + +Value OperatorDouble(const CallbackInfo& info) { + Number number = info[0].As(); + return Boolean::New(info.Env(), + number.DoubleValue() == static_cast(number)); +} + +Value CreateEmptyNumber(const CallbackInfo& info) { + Number number; + return Boolean::New(info.Env(), number.IsEmpty()); +} + +Value CreateNumberFromExistingValue(const CallbackInfo& info) { + return info[0].As(); +} + +Object InitBasicTypesNumber(Env env) { + Object exports = Object::New(env); + + exports["toInt32"] = Function::New(env, ToInt32); + exports["toUint32"] = Function::New(env, ToUint32); + exports["toInt64"] = Function::New(env, ToInt64); + exports["toFloat"] = Function::New(env, ToFloat); + exports["toDouble"] = Function::New(env, ToDouble); + exports["minFloat"] = Function::New(env, MinFloat); + exports["maxFloat"] = Function::New(env, MaxFloat); + exports["minDouble"] = Function::New(env, MinDouble); + exports["maxDouble"] = Function::New(env, MaxDouble); + exports["operatorInt32"] = Function::New(env, OperatorInt32); + exports["operatorUint32"] = Function::New(env, OperatorUint32); + exports["operatorInt64"] = Function::New(env, OperatorInt64); + exports["operatorFloat"] = Function::New(env, OperatorFloat); + exports["operatorDouble"] = Function::New(env, OperatorDouble); + exports["createEmptyNumber"] = Function::New(env, CreateEmptyNumber); + exports["createNumberFromExistingValue"] = + Function::New(env, CreateNumberFromExistingValue); + + return exports; +} diff --git a/test/node-addon-api/test/basic_types/number.js b/test/node-addon-api/test/basic_types/number.js new file mode 100644 index 0000000..41e5ebd --- /dev/null +++ b/test/node-addon-api/test/basic_types/number.js @@ -0,0 +1,115 @@ +/* eslint-disable no-lone-blocks */ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + const MIN_INT32 = -2147483648; + const MAX_INT32 = 2147483647; + const MIN_UINT32 = 0; + const MAX_UINT32 = 4294967295; + const MIN_INT64 = Number.MIN_SAFE_INTEGER; + const MAX_INT64 = Number.MAX_SAFE_INTEGER; + const MIN_FLOAT = binding.basic_types_number.minFloat(); + const MAX_FLOAT = binding.basic_types_number.maxFloat(); + const MIN_DOUBLE = binding.basic_types_number.minDouble(); + const MAX_DOUBLE = binding.basic_types_number.maxDouble(); + + function randomRangeTestForInteger (min, max, converter) { + for (let i = min; i < max; i += Math.floor(Math.random() * max / 100)) { + assert.strictEqual(i, converter(i)); + } + } + + // Test for 32bit signed integer [-2147483648, 2147483647] + { + // Range tests + randomRangeTestForInteger(MIN_INT32, MAX_INT32, binding.basic_types_number.toInt32); + assert.strictEqual(MIN_INT32, binding.basic_types_number.toInt32(MIN_INT32)); + assert.strictEqual(MAX_INT32, binding.basic_types_number.toInt32(MAX_INT32)); + + // Overflow tests + assert.notStrictEqual(MAX_INT32 + 1, binding.basic_types_number.toInt32(MAX_INT32 + 1)); + assert.notStrictEqual(MIN_INT32 - 1, binding.basic_types_number.toInt32(MIN_INT32 - 1)); + } + + // Test for 32bit unsigned integer [0, 4294967295] + { + // Range tests + randomRangeTestForInteger(MIN_UINT32, MAX_UINT32, binding.basic_types_number.toUint32); + assert.strictEqual(MIN_UINT32, binding.basic_types_number.toUint32(MIN_UINT32)); + assert.strictEqual(MAX_UINT32, binding.basic_types_number.toUint32(MAX_UINT32)); + + // Overflow tests + assert.notStrictEqual(MAX_UINT32 + 1, binding.basic_types_number.toUint32(MAX_UINT32 + 1)); + assert.notStrictEqual(MIN_UINT32 - 1, binding.basic_types_number.toUint32(MIN_UINT32 - 1)); + } + + // Test for 64bit signed integer + { + // Range tests + randomRangeTestForInteger(MIN_INT64, MAX_INT64, binding.basic_types_number.toInt64); + assert.strictEqual(MIN_INT64, binding.basic_types_number.toInt64(MIN_INT64)); + assert.strictEqual(MAX_INT64, binding.basic_types_number.toInt64(MAX_INT64)); + + // The int64 type can't be represented with full precision in JavaScript. + // So, we are not able to do overflow test here. + // Please see https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type. + } + + // Test for float type (might be single-precision 32bit IEEE 754 floating point number) + { + // Range test + assert.strictEqual(MIN_FLOAT, binding.basic_types_number.toFloat(MIN_FLOAT)); + assert.strictEqual(MAX_FLOAT, binding.basic_types_number.toFloat(MAX_FLOAT)); + + // Overflow test + assert.strictEqual(0, binding.basic_types_number.toFloat(MIN_FLOAT * MIN_FLOAT)); + assert.strictEqual(Infinity, binding.basic_types_number.toFloat(MAX_FLOAT * MAX_FLOAT)); + } + + // Test for double type (is double-precision 64 bit IEEE 754 floating point number) + { + assert.strictEqual(MIN_DOUBLE, binding.basic_types_number.toDouble(MIN_DOUBLE)); + assert.strictEqual(MAX_DOUBLE, binding.basic_types_number.toDouble(MAX_DOUBLE)); + + // Overflow test + assert.strictEqual(0, binding.basic_types_number.toDouble(MIN_DOUBLE * MIN_DOUBLE)); + assert.strictEqual(Infinity, binding.basic_types_number.toDouble(MAX_DOUBLE * MAX_DOUBLE)); + } + + // Test for operator overloading + { + assert.strictEqual(binding.basic_types_number.operatorInt32(MIN_INT32), true); + assert.strictEqual(binding.basic_types_number.operatorInt32(MAX_INT32), true); + assert.strictEqual(binding.basic_types_number.operatorUint32(MIN_UINT32), true); + assert.strictEqual(binding.basic_types_number.operatorUint32(MAX_UINT32), true); + assert.strictEqual(binding.basic_types_number.operatorInt64(MIN_INT64), true); + assert.strictEqual(binding.basic_types_number.operatorInt64(MAX_INT64), true); + assert.strictEqual(binding.basic_types_number.operatorFloat(MIN_FLOAT), true); + assert.strictEqual(binding.basic_types_number.operatorFloat(MAX_FLOAT), true); + assert.strictEqual(binding.basic_types_number.operatorFloat(MAX_DOUBLE), true); + assert.strictEqual(binding.basic_types_number.operatorDouble(MIN_DOUBLE), true); + assert.strictEqual(binding.basic_types_number.operatorDouble(MAX_DOUBLE), true); + } + + // Construction test + { + assert.strictEqual(binding.basic_types_number.createEmptyNumber(), true); + randomRangeTestForInteger(MIN_INT32, MAX_INT32, binding.basic_types_number.createNumberFromExistingValue); + assert.strictEqual(MIN_INT32, binding.basic_types_number.createNumberFromExistingValue(MIN_INT32)); + assert.strictEqual(MAX_INT32, binding.basic_types_number.createNumberFromExistingValue(MAX_INT32)); + randomRangeTestForInteger(MIN_UINT32, MAX_UINT32, binding.basic_types_number.createNumberFromExistingValue); + assert.strictEqual(MIN_UINT32, binding.basic_types_number.createNumberFromExistingValue(MIN_UINT32)); + assert.strictEqual(MAX_UINT32, binding.basic_types_number.createNumberFromExistingValue(MAX_UINT32)); + randomRangeTestForInteger(MIN_INT64, MAX_INT64, binding.basic_types_number.createNumberFromExistingValue); + assert.strictEqual(MIN_INT64, binding.basic_types_number.createNumberFromExistingValue(MIN_INT64)); + assert.strictEqual(MAX_INT64, binding.basic_types_number.createNumberFromExistingValue(MAX_INT64)); + assert.strictEqual(MIN_FLOAT, binding.basic_types_number.createNumberFromExistingValue(MIN_FLOAT)); + assert.strictEqual(MAX_FLOAT, binding.basic_types_number.createNumberFromExistingValue(MAX_FLOAT)); + assert.strictEqual(MIN_DOUBLE, binding.basic_types_number.createNumberFromExistingValue(MIN_DOUBLE)); + assert.strictEqual(MAX_DOUBLE, binding.basic_types_number.createNumberFromExistingValue(MAX_DOUBLE)); + } +} diff --git a/test/node-addon-api/test/basic_types/value.cc b/test/node-addon-api/test/basic_types/value.cc new file mode 100644 index 0000000..7ec3b7e --- /dev/null +++ b/test/node-addon-api/test/basic_types/value.cc @@ -0,0 +1,177 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +namespace { + +int testData = 1; + +// Helpers for testing non-Javascript values. +Value CreateExternal(const CallbackInfo& info) { + return External::New(info.Env(), &testData); +} + +} // end anonymous namespace + +static Value StrictlyEquals(const CallbackInfo& info) { + bool strictlyEquals = info[0].StrictEquals(info[1]); + return Boolean::New(info.Env(), strictlyEquals); +} + +// tests the '==' overload +static Value StrictEqualsOverload(const CallbackInfo& info) { + bool strictlyEquals = info[0] == info[1]; + return Boolean::New(info.Env(), strictlyEquals); +} + +// tests the '!=' overload +static Value StrictlyNotEqualsOverload(const CallbackInfo& info) { + bool strictlyEquals = info[0] != info[1]; + return Boolean::New(info.Env(), strictlyEquals); +} + +static Value ValueReturnsCorrectEnv(const CallbackInfo& info) { + Value testValue = CreateExternal(info); + return Boolean::New(info.Env(), testValue.Env() == info.Env()); +} + +static Value EmptyValueReturnNullPtrOnCast(const CallbackInfo& info) { + Value emptyValue; + bool isNullPtr = static_cast(emptyValue) == nullptr; + return Boolean::New(info.Env(), isNullPtr); +} + +static Value NonEmptyValueReturnValOnCast(const CallbackInfo& info) { + Value boolValue = Value::From(info.Env(), true); + return Boolean::New(info.Env(), static_cast(boolValue)); +} + +static Value CreateNonEmptyValue(const CallbackInfo& info) { + return Napi::Value(info.Env(), String::New(info.Env(), "non_empty_val")); +} + +static Value IsEmpty(const CallbackInfo& info) { + Value value; + return Boolean::New(info.Env(), value.IsEmpty()); +} + +static Value IsUndefined(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsUndefined()); +} + +static Value IsNull(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsNull()); +} + +static Value IsBoolean(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsBoolean()); +} + +static Value IsNumber(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsNumber()); +} + +static Value IsString(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsString()); +} + +static Value IsSymbol(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsSymbol()); +} + +static Value IsArray(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsArray()); +} + +static Value IsArrayBuffer(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsArrayBuffer()); +} + +static Value IsTypedArray(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsTypedArray()); +} + +static Value IsObject(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsObject()); +} + +static Value IsFunction(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsFunction()); +} + +static Value IsPromise(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsPromise()); +} + +static Value IsDataView(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsDataView()); +} + +static Value IsExternal(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsExternal()); +} + +static Value ToBoolean(const CallbackInfo& info) { + return MaybeUnwrap(info[0].ToBoolean()); +} + +static Value ToNumber(const CallbackInfo& info) { + return MaybeUnwrap(info[0].ToNumber()); +} + +static Value ToString(const CallbackInfo& info) { + return MaybeUnwrap(info[0].ToString()); +} + +static Value ToObject(const CallbackInfo& info) { + return MaybeUnwrap(info[0].ToObject()); +} + +static Value AccessProp(const CallbackInfo& info) { + Object obj = MaybeUnwrap(info[0].ToObject()); + return obj[info[1]].AsValue(); +} + +Object InitBasicTypesValue(Env env) { + Object exports = Object::New(env); + + exports["isEmpty"] = Function::New(env, IsEmpty); + exports["isUndefined"] = Function::New(env, IsUndefined); + exports["isNull"] = Function::New(env, IsNull); + exports["isBoolean"] = Function::New(env, IsBoolean); + exports["isNumber"] = Function::New(env, IsNumber); + exports["isString"] = Function::New(env, IsString); + exports["isSymbol"] = Function::New(env, IsSymbol); + exports["isArray"] = Function::New(env, IsArray); + exports["isArrayBuffer"] = Function::New(env, IsArrayBuffer); + exports["isTypedArray"] = Function::New(env, IsTypedArray); + exports["isObject"] = Function::New(env, IsObject); + exports["isFunction"] = Function::New(env, IsFunction); + exports["isPromise"] = Function::New(env, IsPromise); + exports["isDataView"] = Function::New(env, IsDataView); + exports["isExternal"] = Function::New(env, IsExternal); + exports["toBoolean"] = Function::New(env, ToBoolean); + exports["toNumber"] = Function::New(env, ToNumber); + exports["toString"] = Function::New(env, ToString); + exports["toObject"] = Function::New(env, ToObject); + exports["accessProp"] = Function::New(env, AccessProp); + + exports["strictlyEquals"] = Function::New(env, StrictlyEquals); + exports["strictlyEqualsOverload"] = Function::New(env, StrictEqualsOverload); + exports["strictlyNotEqualsOverload"] = + Function::New(env, StrictlyNotEqualsOverload); + + exports["assertValueReturnsCorrectEnv"] = + Function::New(env, ValueReturnsCorrectEnv); + + exports["assertEmptyValReturnNullPtrOnCast"] = + Function::New(env, EmptyValueReturnNullPtrOnCast); + exports["assertNonEmptyReturnValOnCast"] = + Function::New(env, NonEmptyValueReturnValOnCast); + + exports["createNonEmptyValue"] = Function::New(env, CreateNonEmptyValue); + exports["createExternal"] = Function::New(env, CreateExternal); + + return exports; +} diff --git a/test/node-addon-api/test/basic_types/value.js b/test/node-addon-api/test/basic_types/value.js new file mode 100644 index 0000000..adf73d3 --- /dev/null +++ b/test/node-addon-api/test/basic_types/value.js @@ -0,0 +1,173 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + const externalValue = binding.basic_types_value.createExternal(); + + function isObject (value) { + return (typeof value === 'object' && value !== externalValue) || + (typeof value === 'function'); + } + + function detailedTypeOf (value) { + const type = typeof value; + if (type !== 'object') { return type; } + + if (value === null) { return 'null'; } + + if (Array.isArray(value)) { return 'array'; } + + if (value === externalValue) { return 'external'; } + + if (!value.constructor) { return type; } + + if (value instanceof ArrayBuffer) { return 'arraybuffer'; } + + if (ArrayBuffer.isView(value)) { + if (value instanceof DataView) { + return 'dataview'; + } else { + return 'typedarray'; + } + } + + if (value instanceof Promise) { return 'promise'; } + + return 'object'; + } + + function typeCheckerTest (typeChecker, expectedType) { + const testValueList = [ + undefined, + null, + true, + 10, + 'string', + Symbol('symbol'), + [], + new ArrayBuffer(10), + new Int32Array(new ArrayBuffer(12)), + {}, + function () {}, + new Promise((resolve, reject) => {}), + new DataView(new ArrayBuffer(12)), + externalValue + ]; + + testValueList.forEach((testValue) => { + if (testValue !== null && expectedType === 'object') { + assert.strictEqual(typeChecker(testValue), isObject(testValue)); + } else { + assert.strictEqual(typeChecker(testValue), detailedTypeOf(testValue) === expectedType); + } + }); + } + + function typeConverterTest (typeConverter, expectedType) { + const testValueList = [ + true, + false, + 0, + 10, + 'string', + [], + new ArrayBuffer(10), + new Int32Array(new ArrayBuffer(12)), + {}, + function () {}, + new Promise((resolve, reject) => {}) + ]; + + testValueList.forEach((testValue) => { + const expected = expectedType(testValue); + const actual = typeConverter(testValue); + + if (isNaN(expected)) { + assert(isNaN(actual)); + } else { + assert.deepStrictEqual(typeConverter(testValue), expectedType(testValue)); + } + }); + } + + function assertValueStrictlyEqual (value) { + const newValue = value.createNonEmptyValue(); + assert(value.strictlyEquals(newValue, newValue)); + assert(value.strictlyEqualsOverload(newValue, newValue)); + } + + function assertValueStrictlyNonEqual (value) { + const valueA = value.createNonEmptyValue(); + const valueB = value.createExternal(); + assert(value.strictlyNotEqualsOverload(valueA, valueB)); + } + + function assertValueReturnsCorrectEnv (value) { + assert(value.assertValueReturnsCorrectEnv()); + } + + function assertEmptyValueNullPtrOnCast (value) { + assert(value.assertEmptyValReturnNullPtrOnCast()); + } + + function assertNonEmptyReturnValOnCast (value) { + assert(value.assertNonEmptyReturnValOnCast()); + } + + function accessPropTest (value) { + const testObject = { key: '123' }; + const testSymbol = Symbol('123'); + const testNumber = 123; + const destObj = { + testObject, + testSymbol, + [testNumber]: testNumber + }; + assert.strictEqual(value.accessProp(destObj, 'testObject'), testObject); + assert.strictEqual(value.accessProp(destObj, 'testSymbol'), testSymbol); + assert.strictEqual(value.accessProp(destObj, testNumber), testNumber); + assert.strictEqual(value.accessProp(destObj, 'invalidKey'), undefined); + } + + const value = binding.basic_types_value; + + assertValueStrictlyEqual(value); + assertValueStrictlyNonEqual(value); + assertValueReturnsCorrectEnv(value); + assertEmptyValueNullPtrOnCast(value); + assertNonEmptyReturnValOnCast(value); + + typeCheckerTest(value.isUndefined, 'undefined'); + typeCheckerTest(value.isNull, 'null'); + typeCheckerTest(value.isBoolean, 'boolean'); + typeCheckerTest(value.isNumber, 'number'); + typeCheckerTest(value.isString, 'string'); + typeCheckerTest(value.isSymbol, 'symbol'); + typeCheckerTest(value.isArray, 'array'); + typeCheckerTest(value.isArrayBuffer, 'arraybuffer'); + typeCheckerTest(value.isTypedArray, 'typedarray'); + typeCheckerTest(value.isObject, 'object'); + typeCheckerTest(value.isFunction, 'function'); + typeCheckerTest(value.isPromise, 'promise'); + typeCheckerTest(value.isDataView, 'dataview'); + typeCheckerTest(value.isExternal, 'external'); + + typeConverterTest(value.toBoolean, Boolean); + assert.strictEqual(value.toBoolean(undefined), false); + assert.strictEqual(value.toBoolean(null), false); + + typeConverterTest(value.toNumber, Number); + assert(isNaN(value.toNumber(undefined))); + assert.strictEqual(value.toNumber(null), 0); + + typeConverterTest(value.toString, String); + assert.strictEqual(value.toString(undefined), 'undefined'); + assert.strictEqual(value.toString(null), 'null'); + + typeConverterTest(value.toObject, Object); + + accessPropTest(value); +} diff --git a/test/node-addon-api/test/bigint.cc b/test/node-addon-api/test/bigint.cc new file mode 100644 index 0000000..4faccdd --- /dev/null +++ b/test/node-addon-api/test/bigint.cc @@ -0,0 +1,91 @@ +#if (NAPI_VERSION > 5) + +#include "napi.h" + +#include "test_helper.h" + +using namespace Napi; + +namespace { + +Value IsLossless(const CallbackInfo& info) { + Env env = info.Env(); + + BigInt big = info[0].As(); + bool is_signed = MaybeUnwrap(info[1].ToBoolean()).Value(); + + bool lossless; + if (is_signed) { + big.Int64Value(&lossless); + } else { + big.Uint64Value(&lossless); + } + + return Boolean::New(env, lossless); +} + +Value IsBigInt(const CallbackInfo& info) { + Env env = info.Env(); + + BigInt big = info[0].As(); + + return Boolean::New(env, big.IsBigInt()); +} + +Value TestInt64(const CallbackInfo& info) { + bool lossless; + int64_t input = info[0].As().Int64Value(&lossless); + + return BigInt::New(info.Env(), input); +} + +Value TestUint64(const CallbackInfo& info) { + bool lossless; + uint64_t input = info[0].As().Uint64Value(&lossless); + + return BigInt::New(info.Env(), input); +} + +Value TestWords(const CallbackInfo& info) { + BigInt big = info[0].As(); + + size_t expected_word_count = big.WordCount(); + + int sign_bit; + size_t word_count = 10; + uint64_t words[10] = {0}; + + big.ToWords(&sign_bit, &word_count, words); + + if (word_count != expected_word_count) { + Error::New(info.Env(), "word count did not match") + .ThrowAsJavaScriptException(); + return BigInt(); + } + + return BigInt::New(info.Env(), sign_bit, word_count, words); +} + +Value TestTooBigBigInt(const CallbackInfo& info) { + int sign_bit = 0; + size_t word_count = SIZE_MAX; + uint64_t words[10] = {0}; + + return BigInt::New(info.Env(), sign_bit, word_count, words); +} + +} // anonymous namespace + +Object InitBigInt(Env env) { + Object exports = Object::New(env); + exports["IsLossless"] = Function::New(env, IsLossless); + exports["IsBigInt"] = Function::New(env, IsBigInt); + exports["TestInt64"] = Function::New(env, TestInt64); + exports["TestUint64"] = Function::New(env, TestUint64); + exports["TestWords"] = Function::New(env, TestWords); + exports["TestTooBigBigInt"] = Function::New(env, TestTooBigBigInt); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/bigint.js b/test/node-addon-api/test/bigint.js new file mode 100644 index 0000000..c30e525 --- /dev/null +++ b/test/node-addon-api/test/bigint.js @@ -0,0 +1,53 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + const { + TestInt64, + TestUint64, + TestWords, + IsLossless, + IsBigInt, + TestTooBigBigInt + } = binding.bigint; + + [ + 0n, + -0n, + 1n, + -1n, + 100n, + 2121n, + -1233n, + 986583n, + -976675n, + 98765432213456789876546896323445679887645323232436587988766545658n, + -4350987086545760976737453646576078997096876957864353245245769809n + ].forEach((num) => { + if (num > -(2n ** 63n) && num < 2n ** 63n) { + assert.strictEqual(TestInt64(num), num); + assert.strictEqual(IsLossless(num, true), true); + } else { + assert.strictEqual(IsLossless(num, true), false); + } + + if (num >= 0 && num < 2n ** 64n) { + assert.strictEqual(TestUint64(num), num); + assert.strictEqual(IsLossless(num, false), true); + } else { + assert.strictEqual(IsLossless(num, false), false); + } + + assert.strictEqual(IsBigInt(num), true); + + assert.strictEqual(num, TestWords(num)); + }); + + assert.throws(TestTooBigBigInt, { + name: /^(RangeError|Error)$/, + message: /^(Maximum BigInt size exceeded|Invalid argument)$/ + }); +} diff --git a/test/node-addon-api/test/binding-swallowexcept.cc b/test/node-addon-api/test/binding-swallowexcept.cc new file mode 100644 index 0000000..febc7db --- /dev/null +++ b/test/node-addon-api/test/binding-swallowexcept.cc @@ -0,0 +1,12 @@ +#include "napi.h" + +using namespace Napi; + +Object InitError(Env env); + +Object Init(Env env, Object exports) { + exports.Set("error", InitError(env)); + return exports; +} + +NODE_API_MODULE(addon, Init) diff --git a/test/node-addon-api/test/binding.cc b/test/node-addon-api/test/binding.cc new file mode 100644 index 0000000..fa651cc --- /dev/null +++ b/test/node-addon-api/test/binding.cc @@ -0,0 +1,208 @@ +#include "napi.h" + +using namespace Napi; + +#if (NAPI_VERSION > 5) +Object InitAddon(Env env); +Object InitAddonData(Env env); +#endif +Object InitArrayBuffer(Env env); +Object InitAsyncContext(Env env); +#if (NAPI_VERSION > 3) +Object InitAsyncProgressQueueWorker(Env env); +Object InitAsyncProgressWorker(Env env); +#endif +Object InitAsyncWorker(Env env); +Object InitPersistentAsyncWorker(Env env); +Object InitBasicTypesArray(Env env); +Object InitBasicTypesBoolean(Env env); +Object InitBasicTypesNumber(Env env); +Object InitBasicTypesValue(Env env); +#if (NAPI_VERSION > 5) +Object InitBigInt(Env env); +#endif +Object InitBuffer(Env env); +Object InitBufferNoExternal(Env env); +#if (NAPI_VERSION > 2) +Object InitCallbackScope(Env env); +#endif +#if (NAPI_VERSION > 4) +Object InitDate(Env env); +#endif +Object InitCallbackInfo(Env env); +Object InitDataView(Env env); +Object InitDataViewReadWrite(Env env); +Object InitEnvCleanup(Env env); +Object InitErrorHandlingPrim(Env env); +Object InitError(Env env); +Object InitExternal(Env env); +Object InitFunction(Env env); +Object InitFunctionReference(Env env); +Object InitHandleScope(Env env); +Object InitMovableCallbacks(Env env); +Object InitMemoryManagement(Env env); +Object InitName(Env env); +Object InitObject(Env env); +#ifndef NODE_ADDON_API_DISABLE_DEPRECATED +Object InitObjectDeprecated(Env env); +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED +Object InitPromise(Env env); +Object InitRunScript(Env env); +#if (NAPI_VERSION > 3) +Object InitThreadSafeFunctionCtx(Env env); +Object InitThreadSafeFunctionException(Env env); +Object InitThreadSafeFunctionExistingTsfn(Env env); +Object InitThreadSafeFunctionPtr(Env env); +Object InitThreadSafeFunctionSum(Env env); +Object InitThreadSafeFunctionUnref(Env env); +Object InitThreadSafeFunction(Env env); +Object InitTypedThreadSafeFunctionCtx(Env env); +Object InitTypedThreadSafeFunctionException(Env env); +Object InitTypedThreadSafeFunctionExistingTsfn(Env env); +Object InitTypedThreadSafeFunctionPtr(Env env); +Object InitTypedThreadSafeFunctionSum(Env env); +Object InitTypedThreadSafeFunctionUnref(Env env); +Object InitTypedThreadSafeFunction(Env env); +#endif +Object InitSharedArrayBuffer(Env env); +Object InitSymbol(Env env); +Object InitTypedArray(Env env); +Object InitGlobalObject(Env env); +Object InitObjectWrap(Env env); +Object InitObjectWrapConstructorException(Env env); +Object InitObjectWrapFunction(Env env); +Object InitObjectWrapRemoveWrap(Env env); +Object InitObjectWrapMultipleInheritance(Env env); +Object InitObjectReference(Env env); +Object InitReference(Env env); +Object InitVersionManagement(Env env); +Object InitThunkingManual(Env env); +#if (NAPI_VERSION > 7) +Object InitObjectFreezeSeal(Env env); +Object InitTypeTaggable(Env env); +#endif +#if (NAPI_VERSION > 8) +Object InitEnvMiscellaneous(Env env); +#endif +#if defined(NODE_ADDON_API_ENABLE_MAYBE) +Object InitMaybeCheck(Env env); +#endif +Object InitFinalizerOrder(Env env); + +Object Init(Env env, Object exports) { +#if (NAPI_VERSION > 5) + exports.Set("addon", InitAddon(env)); + exports.Set("addon_data", InitAddonData(env)); +#endif + exports.Set("arraybuffer", InitArrayBuffer(env)); + exports.Set("asynccontext", InitAsyncContext(env)); +#if (NAPI_VERSION > 3) + exports.Set("asyncprogressqueueworker", InitAsyncProgressQueueWorker(env)); + exports.Set("asyncprogressworker", InitAsyncProgressWorker(env)); +#endif + exports.Set("globalObject", InitGlobalObject(env)); + exports.Set("asyncworker", InitAsyncWorker(env)); + exports.Set("persistentasyncworker", InitPersistentAsyncWorker(env)); + exports.Set("basic_types_array", InitBasicTypesArray(env)); + exports.Set("basic_types_boolean", InitBasicTypesBoolean(env)); + exports.Set("basic_types_number", InitBasicTypesNumber(env)); + exports.Set("basic_types_value", InitBasicTypesValue(env)); +#if (NAPI_VERSION > 5) + exports.Set("bigint", InitBigInt(env)); +#endif +#if (NAPI_VERSION > 4) + exports.Set("date", InitDate(env)); +#endif + exports.Set("buffer", InitBuffer(env)); + exports.Set("bufferNoExternal", InitBufferNoExternal(env)); +#if (NAPI_VERSION > 2) + exports.Set("callbackscope", InitCallbackScope(env)); +#endif + exports.Set("callbackInfo", InitCallbackInfo(env)); + exports.Set("dataview", InitDataView(env)); + exports.Set("dataview_read_write", InitDataView(env)); + exports.Set("dataview_read_write", InitDataViewReadWrite(env)); +#if (NAPI_VERSION > 2) + exports.Set("env_cleanup", InitEnvCleanup(env)); +#endif + exports.Set("error", InitError(env)); + exports.Set("errorHandlingPrim", InitErrorHandlingPrim(env)); + exports.Set("external", InitExternal(env)); + exports.Set("function", InitFunction(env)); + exports.Set("functionreference", InitFunctionReference(env)); + exports.Set("name", InitName(env)); + exports.Set("handlescope", InitHandleScope(env)); + exports.Set("movable_callbacks", InitMovableCallbacks(env)); + exports.Set("memory_management", InitMemoryManagement(env)); + exports.Set("object", InitObject(env)); +#ifndef NODE_ADDON_API_DISABLE_DEPRECATED + exports.Set("object_deprecated", InitObjectDeprecated(env)); +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED + exports.Set("promise", InitPromise(env)); + exports.Set("run_script", InitRunScript(env)); + exports.Set("symbol", InitSymbol(env)); + exports.Set("sharedarraybuffer", InitSharedArrayBuffer(env)); +#if (NAPI_VERSION > 3) + exports.Set("threadsafe_function_ctx", InitThreadSafeFunctionCtx(env)); + exports.Set("threadsafe_function_exception", + InitThreadSafeFunctionException(env)); + exports.Set("threadsafe_function_existing_tsfn", + InitThreadSafeFunctionExistingTsfn(env)); + exports.Set("threadsafe_function_ptr", InitThreadSafeFunctionPtr(env)); + exports.Set("threadsafe_function_sum", InitThreadSafeFunctionSum(env)); + exports.Set("threadsafe_function_unref", InitThreadSafeFunctionUnref(env)); + exports.Set("threadsafe_function", InitThreadSafeFunction(env)); + exports.Set("typed_threadsafe_function_ctx", + InitTypedThreadSafeFunctionCtx(env)); + exports.Set("typed_threadsafe_function_exception", + InitTypedThreadSafeFunctionException(env)); + exports.Set("typed_threadsafe_function_existing_tsfn", + InitTypedThreadSafeFunctionExistingTsfn(env)); + exports.Set("typed_threadsafe_function_ptr", + InitTypedThreadSafeFunctionPtr(env)); + exports.Set("typed_threadsafe_function_sum", + InitTypedThreadSafeFunctionSum(env)); + exports.Set("typed_threadsafe_function_unref", + InitTypedThreadSafeFunctionUnref(env)); + exports.Set("typed_threadsafe_function", InitTypedThreadSafeFunction(env)); +#endif + exports.Set("typedarray", InitTypedArray(env)); + exports.Set("objectwrap", InitObjectWrap(env)); + exports.Set("objectwrapConstructorException", + InitObjectWrapConstructorException(env)); + exports.Set("objectwrap_function", InitObjectWrapFunction(env)); + exports.Set("objectwrap_removewrap", InitObjectWrapRemoveWrap(env)); + exports.Set("objectwrap_multiple_inheritance", + InitObjectWrapMultipleInheritance(env)); + exports.Set("objectreference", InitObjectReference(env)); + exports.Set("reference", InitReference(env)); + exports.Set("version_management", InitVersionManagement(env)); + exports.Set("thunking_manual", InitThunkingManual(env)); +#if (NAPI_VERSION > 7) + exports.Set("object_freeze_seal", InitObjectFreezeSeal(env)); + exports.Set("type_taggable", InitTypeTaggable(env)); +#endif +#if (NAPI_VERSION > 8) + exports.Set("env_misc", InitEnvMiscellaneous(env)); +#endif + +#if defined(NODE_ADDON_API_ENABLE_MAYBE) + exports.Set("maybe_check", InitMaybeCheck(env)); +#endif + + exports.Set("finalizer_order", InitFinalizerOrder(env)); + + exports.Set( + "isExperimental", + Napi::Boolean::New(env, NAPI_VERSION == NAPI_VERSION_EXPERIMENTAL)); + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + exports.Set("hasSharedArrayBuffer", Napi::Boolean::New(env, true)); +#else + exports.Set("hasSharedArrayBuffer", Napi::Boolean::New(env, false)); +#endif + + return exports; +} + +NODE_API_MODULE(addon, Init) diff --git a/test/node-addon-api/test/binding.gyp b/test/node-addon-api/test/binding.gyp new file mode 100644 index 0000000..9ff334b --- /dev/null +++ b/test/node-addon-api/test/binding.gyp @@ -0,0 +1,161 @@ +{ + 'target_defaults': { + 'includes': ['../common.gypi'], + 'include_dirs': ['./common'], + 'variables': { + 'build_sources': [ + 'addon.cc', + 'addon_data.cc', + 'array_buffer.cc', + 'async_context.cc', + 'async_progress_queue_worker.cc', + 'async_progress_worker.cc', + 'async_worker.cc', + 'async_worker_persistent.cc', + 'basic_types/array.cc', + 'basic_types/boolean.cc', + 'basic_types/number.cc', + 'basic_types/value.cc', + 'bigint.cc', + 'callbackInfo.cc', + 'date.cc', + 'binding.cc', + 'buffer_no_external.cc', + 'buffer.cc', + 'callbackscope.cc', + 'dataview/dataview.cc', + 'dataview/dataview_read_write.cc', + 'env_cleanup.cc', + 'env_misc.cc', + 'error.cc', + 'error_handling_for_primitives.cc', + 'external.cc', + 'finalizer_order.cc', + 'function.cc', + 'function_reference.cc', + 'handlescope.cc', + 'maybe/check.cc', + 'movable_callbacks.cc', + 'memory_management.cc', + 'name.cc', + 'globalObject/global_object_delete_property.cc', + 'globalObject/global_object_has_own_property.cc', + 'globalObject/global_object_set_property.cc', + 'globalObject/global_object_get_property.cc', + 'globalObject/global_object.cc', + 'object/delete_property.cc', + 'object/finalizer.cc', + 'object/get_property.cc', + 'object/has_own_property.cc', + 'object/has_property.cc', + 'object/object.cc', + 'object/object_freeze_seal.cc', + 'object/set_property.cc', + 'object/subscript_operator.cc', + 'promise.cc', + 'run_script.cc', + 'shared_array_buffer.cc', + 'symbol.cc', + 'threadsafe_function/threadsafe_function_ctx.cc', + 'threadsafe_function/threadsafe_function_exception.cc', + 'threadsafe_function/threadsafe_function_existing_tsfn.cc', + 'threadsafe_function/threadsafe_function_ptr.cc', + 'threadsafe_function/threadsafe_function_sum.cc', + 'threadsafe_function/threadsafe_function_unref.cc', + 'threadsafe_function/threadsafe_function.cc', + 'type_taggable.cc', + 'typed_threadsafe_function/typed_threadsafe_function_ctx.cc', + 'typed_threadsafe_function/typed_threadsafe_function_exception.cc', + 'typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.cc', + 'typed_threadsafe_function/typed_threadsafe_function_ptr.cc', + 'typed_threadsafe_function/typed_threadsafe_function_sum.cc', + 'typed_threadsafe_function/typed_threadsafe_function_unref.cc', + 'typed_threadsafe_function/typed_threadsafe_function.cc', + 'typedarray.cc', + 'objectwrap.cc', + 'objectwrap_constructor_exception.cc', + 'objectwrap_function.cc', + 'objectwrap_removewrap.cc', + 'objectwrap_multiple_inheritance.cc', + 'object_reference.cc', + 'reference.cc', + 'version_management.cc', + 'thunking_manual.cc', + ], + 'build_sources_swallowexcept': [ + 'binding-swallowexcept.cc', + 'error.cc', + ], + 'build_sources_except_all': [ + 'except_all.cc', + ], + 'build_sources_type_check': [ + 'value_type_cast.cc' + ], + 'want_coverage': '@(build_sources)'], + 'defines': ['NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS'] + }, + { + 'target_name': 'binding_except_all', + 'dependencies': ['../node_addon_api.gyp:node_addon_api_except_all'], + 'sources': [ '>@(build_sources_except_all)'] + }, + { + 'target_name': 'binding_noexcept', + 'dependencies': ['../node_addon_api.gyp:node_addon_api'], + 'sources': ['>@(build_sources)'] + }, + { + 'target_name': 'binding_noexcept_maybe', + 'dependencies': ['../node_addon_api.gyp:node_addon_api_maybe'], + 'sources': ['>@(build_sources)'], + }, + { + 'target_name': 'binding_swallowexcept', + 'dependencies': ['../node_addon_api.gyp:node_addon_api_except'], + 'sources': [ '>@(build_sources_swallowexcept)'], + 'defines': ['NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS'] + }, + { + 'target_name': 'binding_swallowexcept_noexcept', + 'dependencies': ['../node_addon_api.gyp:node_addon_api'], + 'sources': ['>@(build_sources_swallowexcept)'], + 'defines': ['NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS'] + }, + { + 'target_name': 'binding_type_check', + 'dependencies': ['../node_addon_api.gyp:node_addon_api'], + 'sources': ['>@(build_sources_type_check)'], + 'defines': ['NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS'] + }, + { + 'target_name': 'binding_custom_namespace', + 'dependencies': ['../node_addon_api.gyp:node_addon_api'], + 'sources': ['>@(build_sources)'], + 'defines': ['NAPI_CPP_CUSTOM_NAMESPACE=cstm'] + }, + ], +} diff --git a/test/node-addon-api/test/buffer.cc b/test/node-addon-api/test/buffer.cc new file mode 100644 index 0000000..c10300d --- /dev/null +++ b/test/node-addon-api/test/buffer.cc @@ -0,0 +1,185 @@ +#include "buffer.h" +#include "napi.h" + +using namespace Napi; + +namespace test_buffer { +uint16_t testData[testLength]; +int finalizeCount = 0; +} // namespace test_buffer + +using namespace test_buffer; + +namespace { +Value CreateBuffer(const CallbackInfo& info) { + Buffer buffer = Buffer::New(info.Env(), testLength); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + InitData(buffer.Data(), testLength); + return buffer; +} + +Value CreateExternalBuffer(const CallbackInfo& info) { + finalizeCount = 0; + + Buffer buffer = + Buffer::New(info.Env(), testData, testLength); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + if (buffer.Data() != testData) { + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); + return Value(); + } + + InitData(testData, testLength); + return buffer; +} + +Value CreateExternalBufferWithFinalize(const CallbackInfo& info) { + finalizeCount = 0; + + uint16_t* data = new uint16_t[testLength]; + + Buffer buffer = Buffer::New( + info.Env(), data, testLength, [](Env /*env*/, uint16_t* finalizeData) { + delete[] finalizeData; + finalizeCount++; + }); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + if (buffer.Data() != data) { + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); + return Value(); + } + + InitData(data, testLength); + return buffer; +} + +Value CreateExternalBufferWithFinalizeHint(const CallbackInfo& info) { + finalizeCount = 0; + + uint16_t* data = new uint16_t[testLength]; + + char* hint = nullptr; + Buffer buffer = Buffer::New( + info.Env(), + data, + testLength, + [](Env /*env*/, uint16_t* finalizeData, char* /*finalizeHint*/) { + delete[] finalizeData; + finalizeCount++; + }, + hint); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + if (buffer.Data() != data) { + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); + return Value(); + } + + InitData(data, testLength); + return buffer; +} + +Value CreateBufferCopy(const CallbackInfo& info) { + InitData(testData, testLength); + + Buffer buffer = + Buffer::Copy(info.Env(), testData, testLength); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + if (buffer.Data() == testData) { + Error::New(info.Env(), "Copy should have different memory.") + .ThrowAsJavaScriptException(); + return Value(); + } + + if (!VerifyData(buffer.Data(), buffer.Length())) { + Error::New(info.Env(), "Copy data is incorrect.") + .ThrowAsJavaScriptException(); + return Value(); + } + + return buffer; +} + +#include "buffer_new_or_copy-inl.h" + +void CheckBuffer(const CallbackInfo& info) { + if (!info[0].IsBuffer()) { + Error::New(info.Env(), "A buffer was expected.") + .ThrowAsJavaScriptException(); + return; + } + + Buffer buffer = info[0].As>(); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return; + } + + if (!VerifyData(buffer.Data(), testLength)) { + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); + return; + } +} + +Value GetFinalizeCount(const CallbackInfo& info) { + return Number::New(info.Env(), finalizeCount); +} + +} // end anonymous namespace + +Object InitBuffer(Env env) { + Object exports = Object::New(env); + + exports["createBuffer"] = Function::New(env, CreateBuffer); + exports["createExternalBuffer"] = Function::New(env, CreateExternalBuffer); + exports["createExternalBufferWithFinalize"] = + Function::New(env, CreateExternalBufferWithFinalize); + exports["createExternalBufferWithFinalizeHint"] = + Function::New(env, CreateExternalBufferWithFinalizeHint); + exports["createOrCopyExternalBuffer"] = + Function::New(env, CreateOrCopyExternalBuffer); + exports["createOrCopyExternalBufferWithFinalize"] = + Function::New(env, CreateOrCopyExternalBufferWithFinalize); + exports["createOrCopyExternalBufferWithFinalizeHint"] = + Function::New(env, CreateOrCopyExternalBufferWithFinalizeHint); + exports["createBufferCopy"] = Function::New(env, CreateBufferCopy); + exports["checkBuffer"] = Function::New(env, CheckBuffer); + exports["getFinalizeCount"] = Function::New(env, GetFinalizeCount); + + return exports; +} diff --git a/test/node-addon-api/test/buffer.h b/test/node-addon-api/test/buffer.h new file mode 100644 index 0000000..ed2a717 --- /dev/null +++ b/test/node-addon-api/test/buffer.h @@ -0,0 +1,26 @@ +#include +#include + +namespace test_buffer { + +const size_t testLength = 4; +extern uint16_t testData[testLength]; +extern int finalizeCount; + +template +void InitData(T* data, size_t length) { + for (size_t i = 0; i < length; i++) { + data[i] = static_cast(i); + } +} + +template +bool VerifyData(T* data, size_t length) { + for (size_t i = 0; i < length; i++) { + if (data[i] != static_cast(i)) { + return false; + } + } + return true; +} +} // namespace test_buffer diff --git a/test/node-addon-api/test/buffer.js b/test/node-addon-api/test/buffer.js new file mode 100644 index 0000000..3f49201 --- /dev/null +++ b/test/node-addon-api/test/buffer.js @@ -0,0 +1,150 @@ +'use strict'; + +const assert = require('assert'); +const testUtil = require('./testUtil'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + return testUtil.runGCTests([ + 'Internal Buffer', + () => { + const test = binding.buffer.createBuffer(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + + const test2 = Buffer.alloc(test.length); + test.copy(test2); + binding.buffer.checkBuffer(test2); + }, + + 'Buffer copy', + () => { + const test = binding.buffer.createBufferCopy(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + }, + + 'External Buffer', + () => { + const test = binding.buffer.createExternalBuffer(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + + 'External Buffer with finalizer', + () => { + const test = binding.buffer.createExternalBufferWithFinalize(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + }, + () => { + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + + 'External Buffer with finalizer hint', + () => { + const test = binding.buffer.createExternalBufferWithFinalizeHint(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + }, + () => { + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer', + () => { + const test = binding.buffer.createOrCopyExternalBuffer(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer with finalizer', + () => { + const test = binding.buffer.createOrCopyExternalBufferWithFinalize(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + }, + () => { + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer with finalizer hint', + () => { + const test = binding.buffer.createOrCopyExternalBufferWithFinalizeHint(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + }, + () => { + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer when NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED defined', + () => { + const test = binding.bufferNoExternal.createOrCopyExternalBuffer(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer with finalizer when NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED defined', + () => { + const test = binding.bufferNoExternal.createOrCopyExternalBufferWithFinalize(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + // finalizer should have been called when the buffer was created. + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + }, + () => { + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + + 'Create or Copy External Buffer with finalizer hint when NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED defined', + () => { + const test = binding.bufferNoExternal.createOrCopyExternalBufferWithFinalizeHint(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + // finalizer should have been called when the buffer was created. + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + }, + () => { + global.gc(); + }, + () => { + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + } + ]); +} diff --git a/test/node-addon-api/test/buffer_new_or_copy-inl.h b/test/node-addon-api/test/buffer_new_or_copy-inl.h new file mode 100644 index 0000000..4d68fbc --- /dev/null +++ b/test/node-addon-api/test/buffer_new_or_copy-inl.h @@ -0,0 +1,68 @@ +// Same tests on when NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED is defined or not +// defined. + +Value CreateOrCopyExternalBuffer(const CallbackInfo& info) { + finalizeCount = 0; + + InitData(testData, testLength); + Buffer buffer = + Buffer::NewOrCopy(info.Env(), testData, testLength); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + VerifyData(buffer.Data(), testLength); + return buffer; +} + +Value CreateOrCopyExternalBufferWithFinalize(const CallbackInfo& info) { + finalizeCount = 0; + + uint16_t* data = new uint16_t[testLength]; + InitData(data, testLength); + + Buffer buffer = Buffer::NewOrCopy( + info.Env(), data, testLength, [](Env /*env*/, uint16_t* finalizeData) { + delete[] finalizeData; + finalizeCount++; + }); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + VerifyData(buffer.Data(), testLength); + return buffer; +} + +Value CreateOrCopyExternalBufferWithFinalizeHint(const CallbackInfo& info) { + finalizeCount = 0; + + uint16_t* data = new uint16_t[testLength]; + InitData(data, testLength); + + char* hint = nullptr; + Buffer buffer = Buffer::NewOrCopy( + info.Env(), + data, + testLength, + [](Env /*env*/, uint16_t* finalizeData, char* /*finalizeHint*/) { + delete[] finalizeData; + finalizeCount++; + }, + hint); + + if (buffer.Length() != testLength) { + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); + return Value(); + } + + VerifyData(buffer.Data(), testLength); + return buffer; +} diff --git a/test/node-addon-api/test/buffer_no_external.cc b/test/node-addon-api/test/buffer_no_external.cc new file mode 100644 index 0000000..11920bf --- /dev/null +++ b/test/node-addon-api/test/buffer_no_external.cc @@ -0,0 +1,24 @@ +#define NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +// Should compile without errors +#include "buffer.h" +#include "napi.h" + +using namespace Napi; +using namespace test_buffer; + +namespace { +#include "buffer_new_or_copy-inl.h" +} + +Object InitBufferNoExternal(Env env) { + Object exports = Object::New(env); + + exports["createOrCopyExternalBuffer"] = + Function::New(env, CreateOrCopyExternalBuffer); + exports["createOrCopyExternalBufferWithFinalize"] = + Function::New(env, CreateOrCopyExternalBufferWithFinalize); + exports["createOrCopyExternalBufferWithFinalizeHint"] = + Function::New(env, CreateOrCopyExternalBufferWithFinalizeHint); + + return exports; +} diff --git a/test/node-addon-api/test/callbackInfo.cc b/test/node-addon-api/test/callbackInfo.cc new file mode 100644 index 0000000..ad5f723 --- /dev/null +++ b/test/node-addon-api/test/callbackInfo.cc @@ -0,0 +1,27 @@ +#include +#include "napi.h" +using namespace Napi; + +struct TestCBInfoSetData { + static void Test(napi_env env, napi_callback_info info) { + Napi::CallbackInfo cbInfo(env, info); + int valuePointer = 1220202; + cbInfo.SetData(&valuePointer); + + int* placeHolder = static_cast(cbInfo.Data()); + assert(*(placeHolder) == valuePointer); + assert(placeHolder == &valuePointer); + } +}; + +void TestCallbackInfoSetData(const Napi::CallbackInfo& info) { + napi_callback_info cb_info = static_cast(info); + TestCBInfoSetData::Test(info.Env(), cb_info); +} + +Object InitCallbackInfo(Env env) { + Object exports = Object::New(env); + + exports["testCbSetData"] = Function::New(env, TestCallbackInfoSetData); + return exports; +} diff --git a/test/node-addon-api/test/callbackInfo.js b/test/node-addon-api/test/callbackInfo.js new file mode 100644 index 0000000..ea671a9 --- /dev/null +++ b/test/node-addon-api/test/callbackInfo.js @@ -0,0 +1,9 @@ +'use strict'; + +const common = require('./common'); + +module.exports = common.runTest(test); + +async function test (binding) { + binding.callbackInfo.testCbSetData(); +} diff --git a/test/node-addon-api/test/callbackscope.cc b/test/node-addon-api/test/callbackscope.cc new file mode 100644 index 0000000..9554a73 --- /dev/null +++ b/test/node-addon-api/test/callbackscope.cc @@ -0,0 +1,39 @@ +#include "assert.h" +#include "napi.h" +using namespace Napi; + +#if (NAPI_VERSION > 2) + +namespace { + +static void RunInCallbackScope(const CallbackInfo& info) { + Function callback = info[0].As(); + AsyncContext context(info.Env(), "callback_scope_test"); + CallbackScope scope(info.Env(), context); + callback.Call({}); +} + +static void RunInCallbackScopeFromExisting(const CallbackInfo& info) { + Function callback = info[0].As(); + Env env = info.Env(); + + AsyncContext ctx(env, "existing_callback_scope_test"); + napi_callback_scope scope; + napi_open_callback_scope(env, Object::New(env), ctx, &scope); + + CallbackScope existingScope(env, scope); + assert(existingScope.Env() == env); + + callback.Call({}); +} + +} // namespace + +Object InitCallbackScope(Env env) { + Object exports = Object::New(env); + exports["runInCallbackScope"] = Function::New(env, RunInCallbackScope); + exports["runInPreExistingCbScope"] = + Function::New(env, RunInCallbackScopeFromExisting); + return exports; +} +#endif diff --git a/test/node-addon-api/test/callbackscope.js b/test/node-addon-api/test/callbackscope.js new file mode 100644 index 0000000..2707af4 --- /dev/null +++ b/test/node-addon-api/test/callbackscope.js @@ -0,0 +1,49 @@ +'use strict'; +const assert = require('assert'); + +// we only check async hooks on 8.x an higher were +// they are closer to working properly +const nodeVersion = process.versions.node.split('.')[0]; +let asyncHooks; +function checkAsyncHooks () { + if (false) { // quickjs-napi: no async_hooks + if (asyncHooks === undefined) { + asyncHooks = require('async_hooks'); + } + return true; + } + return false; +} + +module.exports = require('./common').runTest(test); + +function test (binding) { + if (!checkAsyncHooks()) { return; } + + let id; + let insideHook = false; + const hook = asyncHooks.createHook({ + init (asyncId, type, triggerAsyncId, resource) { + if (id === undefined && (type === 'callback_scope_test' || type === 'existing_callback_scope_test')) { + id = asyncId; + } + }, + before (asyncId) { + if (asyncId === id) { insideHook = true; } + }, + after (asyncId) { + if (asyncId === id) { insideHook = false; } + } + }).enable(); + + return new Promise(resolve => { + binding.callbackscope.runInCallbackScope(function () { + assert(insideHook); + binding.callbackscope.runInPreExistingCbScope(function () { + assert(insideHook); + hook.disable(); + resolve(); + }); + }); + }); +} diff --git a/test/node-addon-api/test/child_processes/addon.js b/test/node-addon-api/test/child_processes/addon.js new file mode 100644 index 0000000..33e80d7 --- /dev/null +++ b/test/node-addon-api/test/child_processes/addon.js @@ -0,0 +1,11 @@ +'use strict'; +const assert = require('assert'); + +module.exports = { + workingCode: binding => { + const addon = binding.addon(); + assert.strictEqual(addon.increment(), 43); + assert.strictEqual(addon.increment(), 44); + assert.strictEqual(addon.subObject.decrement(), 43); + } +}; diff --git a/test/node-addon-api/test/child_processes/addon_data.js b/test/node-addon-api/test/child_processes/addon_data.js new file mode 100644 index 0000000..82d1aa3 --- /dev/null +++ b/test/node-addon-api/test/child_processes/addon_data.js @@ -0,0 +1,24 @@ +'use strict'; + +const assert = require('assert'); + +// Make sure the instance data finalizer is called at process exit. If the hint +// is non-zero, it will be printed out by the child process. +const cleanupTest = (binding, hint) => { + binding.addon_data(hint).verbose = true; +}; + +module.exports = { + workingCode: binding => { + const addonData = binding.addon_data(0); + + // Make sure it is possible to get/set instance data. + assert.strictEqual(addonData.verbose.verbose, false); + addonData.verbose = true; + assert.strictEqual(addonData.verbose.verbose, true); + addonData.verbose = false; + assert.strictEqual(addonData.verbose.verbose, false); + }, + cleanupWithHint: binding => cleanupTest(binding, 42), + cleanupWithoutHint: binding => cleanupTest(binding, 0) +}; diff --git a/test/node-addon-api/test/child_processes/objectwrap_function.js b/test/node-addon-api/test/child_processes/objectwrap_function.js new file mode 100644 index 0000000..2ee83cb --- /dev/null +++ b/test/node-addon-api/test/child_processes/objectwrap_function.js @@ -0,0 +1,22 @@ +'use strict'; + +const assert = require('assert'); +const testUtil = require('../testUtil'); + +module.exports = { + runTest: function (binding) { + return testUtil.runGCTests([ + 'objectwrap function', + () => { + const { FunctionTest } = binding.objectwrap_function(); + const newConstructed = new FunctionTest(); + const functionConstructed = FunctionTest(); + assert(newConstructed instanceof FunctionTest); + assert(functionConstructed instanceof FunctionTest); + assert.throws(() => (FunctionTest(true)), /an exception/); + }, + // Do one gc before returning. + () => {} + ]); + } +}; diff --git a/test/node-addon-api/test/child_processes/threadsafe_function_exception.js b/test/node-addon-api/test/child_processes/threadsafe_function_exception.js new file mode 100644 index 0000000..4fc63d7 --- /dev/null +++ b/test/node-addon-api/test/child_processes/threadsafe_function_exception.js @@ -0,0 +1,33 @@ +'use strict'; + +const assert = require('assert'); +const common = require('../common'); + +module.exports = { + testCall: async binding => { + const { testCall } = binding.threadsafe_function_exception; + + await new Promise(resolve => { + process.once('uncaughtException', common.mustCall(err => { + assert.strictEqual(err.message, 'test'); + resolve(); + }, 1)); + + testCall(common.mustCall(() => { + throw new Error('test'); + }, 1)); + }); + }, + testCallWithNativeCallback: async binding => { + const { testCallWithNativeCallback } = binding.threadsafe_function_exception; + + await new Promise(resolve => { + process.once('uncaughtException', common.mustCall(err => { + assert.strictEqual(err.message, 'test-from-native'); + resolve(); + }, 1)); + + testCallWithNativeCallback(); + }); + } +}; diff --git a/test/node-addon-api/test/child_processes/typed_threadsafe_function_exception.js b/test/node-addon-api/test/child_processes/typed_threadsafe_function_exception.js new file mode 100644 index 0000000..5cbfab2 --- /dev/null +++ b/test/node-addon-api/test/child_processes/typed_threadsafe_function_exception.js @@ -0,0 +1,19 @@ +'use strict'; + +const assert = require('assert'); +const common = require('../common'); + +module.exports = { + testCall: async binding => { + const { testCall } = binding.typed_threadsafe_function_exception; + + await new Promise(resolve => { + process.once('uncaughtException', common.mustCall(err => { + assert.strictEqual(err.message, 'test-from-native'); + resolve(); + }, 1)); + + testCall(); + }); + } +}; diff --git a/test/node-addon-api/test/common/index.js b/test/node-addon-api/test/common/index.js new file mode 100644 index 0000000..2469151 --- /dev/null +++ b/test/node-addon-api/test/common/index.js @@ -0,0 +1,246 @@ +/* Test helpers ported from test/common/index.js in Node.js project. */ +'use strict'; +const assert = require('assert'); +const path = require('path'); +const { access } = require('node:fs/promises'); +const { spawn } = require('child_process'); +const { EOL } = require('os'); +const readline = require('readline'); + +const escapeBackslashes = (pathString) => pathString.split('\\').join('\\\\'); + +const noop = () => {}; + +const mustCallChecks = []; + +function runCallChecks (exitCode) { + if (exitCode !== 0) return; + + const failed = mustCallChecks.filter(function (context) { + if ('minimum' in context) { + context.messageSegment = `at least ${context.minimum}`; + return context.actual < context.minimum; + } else { + context.messageSegment = `exactly ${context.exact}`; + return context.actual !== context.exact; + } + }); + + failed.forEach(function (context) { + console.log('Mismatched %s function calls. Expected %s, actual %d.', + context.name, + context.messageSegment, + context.actual); + console.log(context.stack.split(EOL).slice(2).join(EOL)); + }); + + if (failed.length) process.exit(1); +} + +exports.installAysncHooks = function (asyncResName) { + const asyncHooks = require('async_hooks'); + return new Promise((resolve, reject) => { + let id; + const events = []; + /** + * TODO(legendecas): investigate why resolving & disabling hooks in + * destroy callback causing crash with case 'callbackscope.js'. + */ + let destroyed = false; + const hook = asyncHooks.createHook({ + init (asyncId, type, triggerAsyncId, resource) { + if (id === undefined && type === asyncResName) { + id = asyncId; + events.push({ eventName: 'init', type, triggerAsyncId, resource }); + } + }, + before (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'before' }); + } + }, + after (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'after' }); + } + }, + destroy (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'destroy' }); + destroyed = true; + } + } + }).enable(); + + const interval = setInterval(() => { + if (destroyed) { + hook.disable(); + clearInterval(interval); + resolve(events); + } + }, 10); + }); +}; + +exports.mustCall = function (fn, exact) { + return _mustCallInner(fn, exact, 'exact'); +}; +exports.mustCallAtLeast = function (fn, minimum) { + return _mustCallInner(fn, minimum, 'minimum'); +}; + +function _mustCallInner (fn, criteria, field) { + if (typeof fn === 'number') { + criteria = fn; + fn = noop; + } else if (fn === undefined) { + fn = noop; + } + if (criteria === undefined) { + criteria = 1; + } + + if (typeof criteria !== 'number') { throw new TypeError(`Invalid ${field} value: ${criteria}`); } + + const context = { + [field]: criteria, + actual: 0, + stack: (new Error()).stack, + name: fn.name || '' + }; + + // add the exit listener only once to avoid listener leak warnings + if (mustCallChecks.length === 0) process.on('exit', runCallChecks); + + mustCallChecks.push(context); + + return function () { + context.actual++; + return fn.apply(this, arguments); + }; +} + +exports.mustNotCall = function (msg) { + return function mustNotCall () { + assert.fail(msg || 'function should not have been called'); + }; +}; + +const buildTypes = { + Release: 'Release', + Debug: 'Debug' +}; + +async function checkBuildType (buildType) { + try { + await access(path.join(path.resolve('./test/build'), buildType)); + return true; + } catch { + return false; + } +} + +async function whichBuildType () { + let buildType = 'Release'; + const envBuildType = process.env.NODE_API_BUILD_CONFIG || (process.env.npm_config_debug === 'true' ? 'Debug' : 'Release'); + if (envBuildType) { + if (Object.values(buildTypes).includes(envBuildType)) { + if (await checkBuildType(envBuildType)) { + buildType = envBuildType; + } else { + throw new Error(`The ${envBuildType} build doesn't exist.`); + } + } else { + throw new Error('Invalid value for NODE_API_BUILD_CONFIG environment variable. It should be set to Release or Debug.'); + } + } + return buildType; +} + +exports.whichBuildType = whichBuildType; + +exports.runTest = async function (test, buildType, buildPathRoot = process.env.BUILD_PATH || '') { + buildType = buildType || await whichBuildType(); + const bindings = [ + path.join(buildPathRoot, `../build/${buildType}/binding.node`), + path.join(buildPathRoot, `../build/${buildType}/binding_noexcept.node`), + path.join(buildPathRoot, `../build/${buildType}/binding_noexcept_maybe.node`), + path.join(buildPathRoot, `../build/${buildType}/binding_custom_namespace.node`) + ].map(it => require.resolve(it)); + + for (const item of bindings) { + await Promise.resolve(test(require(item), { bindingPath: item })) + .finally(exports.mustCall()); + } +}; + +exports.runTestWithBindingPath = async function (test, buildType, buildPathRoot = process.env.BUILD_PATH || '') { + buildType = buildType || await whichBuildType(); + + const bindings = [ + path.join(buildPathRoot, `../build/${buildType}/binding.node`), + path.join(buildPathRoot, `../build/${buildType}/binding_noexcept.node`), + path.join(buildPathRoot, `../build/${buildType}/binding_noexcept_maybe.node`), + path.join(buildPathRoot, `../build/${buildType}/binding_custom_namespace.node`) + ].map(it => require.resolve(it)); + + for (const item of bindings) { + await test(item); + } +}; + +exports.runTestWithBuildType = async function (test, buildType) { + buildType = buildType || await whichBuildType(); + + await Promise.resolve(test(buildType)) + .finally(exports.mustCall()); +}; + +// Some tests have to run in their own process, otherwise they would interfere +// with each other. Such tests export a factory function rather than the test +// itself so as to avoid automatic instantiation, and therefore interference, +// in the main process. Two examples are addon and addon_data, both of which +// use Napi::Env::SetInstanceData(). This helper function provides a common +// approach for running such tests. +exports.runTestInChildProcess = function ({ suite, testName, expectedStderr, execArgv }) { + return exports.runTestWithBindingPath((bindingName) => { + return new Promise((resolve) => { + bindingName = escapeBackslashes(bindingName); + // Test suites are assumed to be located here. + const suitePath = escapeBackslashes(path.join(__dirname, '..', 'child_processes', suite)); + const child = spawn(process.execPath, [ + '--expose-gc', + ...(execArgv ?? []), + '-e', + `require('${suitePath}').${testName}(require('${bindingName}'))` + ]); + const resultOfProcess = { stderr: [] }; + + // Capture the exit code and signal. + child.on('close', (code, signal) => resolve(Object.assign(resultOfProcess, { code, signal }))); + + // Capture the stderr as an array of lines. + readline + .createInterface({ input: child.stderr }) + .on('line', (line) => { + resultOfProcess.stderr.push(line); + }); + }).then(actual => { + // Back up the stderr in case the assertion fails. + const fullStderr = actual.stderr.map(item => `from child process: ${item}`); + const expected = { stderr: expectedStderr, code: 0, signal: null }; + + if (!expectedStderr) { + // If we don't care about stderr, delete it. + delete actual.stderr; + delete expected.stderr; + } else { + // Otherwise we only care about expected lines in the actual stderr, so + // filter out everything else. + actual.stderr = actual.stderr.filter(line => expectedStderr.includes(line)); + } + + assert.deepStrictEqual(actual, expected, `Assertion for child process test ${suite}.${testName} failed:${EOL}` + fullStderr.join(EOL)); + }); + }); +}; diff --git a/test/node-addon-api/test/common/test_helper.h b/test/node-addon-api/test/common/test_helper.h new file mode 100644 index 0000000..88ab1e8 --- /dev/null +++ b/test/node-addon-api/test/common/test_helper.h @@ -0,0 +1,71 @@ +#pragma once +#include "napi.h" + +namespace Napi { + +// Needs this here since the MaybeUnwrap() functions need to be in the +// same namespace as their arguments for C++ argument-dependent lookup +#ifdef NAPI_CPP_CUSTOM_NAMESPACE +namespace NAPI_CPP_CUSTOM_NAMESPACE { +#endif + +// Use this when a variable or parameter is unused in order to explicitly +// silence a compiler warning about that. +template +inline void USE(T&&) {} + +/** + * A test helper that converts MaybeOrValue to T by checking that + * MaybeOrValue is NOT an empty Maybe when NODE_ADDON_API_ENABLE_MAYBE is + * defined. + * + * Do nothing when NODE_ADDON_API_ENABLE_MAYBE is not defined. + */ +template +inline T MaybeUnwrap(MaybeOrValue maybe) { +#if defined(NODE_ADDON_API_ENABLE_MAYBE) + return maybe.Unwrap(); +#else + return maybe; +#endif +} + +/** + * A test helper that converts MaybeOrValue to T by getting the value that + * wrapped by the Maybe or return the default_value if the Maybe is empty when + * NODE_ADDON_API_ENABLE_MAYBE is defined. + * + * Do nothing when NODE_ADDON_API_ENABLE_MAYBE is not defined. + */ +template +inline T MaybeUnwrapOr(MaybeOrValue maybe, const T& default_value) { +#if defined(NODE_ADDON_API_ENABLE_MAYBE) + return maybe.UnwrapOr(default_value); +#else + USE(default_value); + return maybe; +#endif +} + +/** + * A test helper that converts MaybeOrValue to T by getting the value that + * wrapped by the Maybe or return false if the Maybe is empty when + * NODE_ADDON_API_ENABLE_MAYBE is defined. + * + * Copying the value to out when NODE_ADDON_API_ENABLE_MAYBE is not defined. + */ +template +inline bool MaybeUnwrapTo(MaybeOrValue maybe, T* out) { +#if defined(NODE_ADDON_API_ENABLE_MAYBE) + return maybe.UnwrapTo(out); +#else + *out = maybe; + return true; +#endif +} + +#ifdef NAPI_CPP_CUSTOM_NAMESPACE +} // namespace NAPI_CPP_CUSTOM_NAMESPACE +#endif + +} // namespace Napi diff --git a/test/node-addon-api/test/dataview/dataview.cc b/test/node-addon-api/test/dataview/dataview.cc new file mode 100644 index 0000000..cbd5933 --- /dev/null +++ b/test/node-addon-api/test/dataview/dataview.cc @@ -0,0 +1,89 @@ +#include "napi.h" + +using namespace Napi; + +static Value CreateDataView(const CallbackInfo& info) { + ArrayBuffer arrayBuffer = info[0].As(); + return DataView::New(info.Env(), arrayBuffer); +} + +static Value CreateDataViewWithByteOffset(const CallbackInfo& info) { + ArrayBuffer arrayBuffer = info[0].As(); + size_t byteOffset = info[1].As().Uint32Value(); + return DataView::New(info.Env(), arrayBuffer, byteOffset); +} + +static Value CreateDataViewWithByteOffsetAndByteLength( + const CallbackInfo& info) { + ArrayBuffer arrayBuffer = info[0].As(); + size_t byteOffset = info[1].As().Uint32Value(); + size_t byteLength = info[2].As().Uint32Value(); + return DataView::New(info.Env(), arrayBuffer, byteOffset, byteLength); +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +static Value CreateDataViewOnSharedArrayBuffer(const CallbackInfo& info) { + SharedArrayBuffer arrayBuffer = info[0].As(); + return DataView::New(info.Env(), arrayBuffer); +} + +static Value CreateDataViewOnSharedArrayBufferWithByteOffset( + const CallbackInfo& info) { + SharedArrayBuffer arrayBuffer = info[0].As(); + size_t byteOffset = info[1].As().Uint32Value(); + return DataView::New(info.Env(), arrayBuffer, byteOffset); +} + +static Value CreateDataViewOnSharedArrayBufferWithByteOffsetAndByteLength( + const CallbackInfo& info) { + SharedArrayBuffer arrayBuffer = info[0].As(); + size_t byteOffset = info[1].As().Uint32Value(); + size_t byteLength = info[2].As().Uint32Value(); + return DataView::New(info.Env(), arrayBuffer, byteOffset, byteLength); +} +#endif + +static Value GetBuffer(const CallbackInfo& info) { + return info[0].As().Buffer(); +} + +static Value GetArrayBuffer(const CallbackInfo& info) { + return info[0].As().ArrayBuffer(); +} + +static Value GetByteOffset(const CallbackInfo& info) { + return Number::New(info.Env(), + static_cast(info[0].As().ByteOffset())); +} + +static Value GetByteLength(const CallbackInfo& info) { + return Number::New(info.Env(), + static_cast(info[0].As().ByteLength())); +} + +Object InitDataView(Env env) { + Object exports = Object::New(env); + + exports["createDataView"] = Function::New(env, CreateDataView); + exports["createDataViewWithByteOffset"] = + Function::New(env, CreateDataViewWithByteOffset); + exports["createDataViewWithByteOffsetAndByteLength"] = + Function::New(env, CreateDataViewWithByteOffsetAndByteLength); + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + exports["createDataViewOnSharedArrayBuffer"] = + Function::New(env, CreateDataViewOnSharedArrayBuffer); + exports["createDataViewOnSharedArrayBufferWithByteOffset"] = + Function::New(env, CreateDataViewOnSharedArrayBufferWithByteOffset); + exports["createDataViewOnSharedArrayBufferWithByteOffsetAndByteLength"] = + Function::New( + env, CreateDataViewOnSharedArrayBufferWithByteOffsetAndByteLength); +#endif + + exports["getArrayBuffer"] = Function::New(env, GetArrayBuffer); + exports["getBuffer"] = Function::New(env, GetBuffer); + exports["getByteOffset"] = Function::New(env, GetByteOffset); + exports["getByteLength"] = Function::New(env, GetByteLength); + + return exports; +} diff --git a/test/node-addon-api/test/dataview/dataview.js b/test/node-addon-api/test/dataview/dataview.js new file mode 100644 index 0000000..5916f6b --- /dev/null +++ b/test/node-addon-api/test/dataview/dataview.js @@ -0,0 +1,74 @@ +'use strict'; + +const assert = require('assert'); +module.exports = require('../common').runTest(test); + +let runSharedArrayBufferTests = true; + +function test (binding) { + function testDataViewCreation (factory, arrayBuffer, offset, length) { + const view = factory(arrayBuffer, offset, length); + offset = offset || 0; + if (arrayBuffer instanceof ArrayBuffer) { + assert.ok(dataview.getArrayBuffer(view) instanceof ArrayBuffer); + assert.strictEqual(dataview.getArrayBuffer(view), arrayBuffer); + } else { + assert.ok(dataview.getBuffer(view) instanceof SharedArrayBuffer); + assert.strictEqual(dataview.getBuffer(view), arrayBuffer); + } + assert.strictEqual(dataview.getByteOffset(view), offset); + assert.strictEqual(dataview.getByteLength(view), + length || arrayBuffer.byteLength - offset); + } + + function testInvalidRange (factory, arrayBuffer, offset, length) { + assert.throws(() => { + factory(arrayBuffer, offset, length); + }, RangeError); + } + + const { hasSharedArrayBuffer, dataview } = binding; + + { + const arrayBuffer = new ArrayBuffer(10); + + testDataViewCreation(dataview.createDataView, arrayBuffer); + testDataViewCreation(dataview.createDataViewWithByteOffset, arrayBuffer, 2); + testDataViewCreation(dataview.createDataViewWithByteOffset, arrayBuffer, 10); + testDataViewCreation(dataview.createDataViewWithByteOffsetAndByteLength, arrayBuffer, 2, 4); + testDataViewCreation(dataview.createDataViewWithByteOffsetAndByteLength, arrayBuffer, 10, 0); + + testInvalidRange(dataview.createDataViewWithByteOffset, arrayBuffer, 11); + testInvalidRange(dataview.createDataViewWithByteOffsetAndByteLength, arrayBuffer, 11, 0); + testInvalidRange(dataview.createDataViewWithByteOffsetAndByteLength, arrayBuffer, 6, 5); + } + + if (hasSharedArrayBuffer && runSharedArrayBufferTests) { + const sab = new SharedArrayBuffer(10); + + try { + testDataViewCreation(dataview.createDataViewOnSharedArrayBuffer, sab); + } catch (ex) { + // The `napi_create_dataview` API does not have a valid `#define` + // preprocessor guard for SharedArrayBuffer support, so it is + // possible that the API is present but creating a DataView on + // SharedArrayBuffer is not supported in the current version of Node.js. + // In that case, we should skip the test instead of throwing. + if (ex.message === 'Invalid argument') { + console.warn(`The current version of Node.js (${process.version}) does not support creating DataViews on SharedArrayBuffers; skipping tests.`); + runSharedArrayBufferTests = false; + return; + } + + throw ex; + } + testDataViewCreation(dataview.createDataViewOnSharedArrayBufferWithByteOffset, sab, 2); + testDataViewCreation(dataview.createDataViewOnSharedArrayBufferWithByteOffset, sab, 10); + testDataViewCreation(dataview.createDataViewOnSharedArrayBufferWithByteOffsetAndByteLength, sab, 2, 4); + testDataViewCreation(dataview.createDataViewOnSharedArrayBufferWithByteOffsetAndByteLength, sab, 10, 0); + + testInvalidRange(dataview.createDataViewOnSharedArrayBufferWithByteOffset, sab, 11); + testInvalidRange(dataview.createDataViewOnSharedArrayBufferWithByteOffsetAndByteLength, sab, 11, 0); + testInvalidRange(dataview.createDataViewOnSharedArrayBufferWithByteOffsetAndByteLength, sab, 6, 5); + } +} diff --git a/test/node-addon-api/test/dataview/dataview_read_write.cc b/test/node-addon-api/test/dataview/dataview_read_write.cc new file mode 100644 index 0000000..da2beed --- /dev/null +++ b/test/node-addon-api/test/dataview/dataview_read_write.cc @@ -0,0 +1,115 @@ +#include "napi.h" + +using namespace Napi; + +static Value GetFloat32(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + return Number::New(info.Env(), info[0].As().GetFloat32(byteOffset)); +} + +static Value GetFloat64(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + return Number::New(info.Env(), info[0].As().GetFloat64(byteOffset)); +} + +static Value GetInt8(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + return Number::New(info.Env(), info[0].As().GetInt8(byteOffset)); +} + +static Value GetInt16(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + return Number::New(info.Env(), info[0].As().GetInt16(byteOffset)); +} + +static Value GetInt32(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + return Number::New(info.Env(), info[0].As().GetInt32(byteOffset)); +} + +static Value GetUint8(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + return Number::New(info.Env(), info[0].As().GetUint8(byteOffset)); +} + +static Value GetUint16(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + return Number::New(info.Env(), info[0].As().GetUint16(byteOffset)); +} + +static Value GetUint32(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + return Number::New(info.Env(), info[0].As().GetUint32(byteOffset)); +} + +static void SetFloat32(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + auto value = info[2].As().FloatValue(); + info[0].As().SetFloat32(byteOffset, value); +} + +static void SetFloat64(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + auto value = info[2].As().DoubleValue(); + info[0].As().SetFloat64(byteOffset, value); +} + +static void SetInt8(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + auto value = info[2].As().Int32Value(); + info[0].As().SetInt8(byteOffset, value); +} + +static void SetInt16(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + auto value = info[2].As().Int32Value(); + info[0].As().SetInt16(byteOffset, value); +} + +static void SetInt32(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + auto value = info[2].As().Int32Value(); + info[0].As().SetInt32(byteOffset, value); +} + +static void SetUint8(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + auto value = info[2].As().Uint32Value(); + info[0].As().SetUint8(byteOffset, value); +} + +static void SetUint16(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + auto value = info[2].As().Uint32Value(); + info[0].As().SetUint16(byteOffset, value); +} + +static void SetUint32(const CallbackInfo& info) { + size_t byteOffset = info[1].As().Uint32Value(); + auto value = info[2].As().Uint32Value(); + info[0].As().SetUint32(byteOffset, value); +} + +Object InitDataViewReadWrite(Env env) { + Object exports = Object::New(env); + + exports["getFloat32"] = Function::New(env, GetFloat32); + exports["getFloat64"] = Function::New(env, GetFloat64); + exports["getInt8"] = Function::New(env, GetInt8); + exports["getInt16"] = Function::New(env, GetInt16); + exports["getInt32"] = Function::New(env, GetInt32); + exports["getUint8"] = Function::New(env, GetUint8); + exports["getUint16"] = Function::New(env, GetUint16); + exports["getUint32"] = Function::New(env, GetUint32); + + exports["setFloat32"] = Function::New(env, SetFloat32); + exports["setFloat64"] = Function::New(env, SetFloat64); + exports["setInt8"] = Function::New(env, SetInt8); + exports["setInt16"] = Function::New(env, SetInt16); + exports["setInt32"] = Function::New(env, SetInt32); + exports["setUint8"] = Function::New(env, SetUint8); + exports["setUint16"] = Function::New(env, SetUint16); + exports["setUint32"] = Function::New(env, SetUint32); + + return exports; +} diff --git a/test/node-addon-api/test/dataview/dataview_read_write.js b/test/node-addon-api/test/dataview/dataview_read_write.js new file mode 100644 index 0000000..708ef28 --- /dev/null +++ b/test/node-addon-api/test/dataview/dataview_read_write.js @@ -0,0 +1,92 @@ +/* eslint-disable no-eval */ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + function expected (type, value) { + return eval(`(new ${type}Array([${value}]))[0]`); + } + + function nativeReadDataView (dataview, type, offset, value) { + return eval(`binding.dataview_read_write.get${type}(dataview, offset)`); + } + + function nativeWriteDataView (dataview, type, offset, value) { + eval(`binding.dataview_read_write.set${type}(dataview, offset, value)`); + } + + // eslint-disable-next-line no-unused-vars + function isLittleEndian () { + const buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true /* littleEndian */); + return new Int16Array(buffer)[0] === 256; + } + + function jsReadDataView (dataview, type, offset, value) { + return eval(`dataview.get${type}(offset, isLittleEndian())`); + } + + function jsWriteDataView (dataview, type, offset, value) { + eval(`dataview.set${type}(offset, value, isLittleEndian())`); + } + + function testReadData (dataview, type, offset, value) { + jsWriteDataView(dataview, type, offset, 0); + assert.strictEqual(jsReadDataView(dataview, type, offset), 0); + + jsWriteDataView(dataview, type, offset, value); + assert.strictEqual( + nativeReadDataView(dataview, type, offset), expected(type, value)); + } + + function testWriteData (dataview, type, offset, value) { + jsWriteDataView(dataview, type, offset, 0); + assert.strictEqual(jsReadDataView(dataview, type, offset), 0); + + nativeWriteDataView(dataview, type, offset, value); + assert.strictEqual( + jsReadDataView(dataview, type, offset), expected(type, value)); + } + + function testInvalidOffset (dataview, type, offset, value) { + assert.throws(() => { + nativeReadDataView(dataview, type, offset); + }, RangeError); + + assert.throws(() => { + nativeWriteDataView(dataview, type, offset, value); + }, RangeError); + } + + const dataview = new DataView(new ArrayBuffer(22)); + + testReadData(dataview, 'Float32', 0, 10.2); + testReadData(dataview, 'Float64', 4, 20.3); + testReadData(dataview, 'Int8', 5, 120); + testReadData(dataview, 'Int16', 7, 15000); + testReadData(dataview, 'Int32', 11, 200000); + testReadData(dataview, 'Uint8', 12, 128); + testReadData(dataview, 'Uint16', 14, 32768); + testReadData(dataview, 'Uint32', 18, 1000000); + + testWriteData(dataview, 'Float32', 0, 10.2); + testWriteData(dataview, 'Float64', 4, 20.3); + testWriteData(dataview, 'Int8', 5, 120); + testWriteData(dataview, 'Int16', 7, 15000); + testWriteData(dataview, 'Int32', 11, 200000); + testWriteData(dataview, 'Uint8', 12, 128); + testWriteData(dataview, 'Uint16', 14, 32768); + testWriteData(dataview, 'Uint32', 18, 1000000); + + testInvalidOffset(dataview, 'Float32', 22, 10.2); + testInvalidOffset(dataview, 'Float64', 22, 20.3); + testInvalidOffset(dataview, 'Int8', 22, 120); + testInvalidOffset(dataview, 'Int16', 22, 15000); + testInvalidOffset(dataview, 'Int32', 22, 200000); + testInvalidOffset(dataview, 'Uint8', 22, 128); + testInvalidOffset(dataview, 'Uint16', 22, 32768); + testInvalidOffset(dataview, 'Uint32', 22, 1000000); +} diff --git a/test/node-addon-api/test/date.cc b/test/node-addon-api/test/date.cc new file mode 100644 index 0000000..a446bde --- /dev/null +++ b/test/node-addon-api/test/date.cc @@ -0,0 +1,52 @@ +#include "napi.h" + +using namespace Napi; + +#if (NAPI_VERSION > 4) +namespace { + +Value CreateDate(const CallbackInfo& info) { + double input = info[0].As().DoubleValue(); + + return Date::New(info.Env(), input); +} + +Value CreateDateFromTimePoint(const CallbackInfo& info) { + auto input = std::chrono::system_clock::time_point{}; + return Date::New(info.Env(), input); +} + +Value IsDate(const CallbackInfo& info) { + Date input = info[0].As(); + + return Boolean::New(info.Env(), input.IsDate()); +} + +Value ValueOf(const CallbackInfo& info) { + Date input = info[0].As(); + + return Number::New(info.Env(), input.ValueOf()); +} + +Value OperatorValue(const CallbackInfo& info) { + Date input = info[0].As(); + + return Boolean::New(info.Env(), + input.ValueOf() == static_cast(input)); +} + +} // anonymous namespace + +Object InitDate(Env env) { + Object exports = Object::New(env); + exports["CreateDate"] = Function::New(env, CreateDate); + exports["CreateDateFromTimePoint"] = + Function::New(env, CreateDateFromTimePoint); + exports["IsDate"] = Function::New(env, IsDate); + exports["ValueOf"] = Function::New(env, ValueOf); + exports["OperatorValue"] = Function::New(env, OperatorValue); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/date.js b/test/node-addon-api/test/date.js new file mode 100644 index 0000000..588b741 --- /dev/null +++ b/test/node-addon-api/test/date.js @@ -0,0 +1,20 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + const { + CreateDate, + IsDate, + ValueOf, + OperatorValue, + CreateDateFromTimePoint + } = binding.date; + assert.deepStrictEqual(CreateDate(0), new Date(0)); + assert.deepStrictEqual(CreateDateFromTimePoint(), new Date(0)); + assert.strictEqual(IsDate(new Date(0)), true); + assert.strictEqual(ValueOf(new Date(42)), 42); + assert.strictEqual(OperatorValue(new Date(42)), true); +} diff --git a/test/node-addon-api/test/env_cleanup.cc b/test/node-addon-api/test/env_cleanup.cc new file mode 100644 index 0000000..a0ef62b --- /dev/null +++ b/test/node-addon-api/test/env_cleanup.cc @@ -0,0 +1,100 @@ +#include +#include "napi.h" + +using namespace Napi; + +#if (NAPI_VERSION > 2) +namespace { + +static void cleanup(void* arg) { + printf("static cleanup(%d)\n", *(int*)(arg)); +} +static void cleanupInt(int* arg) { + printf("static cleanup(%d)\n", *(arg)); +} + +static void cleanupVoid() { + printf("static cleanup()\n"); +} + +static int secret1 = 42; +static int secret2 = 43; + +class TestClass { + public: + Env::CleanupHook hook; + + void removeHook(Env env) { hook.Remove(env); } +}; + +Value AddHooks(const CallbackInfo& info) { + auto env = info.Env(); + + bool shouldRemove = info[0].As().Value(); + + // hook: void (*)(void *arg), hint: int + auto hook1 = env.AddCleanupHook(cleanup, &secret1); + // test using same hook+arg pair + auto hook1b = env.AddCleanupHook(cleanup, &secret1); + + // hook: void (*)(int *arg), hint: int + auto hook2 = env.AddCleanupHook(cleanupInt, &secret2); + + // hook: void (*)(int *arg), hint: void (default) + auto hook3 = env.AddCleanupHook(cleanupVoid); + // test using the same hook + auto hook3b = env.AddCleanupHook(cleanupVoid); + + // hook: lambda []void (int *arg)->void, hint: int + auto hook4 = env.AddCleanupHook( + [&](int* arg) { printf("lambda cleanup(%d)\n", *arg); }, &secret1); + + // hook: lambda []void (void *)->void, hint: void + auto hook5 = + env.AddCleanupHook([&](void*) { printf("lambda cleanup(void)\n"); }, + static_cast(nullptr)); + + // hook: lambda []void ()->void, hint: void (default) + auto hook6 = env.AddCleanupHook([&]() { printf("lambda cleanup()\n"); }); + + if (shouldRemove) { + hook1.Remove(env); + hook1b.Remove(env); + hook2.Remove(env); + hook3.Remove(env); + hook3b.Remove(env); + hook4.Remove(env); + hook5.Remove(env); + hook6.Remove(env); + } + + int added = 0; + + added += !hook1.IsEmpty(); + added += !hook1b.IsEmpty(); + added += !hook2.IsEmpty(); + added += !hook3.IsEmpty(); + added += !hook3b.IsEmpty(); + added += !hook4.IsEmpty(); + added += !hook5.IsEmpty(); + added += !hook6.IsEmpty(); + + // Test store a hook in a member class variable + auto myclass = TestClass(); + myclass.hook = env.AddCleanupHook(cleanup, &secret1); + myclass.removeHook(env); + + return Number::New(env, added); +} + +} // anonymous namespace + +Object InitEnvCleanup(Env env) { + Object exports = Object::New(env); + + exports["addHooks"] = Function::New(env, AddHooks); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/env_cleanup.js b/test/node-addon-api/test/env_cleanup.js new file mode 100644 index 0000000..ad515eb --- /dev/null +++ b/test/node-addon-api/test/env_cleanup.js @@ -0,0 +1,55 @@ +'use strict'; + +const assert = require('assert'); + +if (process.argv[2] === 'runInChildProcess') { + const bindingPath = process.argv[3]; + const removeHooks = process.argv[4] === 'true'; + + const binding = require(bindingPath); + const actualAdded = binding.env_cleanup.addHooks(removeHooks); + const expectedAdded = removeHooks === true ? 0 : 8; + assert(actualAdded === expectedAdded, 'Incorrect number of hooks added'); +} else { + module.exports = require('./common').runTestWithBindingPath(test); +} + +function test (bindingPath) { + for (const removeHooks of [false, true]) { + const { status, output } = require('./napi_child').spawnSync( + process.execPath, + [ + __filename, + 'runInChildProcess', + bindingPath, + removeHooks + ], + { encoding: 'utf8' } + ); + + const stdout = output[1].trim(); + /** + * There is no need to sort the lines, as per Node-API documentation: + * > The hooks will be called in reverse order, i.e. the most recently + * > added one will be called first. + */ + const lines = stdout.split(/[\r\n]+/); + + assert(status === 0, `Process aborted with status ${status}`); + + if (removeHooks) { + assert.deepStrictEqual(lines, [''], 'Child process had console output when none expected'); + } else { + assert.deepStrictEqual(lines, [ + 'lambda cleanup()', + 'lambda cleanup(void)', + 'lambda cleanup(42)', + 'static cleanup()', + 'static cleanup()', + 'static cleanup(43)', + 'static cleanup(42)', + 'static cleanup(42)' + ], 'Child process console output mismisatch'); + } + } +} diff --git a/test/node-addon-api/test/env_misc.cc b/test/node-addon-api/test/env_misc.cc new file mode 100644 index 0000000..a453e5d --- /dev/null +++ b/test/node-addon-api/test/env_misc.cc @@ -0,0 +1,25 @@ +#include "napi.h" +#include "test_helper.h" + +#if (NAPI_VERSION > 8) + +using namespace Napi; + +namespace { + +Value GetModuleFileName(const CallbackInfo& info) { + Env env = info.Env(); + return String::New(env, env.GetModuleFileName()); +} + +} // end anonymous namespace + +Object InitEnvMiscellaneous(Env env) { + Object exports = Object::New(env); + + exports["get_module_file_name"] = Function::New(env, GetModuleFileName); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/env_misc.js b/test/node-addon-api/test/env_misc.js new file mode 100644 index 0000000..19fc988 --- /dev/null +++ b/test/node-addon-api/test/env_misc.js @@ -0,0 +1,12 @@ +'use strict'; + +const assert = require('assert'); +const { pathToFileURL } = require('url'); + +module.exports = require('./common').runTest(test); + +function test (binding, { bindingPath } = {}) { + const path = binding.env_misc.get_module_file_name(); + const bindingFileUrl = pathToFileURL(bindingPath).toString(); + assert(bindingFileUrl === path); +} diff --git a/test/node-addon-api/test/error.cc b/test/node-addon-api/test/error.cc new file mode 100644 index 0000000..6c71635 --- /dev/null +++ b/test/node-addon-api/test/error.cc @@ -0,0 +1,436 @@ +#include +#include +#include "assert.h" +#include "napi.h" + +using namespace Napi; + +namespace { + +std::promise promise_for_child_process_; +std::promise promise_for_worker_thread_; + +void ResetPromises(const CallbackInfo&) { + promise_for_child_process_ = std::promise(); + promise_for_worker_thread_ = std::promise(); +} + +void WaitForWorkerThread(const CallbackInfo&) { + std::future future = promise_for_worker_thread_.get_future(); + + std::future_status status = future.wait_for(std::chrono::seconds(5)); + + if (status != std::future_status::ready) { + Error::Fatal("WaitForWorkerThread", "status != std::future_status::ready"); + } +} + +void ReleaseAndWaitForChildProcess(const CallbackInfo& info, + const uint32_t index) { + if (info.Length() < index + 1) { + return; + } + + if (!info[index].As().Value()) { + return; + } + + promise_for_worker_thread_.set_value(); + + std::future future = promise_for_child_process_.get_future(); + + std::future_status status = future.wait_for(std::chrono::seconds(5)); + + if (status != std::future_status::ready) { + Error::Fatal("ReleaseAndWaitForChildProcess", + "status != std::future_status::ready"); + } +} + +void ReleaseWorkerThread(const CallbackInfo&) { + promise_for_child_process_.set_value(); +} + +void DoNotCatch(const CallbackInfo& info) { + Function thrower = info[0].As(); + thrower({}); +} + +void ThrowApiError(const CallbackInfo& info) { + // Attempting to call an empty function value will throw an API error. + Function(info.Env(), nullptr).Call(std::initializer_list{}); +} + +void LastExceptionErrorCode(const CallbackInfo& info) { + // Previously, `napi_extended_error_info.error_code` got reset to `napi_ok` in + // subsequent Node-API function calls, so this would have previously thrown an + // `Error` object instead of a `TypeError` object. + Env env = info.Env(); + bool res; + napi_get_value_bool(env, Value::From(env, "asd"), &res); + NAPI_THROW_VOID(Error::New(env)); +} + +void TestErrorCopySemantics(const Napi::CallbackInfo& info) { + Napi::Error newError = Napi::Error::New(info.Env(), "errorCopyCtor"); + Napi::Error existingErr; + +#ifdef NAPI_CPP_EXCEPTIONS + std::string msg = "errorCopyCtor"; + assert(strcmp(newError.what(), msg.c_str()) == 0); +#endif + + Napi::Error errCopyCtor = newError; + assert(errCopyCtor.Message() == "errorCopyCtor"); + + existingErr = newError; + assert(existingErr.Message() == "errorCopyCtor"); +} + +void TestErrorMoveSemantics(const Napi::CallbackInfo& info) { + std::string errorMsg = "errorMoveCtor"; + Napi::Error newError = Napi::Error::New(info.Env(), errorMsg.c_str()); + Napi::Error errFromMove = std::move(newError); + assert(errFromMove.Message() == "errorMoveCtor"); + + newError = Napi::Error::New(info.Env(), "errorMoveAssign"); + Napi::Error existingErr = std::move(newError); + + assert(existingErr.Message() == "errorMoveAssign"); +} + +#ifdef NAPI_CPP_EXCEPTIONS + +void ThrowJSError(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + throw Error::New(info.Env(), message); +} + +void ThrowTypeErrorCtor(const CallbackInfo& info) { + Napi::Value js_type_error = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + + throw Napi::TypeError(info.Env(), js_type_error); +} + +void ThrowTypeError(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + throw TypeError::New(info.Env(), message); +} + +void ThrowTypeErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + throw TypeError::New(info.Env(), message.c_str()); +} + +void ThrowRangeErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + ReleaseAndWaitForChildProcess(info, 1); + throw RangeError::New(info.Env(), message.c_str()); +} + +void ThrowRangeErrorCtor(const CallbackInfo& info) { + Napi::Value js_range_err = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + throw Napi::RangeError(info.Env(), js_range_err); +} + +void ThrowEmptyRangeError(const CallbackInfo& info) { + ReleaseAndWaitForChildProcess(info, 1); + throw RangeError(); +} + +void ThrowRangeError(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + throw RangeError::New(info.Env(), message); +} + +#if NAPI_VERSION > 8 +void ThrowSyntaxErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + ReleaseAndWaitForChildProcess(info, 1); + throw SyntaxError::New(info.Env(), message.c_str()); +} + +void ThrowSyntaxErrorCtor(const CallbackInfo& info) { + Napi::Value js_range_err = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + throw Napi::SyntaxError(info.Env(), js_range_err); +} + +void ThrowSyntaxError(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + throw SyntaxError::New(info.Env(), message); +} +#endif // NAPI_VERSION > 8 + +Value CatchError(const CallbackInfo& info) { + Function thrower = info[0].As(); + try { + thrower({}); + } catch (const Error& e) { + return e.Value(); + } + return info.Env().Null(); +} + +Value CatchErrorMessage(const CallbackInfo& info) { + Function thrower = info[0].As(); + try { + thrower({}); + } catch (const Error& e) { + std::string message = e.Message(); + return String::New(info.Env(), message); + } + return info.Env().Null(); +} + +void CatchAndRethrowError(const CallbackInfo& info) { + Function thrower = info[0].As(); + try { + thrower({}); + } catch (Error& e) { + e.Set("caught", Boolean::New(info.Env(), true)); + throw; + } +} + +void ThrowErrorThatEscapesScope(const CallbackInfo& info) { + HandleScope scope(info.Env()); + + std::string message = info[0].As().Utf8Value(); + throw Error::New(info.Env(), message); +} + +void CatchAndRethrowErrorThatEscapesScope(const CallbackInfo& info) { + HandleScope scope(info.Env()); + try { + ThrowErrorThatEscapesScope(info); + } catch (Error& e) { + e.Set("caught", Boolean::New(info.Env(), true)); + throw; + } +} + +#else // NAPI_CPP_EXCEPTIONS + +void ThrowJSError(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + Error::New(info.Env(), message).ThrowAsJavaScriptException(); +} + +void ThrowTypeError(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + TypeError::New(info.Env(), message).ThrowAsJavaScriptException(); +} + +void ThrowTypeErrorCtor(const CallbackInfo& info) { + Napi::Value js_type_error = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + TypeError(info.Env(), js_type_error).ThrowAsJavaScriptException(); +} + +void ThrowTypeErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + TypeError::New(info.Env(), message.c_str()).ThrowAsJavaScriptException(); +} + +void ThrowRangeError(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + RangeError::New(info.Env(), message).ThrowAsJavaScriptException(); +} + +void ThrowRangeErrorCtor(const CallbackInfo& info) { + Napi::Value js_range_err = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + RangeError(info.Env(), js_range_err).ThrowAsJavaScriptException(); +} + +void ThrowRangeErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + ReleaseAndWaitForChildProcess(info, 1); + RangeError::New(info.Env(), message.c_str()).ThrowAsJavaScriptException(); +} + +// TODO: Figure out the correct api for this +void ThrowEmptyRangeError(const CallbackInfo& info) { + ReleaseAndWaitForChildProcess(info, 1); + RangeError().ThrowAsJavaScriptException(); +} + +#if NAPI_VERSION > 8 +void ThrowSyntaxError(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + + ReleaseAndWaitForChildProcess(info, 1); + SyntaxError::New(info.Env(), message).ThrowAsJavaScriptException(); +} + +void ThrowSyntaxErrorCtor(const CallbackInfo& info) { + Napi::Value js_range_err = info[0]; + ReleaseAndWaitForChildProcess(info, 1); + SyntaxError(info.Env(), js_range_err).ThrowAsJavaScriptException(); +} + +void ThrowSyntaxErrorCStr(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + ReleaseAndWaitForChildProcess(info, 1); + SyntaxError::New(info.Env(), message.c_str()).ThrowAsJavaScriptException(); +} +#endif // NAPI_VERSION > 8 + +Value CatchError(const CallbackInfo& info) { + Function thrower = info[0].As(); + thrower({}); + + Env env = info.Env(); + if (env.IsExceptionPending()) { + Error e = env.GetAndClearPendingException(); + return e.Value(); + } + return info.Env().Null(); +} + +Value CatchErrorMessage(const CallbackInfo& info) { + Function thrower = info[0].As(); + thrower({}); + + Env env = info.Env(); + if (env.IsExceptionPending()) { + Error e = env.GetAndClearPendingException(); + std::string message = e.Message(); + return String::New(env, message); + } + return info.Env().Null(); +} + +void CatchAndRethrowError(const CallbackInfo& info) { + Function thrower = info[0].As(); + thrower({}); + + Env env = info.Env(); + if (env.IsExceptionPending()) { + Error e = env.GetAndClearPendingException(); + e.Set("caught", Boolean::New(info.Env(), true)); + e.ThrowAsJavaScriptException(); + } +} + +void ThrowErrorThatEscapesScope(const CallbackInfo& info) { + HandleScope scope(info.Env()); + + std::string message = info[0].As().Utf8Value(); + Error::New(info.Env(), message).ThrowAsJavaScriptException(); +} + +void CatchAndRethrowErrorThatEscapesScope(const CallbackInfo& info) { + HandleScope scope(info.Env()); + ThrowErrorThatEscapesScope(info); + + Env env = info.Env(); + if (env.IsExceptionPending()) { + Error e = env.GetAndClearPendingException(); + e.Set("caught", Boolean::New(info.Env(), true)); + e.ThrowAsJavaScriptException(); + } +} + +#endif // NAPI_CPP_EXCEPTIONS + +void ThrowFatalError(const CallbackInfo& /*info*/) { + Error::Fatal("Error::ThrowFatalError", "This is a fatal error"); +} + +void ThrowDefaultError(const CallbackInfo& info) { + napi_value dummy; + napi_env env = info.Env(); + napi_status status = napi_get_undefined(env, &dummy); + NAPI_FATAL_IF_FAILED(status, "ThrowDefaultError", "napi_get_undefined"); + + if (info[0].As().Value()) { + // Provoke Node-API into setting an error, then use the `Napi::Error::New` + // factory with only the `env` parameter to throw an exception generated + // from the last error. + uint32_t dummy_uint32; + status = napi_get_value_uint32(env, dummy, &dummy_uint32); + if (status == napi_ok) { + Error::Fatal("ThrowDefaultError", "napi_get_value_uint32"); + } + // We cannot use `NAPI_THROW_IF_FAILED()` here because we do not wish + // control to pass back to the engine if we throw an exception here and C++ + // exceptions are turned on. + Napi::Error::New(env).ThrowAsJavaScriptException(); + } + + // Produce and throw a second error that has different content than the one + // above. If the one above was thrown, then throwing the one below should + // have the effect of re-throwing the one above. + status = napi_get_named_property(env, dummy, "xyzzy", &dummy); + if (status == napi_ok) { + Error::Fatal("ThrowDefaultError", "napi_get_named_property"); + } + + ReleaseAndWaitForChildProcess(info, 1); + + // The macro creates a `Napi::Error` using the factory that takes only the + // env, however, it heeds the exception mechanism to be used. + NAPI_THROW_IF_FAILED_VOID(env, status); +} + +} // end anonymous namespace + +Object InitError(Env env) { + Object exports = Object::New(env); + exports["throwApiError"] = Function::New(env, ThrowApiError); + exports["testErrorCopySemantics"] = + Function::New(env, TestErrorCopySemantics); + exports["testErrorMoveSemantics"] = + Function::New(env, TestErrorMoveSemantics); + exports["lastExceptionErrorCode"] = + Function::New(env, LastExceptionErrorCode); + exports["throwJSError"] = Function::New(env, ThrowJSError); + exports["throwTypeError"] = Function::New(env, ThrowTypeError); + exports["throwTypeErrorCtor"] = Function::New(env, ThrowTypeErrorCtor); + exports["throwTypeErrorCStr"] = Function::New(env, ThrowTypeErrorCStr); + exports["throwRangeError"] = Function::New(env, ThrowRangeError); + exports["throwRangeErrorCtor"] = Function::New(env, ThrowRangeErrorCtor); + exports["throwRangeErrorCStr"] = Function::New(env, ThrowRangeErrorCStr); + exports["throwEmptyRangeError"] = Function::New(env, ThrowEmptyRangeError); +#if NAPI_VERSION > 8 + exports["throwSyntaxError"] = Function::New(env, ThrowSyntaxError); + exports["throwSyntaxErrorCtor"] = Function::New(env, ThrowSyntaxErrorCtor); + exports["throwSyntaxErrorCStr"] = Function::New(env, ThrowSyntaxErrorCStr); +#endif // NAPI_VERSION > 8 + exports["catchError"] = Function::New(env, CatchError); + exports["catchErrorMessage"] = Function::New(env, CatchErrorMessage); + exports["doNotCatch"] = Function::New(env, DoNotCatch); + exports["catchAndRethrowError"] = Function::New(env, CatchAndRethrowError); + exports["throwErrorThatEscapesScope"] = + Function::New(env, ThrowErrorThatEscapesScope); + exports["catchAndRethrowErrorThatEscapesScope"] = + Function::New(env, CatchAndRethrowErrorThatEscapesScope); + exports["throwFatalError"] = Function::New(env, ThrowFatalError); + exports["throwDefaultError"] = Function::New(env, ThrowDefaultError); + exports["resetPromises"] = Function::New(env, ResetPromises); + exports["waitForWorkerThread"] = Function::New(env, WaitForWorkerThread); + exports["releaseWorkerThread"] = Function::New(env, ReleaseWorkerThread); + return exports; +} diff --git a/test/node-addon-api/test/error.js b/test/node-addon-api/test/error.js new file mode 100644 index 0000000..c2a3ad3 --- /dev/null +++ b/test/node-addon-api/test/error.js @@ -0,0 +1,111 @@ +'use strict'; + +const assert = require('assert'); + +if (process.argv[2] === 'fatal') { + const binding = require(process.argv[3]); + binding.error.throwFatalError(); +} + +module.exports = require('./common').runTestWithBindingPath(test); + +const napiVersion = Number(process.env.NAPI_VERSION ?? process.versions.napi); + +function test (bindingPath) { + const binding = require(bindingPath); + binding.error.testErrorCopySemantics(); + binding.error.testErrorMoveSemantics(); + + assert.throws(() => binding.error.throwApiError('test'), function (err) { + return err instanceof Error && err.message.includes('Invalid'); + }); + + assert.throws(() => binding.error.lastExceptionErrorCode(), function (err) { + return err instanceof TypeError && err.message === 'A boolean was expected'; + }); + + assert.throws(() => binding.error.throwJSError('test'), function (err) { + return err instanceof Error && err.message === 'test'; + }); + + assert.throws(() => binding.error.throwTypeErrorCStr('test'), function (err) { + return err instanceof TypeError && err.message === 'test'; + }); + + assert.throws(() => binding.error.throwRangeErrorCStr('test'), function (err) { + return err instanceof RangeError && err.message === 'test'; + }); + + assert.throws(() => binding.error.throwRangeError('test'), function (err) { + return err instanceof RangeError && err.message === 'test'; + }); + + assert.throws(() => binding.error.throwTypeErrorCtor(new TypeError('jsTypeError')), function (err) { + return err instanceof TypeError && err.message === 'jsTypeError'; + }); + + assert.throws(() => binding.error.throwRangeErrorCtor(new RangeError('rangeTypeError')), function (err) { + return err instanceof RangeError && err.message === 'rangeTypeError'; + }); + + if (napiVersion > 8) { + assert.throws(() => binding.error.throwSyntaxErrorCStr('test'), function (err) { + return err instanceof SyntaxError && err.message === 'test'; + }); + + assert.throws(() => binding.error.throwSyntaxError('test'), function (err) { + return err instanceof SyntaxError && err.message === 'test'; + }); + + assert.throws(() => binding.error.throwSyntaxErrorCtor(new SyntaxError('syntaxTypeError')), function (err) { + return err instanceof SyntaxError && err.message === 'syntaxTypeError'; + }); + } + + assert.throws( + () => binding.error.doNotCatch( + () => { + throw new TypeError('test'); + }), + function (err) { + return err instanceof TypeError && err.message === 'test' && !err.caught; + }); + + assert.throws( + () => binding.error.catchAndRethrowError( + () => { + throw new TypeError('test'); + }), + function (err) { + return err instanceof TypeError && err.message === 'test' && err.caught; + }); + + const err = binding.error.catchError( + () => { throw new TypeError('test'); }); + assert(err instanceof TypeError); + assert.strictEqual(err.message, 'test'); + + const msg = binding.error.catchErrorMessage( + () => { throw new TypeError('test'); }); + assert.strictEqual(msg, 'test'); + + assert.throws(() => binding.error.throwErrorThatEscapesScope('test'), function (err) { + return err instanceof Error && err.message === 'test'; + }); + + assert.throws(() => binding.error.catchAndRethrowErrorThatEscapesScope('test'), function (err) { + return err instanceof Error && err.message === 'test' && err.caught; + }); + + const p = require('./napi_child').spawnSync( + process.execPath, [__filename, 'fatal', bindingPath]); + assert.ifError(p.error); + assert.ok(p.stderr.toString().includes( + 'FATAL ERROR: Error::ThrowFatalError This is a fatal error')); + + assert.throws(() => binding.error.throwDefaultError(false), + /Cannot convert undefined or null to object/); + + assert.throws(() => binding.error.throwDefaultError(true), + /A number was expected/); +} diff --git a/test/node-addon-api/test/error_handling_for_primitives.cc b/test/node-addon-api/test/error_handling_for_primitives.cc new file mode 100644 index 0000000..1732932 --- /dev/null +++ b/test/node-addon-api/test/error_handling_for_primitives.cc @@ -0,0 +1,13 @@ +#include + +namespace { +void Test(const Napi::CallbackInfo& info) { + info[0].As().Call({}); +} + +} // namespace +Napi::Object InitErrorHandlingPrim(Napi::Env env) { + Napi::Object exports = Napi::Object::New(env); + exports.Set("errorHandlingPrim", Napi::Function::New(env)); + return exports; +} diff --git a/test/node-addon-api/test/error_handling_for_primitives.js b/test/node-addon-api/test/error_handling_for_primitives.js new file mode 100644 index 0000000..105c2b6 --- /dev/null +++ b/test/node-addon-api/test/error_handling_for_primitives.js @@ -0,0 +1,29 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest((binding) => { + test(binding.errorHandlingPrim); +}); + +function canThrow (binding, errorMessage, errorType) { + try { + binding.errorHandlingPrim(() => { + throw errorMessage; + }); + } catch (e) { + // eslint-disable-next-line valid-typeof + assert(typeof e === errorType); + assert(e === errorMessage); + } +} + +function test (binding) { + canThrow(binding, '404 server not found!', 'string'); + canThrow(binding, 42, 'number'); + canThrow(binding, Symbol.for('newSym'), 'symbol'); + canThrow(binding, false, 'boolean'); + canThrow(binding, BigInt(123), 'bigint'); + canThrow(binding, () => { console.log('Logger shutdown incorrectly'); }, 'function'); + canThrow(binding, { status: 403, errorMsg: 'Not authenticated' }, 'object'); +} diff --git a/test/node-addon-api/test/error_terminating_environment.js b/test/node-addon-api/test/error_terminating_environment.js new file mode 100644 index 0000000..df9e8b9 --- /dev/null +++ b/test/node-addon-api/test/error_terminating_environment.js @@ -0,0 +1,99 @@ +'use strict'; + +const assert = require('assert'); +const { whichBuildType } = require('./common'); + +// These tests ensure that Error types can be used in a terminating +// environment without triggering any fatal errors. + +if (process.argv[2] === 'runInChildProcess') { + const bindingPath = process.argv[3]; + const indexForTestCase = Number(process.argv[4]); + + const binding = require(bindingPath); + + // Use C++ promises to ensure the worker thread is terminated right + // before running the testable code in the binding. + + binding.error.resetPromises(); + + const { Worker } = require('worker_threads'); + + const worker = new Worker( + __filename, + { + argv: [ + 'runInWorkerThread', + bindingPath, + indexForTestCase + ] + } + ); + + binding.error.waitForWorkerThread(); + + worker.terminate(); + + binding.error.releaseWorkerThread(); +} else { + if (process.argv[2] === 'runInWorkerThread') { + const bindingPath = process.argv[3]; + const indexForTestCase = Number(process.argv[4]); + + const binding = require(bindingPath); + + switch (indexForTestCase) { + case 0: + binding.error.throwJSError('test', true); + break; + case 1: + binding.error.throwTypeError('test', true); + break; + case 2: + binding.error.throwRangeError('test', true); + break; + case 3: + binding.error.throwDefaultError(false, true); + break; + case 4: + binding.error.throwDefaultError(true, true); + break; + default: assert.fail('Invalid index'); + } + + assert.fail('This should not be reachable'); + } + + wrapTest(); + + async function wrapTest () { + const buildType = await whichBuildType(); + test(`./build/${buildType}/binding.node`, true); + test(`./build/${buildType}/binding_noexcept.node`, true); + test(`./build/${buildType}/binding_swallowexcept.node`, false); + test(`./build/${buildType}/binding_swallowexcept_noexcept.node`, false); + test(`./build/${buildType}/binding_custom_namespace.node`, true); + } + + function test (bindingPath, processShouldAbort) { + const numberOfTestCases = 5; + + for (let i = 0; i < numberOfTestCases; ++i) { + const childProcess = require('./napi_child').spawnSync( + process.execPath, + [ + __filename, + 'runInChildProcess', + bindingPath, + i + ] + ); + + if (processShouldAbort) { + assert(childProcess.status !== 0, `Test case ${bindingPath} ${i} failed: Process exited with status code 0.`); + } else { + assert(childProcess.status === 0, `Test case ${bindingPath} ${i} failed: Process status ${childProcess.status} is non-zero`); + } + } + } +} diff --git a/test/node-addon-api/test/except_all.cc b/test/node-addon-api/test/except_all.cc new file mode 100644 index 0000000..e2c230b --- /dev/null +++ b/test/node-addon-api/test/except_all.cc @@ -0,0 +1,22 @@ +#include +#include "napi.h" + +using namespace Napi; + +void ThrowStdException(const CallbackInfo& info) { + std::string message = info[0].As().Utf8Value(); + throw std::runtime_error(message); +} + +void ThrowPrimitiveException(const CallbackInfo&) { + throw 0; +} + +Object Init(Env env, Object exports) { + exports.Set("throwStdException", Napi::Function::New(env, ThrowStdException)); + exports.Set("throwPrimitiveException", + Napi::Function::New(env, ThrowPrimitiveException)); + return exports; +} + +NODE_API_MODULE(addon, Init) diff --git a/test/node-addon-api/test/except_all.js b/test/node-addon-api/test/except_all.js new file mode 100644 index 0000000..d650ece --- /dev/null +++ b/test/node-addon-api/test/except_all.js @@ -0,0 +1,14 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTestWithBuildType(test); + +function test (buildType) { + const binding = require(`./build/${buildType}/binding_except_all.node`); + + const message = 'error message'; + assert.throws(binding.throwStdException.bind(undefined, message), { message }); + + assert.throws(binding.throwPrimitiveException.bind(undefined), { message: 'A native exception was thrown' }); +} diff --git a/test/node-addon-api/test/exports.js b/test/node-addon-api/test/exports.js new file mode 100644 index 0000000..1aa3928 --- /dev/null +++ b/test/node-addon-api/test/exports.js @@ -0,0 +1,19 @@ +'use strict'; + +const { strictEqual } = require('assert'); +const { valid } = require('semver'); + +const nodeAddonApi = require('../'); + +module.exports = function test () { + strictEqual(nodeAddonApi.include.startsWith('"'), true); + strictEqual(nodeAddonApi.include.endsWith('"'), true); + strictEqual(nodeAddonApi.include.includes('node-addon-api'), true); + strictEqual(nodeAddonApi.include_dir, ''); + strictEqual(nodeAddonApi.gyp, 'node_api.gyp:nothing'); + strictEqual(nodeAddonApi.targets, 'node_addon_api.gyp'); + strictEqual(valid(nodeAddonApi.version), true); + strictEqual(nodeAddonApi.version, require('../package.json').version); + strictEqual(nodeAddonApi.isNodeApiBuiltin, true); + strictEqual(nodeAddonApi.needsFlag, false); +}; diff --git a/test/node-addon-api/test/external.cc b/test/node-addon-api/test/external.cc new file mode 100644 index 0000000..255b17f --- /dev/null +++ b/test/node-addon-api/test/external.cc @@ -0,0 +1,85 @@ +#include "napi.h" + +using namespace Napi; + +namespace { + +int testData = 1; +int finalizeCount = 0; + +Value CreateExternal(const CallbackInfo& info) { + finalizeCount = 0; + return External::New(info.Env(), &testData); +} + +Value CreateExternalWithFinalize(const CallbackInfo& info) { + finalizeCount = 0; + return External::New(info.Env(), new int(1), [](Env /*env*/, int* data) { + delete data; + finalizeCount++; + }); +} + +Value CreateExternalWithFinalizeHint(const CallbackInfo& info) { + finalizeCount = 0; + char* hint = nullptr; + return External::New( + info.Env(), + new int(1), + [](Env /*env*/, int* data, char* /*hint*/) { + delete data; + finalizeCount++; + }, + hint); +} + +void CheckExternal(const CallbackInfo& info) { + Value arg = info[0]; + if (arg.Type() != napi_external) { + Error::New(info.Env(), "An external argument was expected.") + .ThrowAsJavaScriptException(); + return; + } + + External external = arg.As>(); + int* externalData = external.Data(); + if (externalData == nullptr || *externalData != 1) { + Error::New(info.Env(), "An external value of 1 was expected.") + .ThrowAsJavaScriptException(); + return; + } +} + +Value GetFinalizeCount(const CallbackInfo& info) { + return Number::New(info.Env(), finalizeCount); +} + +Value CreateExternalWithFinalizeException(const CallbackInfo& info) { + return External::New(info.Env(), new int(1), [](Env env, int* data) { + Error error = Error::New(env, "Finalizer exception"); + delete data; +#ifdef NAPI_CPP_EXCEPTIONS + throw error; +#else + error.ThrowAsJavaScriptException(); +#endif + }); +} + +} // end anonymous namespace + +Object InitExternal(Env env) { + Object exports = Object::New(env); + + exports["createExternal"] = Function::New(env, CreateExternal); + exports["createExternalWithFinalize"] = + Function::New(env, CreateExternalWithFinalize); + exports["createExternalWithFinalizeException"] = + Function::New(env, CreateExternalWithFinalizeException); + exports["createExternalWithFinalizeHint"] = + Function::New(env, CreateExternalWithFinalizeHint); + exports["checkExternal"] = Function::New(env, CheckExternal); + exports["getFinalizeCount"] = Function::New(env, GetFinalizeCount); + + return exports; +} diff --git a/test/node-addon-api/test/external.js b/test/node-addon-api/test/external.js new file mode 100644 index 0000000..e395ad1 --- /dev/null +++ b/test/node-addon-api/test/external.js @@ -0,0 +1,85 @@ +'use strict'; + +const assert = require('assert'); +const { spawnSync } = require('child_process'); +const testUtil = require('./testUtil'); + +if (process.argv.length === 3) { + let interval; + + // Running as the child process, hook up an `uncaughtException` handler to + // examine the error thrown by the finalizer. + process.on('uncaughtException', (error) => { + // TODO (gabrielschulhof): Use assert.matches() when we drop support for + // Node.js v10.x. + assert(!!error.message.match(/Finalizer exception/)); + if (interval) { + clearInterval(interval); + } + process.exit(0); + }); + + // Create an external whose finalizer throws. + (() => + require(process.argv[2]).external.createExternalWithFinalizeException())(); + + // gc until the external's finalizer throws or until we give up. Since the + // exception is thrown from a native `SetImmediate()` we cannot catch it + // anywhere except in the process' `uncaughtException` handler. + let maxGCTries = 10; + (function gcInterval () { + global.gc(); + if (!interval) { + interval = setInterval(gcInterval, 100); + } else if (--maxGCTries === 0) { + throw new Error('Timed out waiting for the gc to throw'); + } + })(); +} else { + module.exports = require('./common').runTestWithBindingPath(test); + + function test (bindingPath) { + const binding = require(bindingPath); + + const child = spawnSync(process.execPath, [ + '--expose-gc', __filename, bindingPath + ], { stdio: 'inherit' }); + assert.strictEqual(child.status, 0); + assert.strictEqual(child.signal, null); + + return testUtil.runGCTests([ + 'External without finalizer', + () => { + const test = binding.external.createExternal(); + assert.strictEqual(typeof test, 'object'); + binding.external.checkExternal(test); + assert.strictEqual(0, binding.external.getFinalizeCount()); + }, + () => { + assert.strictEqual(0, binding.external.getFinalizeCount()); + }, + + 'External with finalizer', + () => { + const test = binding.external.createExternalWithFinalize(); + assert.strictEqual(typeof test, 'object'); + binding.external.checkExternal(test); + assert.strictEqual(0, binding.external.getFinalizeCount()); + }, + () => { + assert.strictEqual(1, binding.external.getFinalizeCount()); + }, + + 'External with finalizer hint', + () => { + const test = binding.external.createExternalWithFinalizeHint(); + assert.strictEqual(typeof test, 'object'); + binding.external.checkExternal(test); + assert.strictEqual(0, binding.external.getFinalizeCount()); + }, + () => { + assert.strictEqual(1, binding.external.getFinalizeCount()); + } + ]); + } +} diff --git a/test/node-addon-api/test/finalizer_order.cc b/test/node-addon-api/test/finalizer_order.cc new file mode 100644 index 0000000..0767ced --- /dev/null +++ b/test/node-addon-api/test/finalizer_order.cc @@ -0,0 +1,152 @@ +#include + +namespace { +class Test : public Napi::ObjectWrap { + public: + Test(const Napi::CallbackInfo& info) : Napi::ObjectWrap(info) { + basicFinalizerCalled = false; + finalizerCalled = false; + + if (info.Length() > 0) { + finalizeCb_ = Napi::Persistent(info[0].As()); + } + } + + static void Initialize(Napi::Env env, Napi::Object exports) { + exports.Set("Test", + DefineClass(env, + "Test", + { + StaticAccessor("isBasicFinalizerCalled", + &IsBasicFinalizerCalled, + nullptr, + napi_default), + StaticAccessor("isFinalizerCalled", + &IsFinalizerCalled, + nullptr, + napi_default), + })); + } + + void Finalize(Napi::BasicEnv /*env*/) { basicFinalizerCalled = true; } + + void Finalize(Napi::Env /*env*/) { + finalizerCalled = true; + if (!finalizeCb_.IsEmpty()) { + finalizeCb_.Call({}); + } + } + + static Napi::Value IsBasicFinalizerCalled(const Napi::CallbackInfo& info) { + return Napi::Boolean::New(info.Env(), basicFinalizerCalled); + } + + static Napi::Value IsFinalizerCalled(const Napi::CallbackInfo& info) { + return Napi::Boolean::New(info.Env(), finalizerCalled); + } + + private: + Napi::FunctionReference finalizeCb_; + + static bool basicFinalizerCalled; + static bool finalizerCalled; +}; + +bool Test::basicFinalizerCalled = false; +bool Test::finalizerCalled = false; + +bool externalBasicFinalizerCalled = false; +bool externalFinalizerCalled = false; + +Napi::Value CreateExternalBasicFinalizer(const Napi::CallbackInfo& info) { + externalBasicFinalizerCalled = false; + return Napi::External::New( + info.Env(), new int(1), [](Napi::BasicEnv /*env*/, int* data) { + externalBasicFinalizerCalled = true; + delete data; + }); +} + +Napi::Value CreateExternalFinalizer(const Napi::CallbackInfo& info) { + externalFinalizerCalled = false; + return Napi::External::New( + info.Env(), new int(1), [](Napi::Env /*env*/, int* data) { + externalFinalizerCalled = true; + delete data; + }); +} + +Napi::Value isExternalBasicFinalizerCalled(const Napi::CallbackInfo& info) { + return Napi::Boolean::New(info.Env(), externalBasicFinalizerCalled); +} + +Napi::Value IsExternalFinalizerCalled(const Napi::CallbackInfo& info) { + return Napi::Boolean::New(info.Env(), externalFinalizerCalled); +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER +Napi::Value PostFinalizer(const Napi::CallbackInfo& info) { + auto env = info.Env(); + + env.PostFinalizer([callback = Napi::Persistent(info[0].As())]( + Napi::Env /*env*/) { callback.Call({}); }); + + return env.Undefined(); +} + +Napi::Value PostFinalizerWithData(const Napi::CallbackInfo& info) { + auto env = info.Env(); + + env.PostFinalizer( + [callback = Napi::Persistent(info[0].As())]( + Napi::Env /*env*/, Napi::Reference* data) { + callback.Call({data->Value()}); + delete data; + }, + new Napi::Reference(Napi::Persistent(info[1]))); + + return env.Undefined(); +} + +Napi::Value PostFinalizerWithDataAndHint(const Napi::CallbackInfo& info) { + auto env = info.Env(); + + env.PostFinalizer( + [callback = Napi::Persistent(info[0].As())]( + Napi::Env /*env*/, + Napi::Reference* data, + Napi::Reference* hint) { + callback.Call({data->Value(), hint->Value()}); + delete data; + delete hint; + }, + new Napi::Reference(Napi::Persistent(info[1])), + new Napi::Reference(Napi::Persistent(info[2]))); + + return env.Undefined(); +} +#endif + +} // namespace + +Napi::Object InitFinalizerOrder(Napi::Env env) { + Napi::Object exports = Napi::Object::New(env); + Test::Initialize(env, exports); + exports["createExternalBasicFinalizer"] = + Napi::Function::New(env, CreateExternalBasicFinalizer); + exports["createExternalFinalizer"] = + Napi::Function::New(env, CreateExternalFinalizer); + exports["isExternalBasicFinalizerCalled"] = + Napi::Function::New(env, isExternalBasicFinalizerCalled); + exports["isExternalFinalizerCalled"] = + Napi::Function::New(env, IsExternalFinalizerCalled); + +#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER + exports["PostFinalizer"] = Napi::Function::New(env, PostFinalizer); + exports["PostFinalizerWithData"] = + Napi::Function::New(env, PostFinalizerWithData); + exports["PostFinalizerWithDataAndHint"] = + Napi::Function::New(env, PostFinalizerWithDataAndHint); +#endif + return exports; +} diff --git a/test/node-addon-api/test/finalizer_order.js b/test/node-addon-api/test/finalizer_order.js new file mode 100644 index 0000000..4b267a0 --- /dev/null +++ b/test/node-addon-api/test/finalizer_order.js @@ -0,0 +1,98 @@ +'use strict'; + +/* eslint-disable no-unused-vars */ + +const assert = require('assert'); +const common = require('./common'); +const testUtil = require('./testUtil'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + const { isExperimental } = binding; + + let isCallbackCalled = false; + + const tests = [ + 'Finalizer Order - ObjectWrap', + () => { + let test = new binding.finalizer_order.Test(() => { isCallbackCalled = true; }); + test = null; + + global.gc(); + + if (isExperimental) { + assert.strictEqual(binding.finalizer_order.Test.isBasicFinalizerCalled, true, 'Expected basic finalizer to be called [before ticking]'); + assert.strictEqual(binding.finalizer_order.Test.isFinalizerCalled, false, 'Expected (extended) finalizer to not be called [before ticking]'); + assert.strictEqual(isCallbackCalled, false, 'Expected callback to not be called [before ticking]'); + } else { + assert.strictEqual(binding.finalizer_order.Test.isBasicFinalizerCalled, false, 'Expected basic finalizer to not be called [before ticking]'); + assert.strictEqual(binding.finalizer_order.Test.isFinalizerCalled, false, 'Expected (extended) finalizer to not be called [before ticking]'); + assert.strictEqual(isCallbackCalled, false, 'Expected callback to not be called [before ticking]'); + } + }, + () => { + assert.strictEqual(binding.finalizer_order.Test.isBasicFinalizerCalled, true, 'Expected basic finalizer to be called [after ticking]'); + assert.strictEqual(binding.finalizer_order.Test.isFinalizerCalled, true, 'Expected (extended) finalizer to be called [after ticking]'); + assert.strictEqual(isCallbackCalled, true, 'Expected callback to be called [after ticking]'); + }, + + 'Finalizer Order - External with Basic Finalizer', + () => { + let ext = binding.finalizer_order.createExternalBasicFinalizer(); + ext = null; + global.gc(); + + if (isExperimental) { + assert.strictEqual(binding.finalizer_order.isExternalBasicFinalizerCalled(), true, 'Expected External basic finalizer to be called [before ticking]'); + } else { + assert.strictEqual(binding.finalizer_order.isExternalBasicFinalizerCalled(), false, 'Expected External basic finalizer to not be called [before ticking]'); + } + }, + () => { + assert.strictEqual(binding.finalizer_order.isExternalBasicFinalizerCalled(), true, 'Expected External basic finalizer to be called [after ticking]'); + }, + + 'Finalizer Order - External with Finalizer', + () => { + let ext = binding.finalizer_order.createExternalFinalizer(); + ext = null; + global.gc(); + assert.strictEqual(binding.finalizer_order.isExternalFinalizerCalled(), false, 'Expected External extended finalizer to not be called [before ticking]'); + }, + () => { + assert.strictEqual(binding.finalizer_order.isExternalFinalizerCalled(), true, 'Expected External extended finalizer to be called [after ticking]'); + } + ]; + + if (binding.isExperimental) { + tests.push(...[ + 'PostFinalizer', + () => { + binding.finalizer_order.PostFinalizer(common.mustCall()); + }, + + 'PostFinalizerWithData', + () => { + const data = {}; + const callback = (callbackData) => { + assert.strictEqual(callbackData, data); + }; + binding.finalizer_order.PostFinalizerWithData(common.mustCall(callback), data); + }, + + 'PostFinalizerWithDataAndHint', + () => { + const data = {}; + const hint = {}; + const callback = (callbackData, callbackHint) => { + assert.strictEqual(callbackData, data); + assert.strictEqual(callbackHint, hint); + }; + binding.finalizer_order.PostFinalizerWithDataAndHint(common.mustCall(callback), data, hint); + } + ]); + } + + return testUtil.runGCTests(tests); +} diff --git a/test/node-addon-api/test/function.cc b/test/node-addon-api/test/function.cc new file mode 100644 index 0000000..5c1c6e1 --- /dev/null +++ b/test/node-addon-api/test/function.cc @@ -0,0 +1,338 @@ +#include +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +namespace { + +int testData = 1; + +Boolean EmptyConstructor(const CallbackInfo& info) { + auto env = info.Env(); + bool isEmpty = info[0].As(); + Function function = isEmpty ? Function() : Function(env, Object::New(env)); + return Boolean::New(env, function.IsEmpty()); +} + +void VoidCallback(const CallbackInfo& info) { + auto env = info.Env(); + Object obj = info[0].As(); + + obj["foo"] = String::New(env, "bar"); +} + +Value ValueCallback(const CallbackInfo& info) { + auto env = info.Env(); + Object obj = Object::New(env); + + obj["foo"] = String::New(env, "bar"); + + return obj; +} + +void VoidCallbackWithData(const CallbackInfo& info) { + auto env = info.Env(); + Object obj = info[0].As(); + + obj["foo"] = String::New(env, "bar"); + + int* data = static_cast(info.Data()); + obj["data"] = Number::New(env, *data); +} + +Value ValueCallbackWithData(const CallbackInfo& info) { + auto env = info.Env(); + Object obj = Object::New(env); + + obj["foo"] = String::New(env, "bar"); + + int* data = static_cast(info.Data()); + obj["data"] = Number::New(env, *data); + + return obj; +} + +Value CallWithArgs(const CallbackInfo& info) { + Function func = info[0].As(); + return MaybeUnwrap( + func.Call(std::initializer_list{info[1], info[2], info[3]})); +} + +Value CallWithVector(const CallbackInfo& info) { + Function func = info[0].As(); + std::vector args; + args.reserve(3); + args.push_back(info[1]); + args.push_back(info[2]); + args.push_back(info[3]); + return MaybeUnwrap(func.Call(args)); +} + +Value CallWithVectorUsingCppWrapper(const CallbackInfo& info) { + Function func = info[0].As(); + std::vector args; + args.reserve(3); + args.push_back(info[1]); + args.push_back(info[2]); + args.push_back(info[3]); + return MaybeUnwrap(func.Call(args)); +} + +Value CallWithCStyleArray(const CallbackInfo& info) { + Function func = info[0].As(); + std::vector args; + args.reserve(3); + args.push_back(info[1]); + args.push_back(info[2]); + args.push_back(info[3]); + return MaybeUnwrap(func.Call(args.size(), args.data())); +} + +Value CallWithReceiverAndCStyleArray(const CallbackInfo& info) { + Function func = info[0].As(); + Value receiver = info[1]; + std::vector args; + args.reserve(3); + args.push_back(info[2]); + args.push_back(info[3]); + args.push_back(info[4]); + return MaybeUnwrap(func.Call(receiver, args.size(), args.data())); +} + +Value CallWithReceiverAndArgs(const CallbackInfo& info) { + Function func = info[0].As(); + Value receiver = info[1]; + return MaybeUnwrap(func.Call( + receiver, std::initializer_list{info[2], info[3], info[4]})); +} + +Value CallWithReceiverAndVector(const CallbackInfo& info) { + Function func = info[0].As(); + Value receiver = info[1]; + std::vector args; + args.reserve(3); + args.push_back(info[2]); + args.push_back(info[3]); + args.push_back(info[4]); + return MaybeUnwrap(func.Call(receiver, args)); +} + +Value CallWithReceiverAndVectorUsingCppWrapper(const CallbackInfo& info) { + Function func = info[0].As(); + Value receiver = info[1]; + std::vector args; + args.reserve(3); + args.push_back(info[2]); + args.push_back(info[3]); + args.push_back(info[4]); + return MaybeUnwrap(func.Call(receiver, args)); +} + +Value CallWithInvalidReceiver(const CallbackInfo& info) { + Function func = info[0].As(); + return MaybeUnwrapOr(func.Call(Value(), std::initializer_list{}), + Value()); +} + +Value CallConstructorWithArgs(const CallbackInfo& info) { + Function func = info[0].As(); + return MaybeUnwrap( + func.New(std::initializer_list{info[1], info[2], info[3]})); +} + +Value CallConstructorWithVector(const CallbackInfo& info) { + Function func = info[0].As(); + std::vector args; + args.reserve(3); + args.push_back(info[1]); + args.push_back(info[2]); + args.push_back(info[3]); + return MaybeUnwrap(func.New(args)); +} + +Value CallConstructorWithCStyleArray(const CallbackInfo& info) { + Function func = info[0].As(); + std::vector args; + args.reserve(3); + args.push_back(info[1]); + args.push_back(info[2]); + args.push_back(info[3]); + return MaybeUnwrap(func.New(args.size(), args.data())); +} + +void IsConstructCall(const CallbackInfo& info) { + Function callback = info[0].As(); + bool isConstructCall = info.IsConstructCall(); + callback({Napi::Boolean::New(info.Env(), isConstructCall)}); +} + +Value NewTargetCallback(const CallbackInfo& info) { + return info.NewTarget(); +} + +void MakeCallbackWithArgs(const CallbackInfo& info) { + Env env = info.Env(); + Function callback = info[0].As(); + Object resource = info[1].As(); + + AsyncContext context(env, "function_test_context", resource); + + callback.MakeCallback( + resource, + std::initializer_list{info[2], info[3], info[4]}, + context); +} + +void MakeCallbackWithVector(const CallbackInfo& info) { + Env env = info.Env(); + Function callback = info[0].As(); + Object resource = info[1].As(); + + AsyncContext context(env, "function_test_context", resource); + + std::vector args; + args.reserve(3); + args.push_back(info[2]); + args.push_back(info[3]); + args.push_back(info[4]); + callback.MakeCallback(resource, args, context); +} + +void MakeCallbackWithCStyleArray(const CallbackInfo& info) { + Env env = info.Env(); + Function callback = info[0].As(); + Object resource = info[1].As(); + + AsyncContext context(env, "function_test_context", resource); + + std::vector args; + args.reserve(3); + args.push_back(info[2]); + args.push_back(info[3]); + args.push_back(info[4]); + callback.MakeCallback(resource, args.size(), args.data(), context); +} + +void MakeCallbackWithInvalidReceiver(const CallbackInfo& info) { + Function callback = info[0].As(); + callback.MakeCallback(Value(), std::initializer_list{}); +} + +Value CallWithFunctionOperator(const CallbackInfo& info) { + Function func = info[0].As(); + return MaybeUnwrap(func({info[1], info[2], info[3]})); +} + +} // end anonymous namespace + +Object InitFunction(Env env) { + Object result = Object::New(env); + Object exports = Object::New(env); + exports["emptyConstructor"] = Function::New(env, EmptyConstructor); + exports["voidCallback"] = Function::New(env, VoidCallback, "voidCallback"); + exports["valueCallback"] = + Function::New(env, ValueCallback, std::string("valueCallback")); + exports["voidCallbackWithData"] = + Function::New(env, VoidCallbackWithData, nullptr, &testData); + exports["valueCallbackWithData"] = + Function::New(env, ValueCallbackWithData, nullptr, &testData); + exports["newTargetCallback"] = + Function::New(env, NewTargetCallback, std::string("newTargetCallback")); + exports["callWithArgs"] = Function::New(env, CallWithArgs); + exports["callWithVector"] = Function::New(env, CallWithVector); + exports["callWithVectorUsingCppWrapper"] = + Function::New(env, CallWithVectorUsingCppWrapper); + exports["callWithCStyleArray"] = Function::New(env, CallWithCStyleArray); + exports["callWithReceiverAndCStyleArray"] = + Function::New(env, CallWithReceiverAndCStyleArray); + exports["callWithReceiverAndArgs"] = + Function::New(env, CallWithReceiverAndArgs); + exports["callWithReceiverAndVector"] = + Function::New(env, CallWithReceiverAndVector); + exports["callWithReceiverAndVectorUsingCppWrapper"] = + Function::New(env, CallWithReceiverAndVectorUsingCppWrapper); + exports["callWithInvalidReceiver"] = + Function::New(env, CallWithInvalidReceiver); + exports["callConstructorWithArgs"] = + Function::New(env, CallConstructorWithArgs); + exports["callConstructorWithVector"] = + Function::New(env, CallConstructorWithVector); + exports["callConstructorWithCStyleArray"] = + Function::New(env, CallConstructorWithCStyleArray); + exports["isConstructCall"] = Function::New(env, IsConstructCall); + exports["makeCallbackWithArgs"] = Function::New(env, MakeCallbackWithArgs); + exports["makeCallbackWithVector"] = + Function::New(env, MakeCallbackWithVector); + exports["makeCallbackWithCStyleArray"] = + Function::New(env, MakeCallbackWithCStyleArray); + exports["makeCallbackWithInvalidReceiver"] = + Function::New(env, MakeCallbackWithInvalidReceiver); + exports["callWithFunctionOperator"] = + Function::New(env, CallWithFunctionOperator); + result["plain"] = exports; + + exports = Object::New(env); + exports["emptyConstructor"] = Function::New(env, EmptyConstructor); + exports["voidCallback"] = Function::New(env, "voidCallback"); + exports["valueCallback"] = + Function::New(env, std::string("valueCallback")); + exports["newTargetCallback"] = + Function::New(env, std::string("newTargetCallback")); + exports["voidCallbackWithData"] = + Function::New(env, nullptr, &testData); + exports["valueCallbackWithData"] = + Function::New(env, nullptr, &testData); + exports["callWithArgs"] = Function::New(env); + exports["callWithVector"] = Function::New(env); + exports["callWithVectorUsingCppWrapper"] = + Function::New(env); + exports["callWithCStyleArray"] = Function::New(env); + exports["callWithReceiverAndCStyleArray"] = + Function::New(env); + exports["callWithReceiverAndArgs"] = + Function::New(env); + exports["callWithReceiverAndVector"] = + Function::New(env); + exports["callWithReceiverAndVectorUsingCppWrapper"] = + Function::New(env); + exports["callWithInvalidReceiver"] = + Function::New(env); + exports["callConstructorWithArgs"] = + Function::New(env); + exports["callConstructorWithVector"] = + Function::New(env); + exports["callConstructorWithCStyleArray"] = + Function::New(env); + exports["isConstructCall"] = Function::New(env); + exports["makeCallbackWithArgs"] = Function::New(env); + exports["makeCallbackWithVector"] = + Function::New(env); + exports["makeCallbackWithCStyleArray"] = + Function::New(env); + exports["makeCallbackWithInvalidReceiver"] = + Function::New(env); + exports["callWithFunctionOperator"] = + Function::New(env); + result["templated"] = exports; + + exports = Object::New(env); + exports["lambdaWithNoCapture"] = + Function::New(env, [](const CallbackInfo& info) { + auto env = info.Env(); + return Boolean::New(env, true); + }); + exports["lambdaWithCapture"] = + Function::New(env, [data = 42](const CallbackInfo& info) { + auto env = info.Env(); + return Boolean::New(env, data == 42); + }); + exports["lambdaWithMoveOnlyCapture"] = Function::New( + env, [data = std::make_unique(42)](const CallbackInfo& info) { + auto env = info.Env(); + return Boolean::New(env, *data == 42); + }); + result["lambda"] = exports; + + return result; +} diff --git a/test/node-addon-api/test/function.js b/test/node-addon-api/test/function.js new file mode 100644 index 0000000..c5514db --- /dev/null +++ b/test/node-addon-api/test/function.js @@ -0,0 +1,137 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(binding => { + test(binding.function.plain); + test(binding.function.templated); + testLambda(binding.function.lambda); +}); + +function test (binding) { + assert.strictEqual(binding.emptyConstructor(true), true); + assert.strictEqual(binding.emptyConstructor(false), false); + + let obj = {}; + assert.deepStrictEqual(binding.voidCallback(obj), undefined); + assert.deepStrictEqual(obj, { foo: 'bar' }); + + assert.deepStrictEqual(binding.valueCallback(), { foo: 'bar' }); + + /* eslint-disable-next-line new-cap */ + assert.strictEqual(new binding.newTargetCallback(), binding.newTargetCallback); + assert.strictEqual(binding.newTargetCallback(), undefined); + + let args = null; + let ret = null; + let receiver = null; + function testFunction () { + receiver = this; + args = [].slice.call(arguments); + return ret; + } + function testConstructor () { + args = [].slice.call(arguments); + } + + function makeCallbackTestFunction (receiver, expectedOne, expectedTwo, expectedThree) { + return function callback (one, two, three) { + assert.strictEqual(this, receiver); + assert.strictEqual(one, expectedOne); + assert.strictEqual(two, expectedTwo); + assert.strictEqual(three, expectedThree); + }; + } + + ret = 4; + assert.strictEqual(binding.callWithArgs(testFunction, 1, 2, 3), 4); + assert.strictEqual(receiver, undefined); + assert.deepStrictEqual(args, [1, 2, 3]); + + ret = 5; + assert.strictEqual(binding.callWithVector(testFunction, 2, 3, 4), 5); + assert.strictEqual(receiver, undefined); + assert.deepStrictEqual(args, [2, 3, 4]); + + ret = 5; + assert.strictEqual(binding.callWithVectorUsingCppWrapper(testFunction, 2, 3, 4), 5); + assert.strictEqual(receiver, undefined); + assert.deepStrictEqual(args, [2, 3, 4]); + + ret = 6; + assert.strictEqual(binding.callWithReceiverAndArgs(testFunction, obj, 3, 4, 5), 6); + assert.deepStrictEqual(receiver, obj); + assert.deepStrictEqual(args, [3, 4, 5]); + + ret = 7; + assert.strictEqual(binding.callWithReceiverAndVector(testFunction, obj, 4, 5, 6), 7); + assert.deepStrictEqual(receiver, obj); + assert.deepStrictEqual(args, [4, 5, 6]); + + ret = 7; + assert.strictEqual(binding.callWithReceiverAndVectorUsingCppWrapper(testFunction, obj, 4, 5, 6), 7); + assert.deepStrictEqual(receiver, obj); + assert.deepStrictEqual(args, [4, 5, 6]); + + ret = 8; + assert.strictEqual(binding.callWithCStyleArray(testFunction, 5, 6, 7), ret); + assert.deepStrictEqual(receiver, undefined); + assert.deepStrictEqual(args, [5, 6, 7]); + + ret = 9; + assert.strictEqual(binding.callWithReceiverAndCStyleArray(testFunction, obj, 6, 7, 8), ret); + assert.deepStrictEqual(receiver, obj); + assert.deepStrictEqual(args, [6, 7, 8]); + + ret = 10; + assert.strictEqual(binding.callWithFunctionOperator(testFunction, 7, 8, 9), ret); + assert.strictEqual(receiver, undefined); + assert.deepStrictEqual(args, [7, 8, 9]); + + assert.throws(() => { + binding.callWithInvalidReceiver(() => {}); + }, /Invalid (pointer passed as )?argument/); + + obj = binding.callConstructorWithArgs(testConstructor, 5, 6, 7); + assert(obj instanceof testConstructor); + assert.deepStrictEqual(args, [5, 6, 7]); + + obj = binding.callConstructorWithVector(testConstructor, 6, 7, 8); + assert(obj instanceof testConstructor); + assert.deepStrictEqual(args, [6, 7, 8]); + + obj = binding.callConstructorWithCStyleArray(testConstructor, 7, 8, 9); + assert(obj instanceof testConstructor); + assert.deepStrictEqual(args, [7, 8, 9]); + + obj = {}; + assert.deepStrictEqual(binding.voidCallbackWithData(obj), undefined); + assert.deepStrictEqual(obj, { foo: 'bar', data: 1 }); + + assert.deepStrictEqual(binding.valueCallbackWithData(), { foo: 'bar', data: 1 }); + + assert.strictEqual(binding.voidCallback.name, 'voidCallback'); + assert.strictEqual(binding.valueCallback.name, 'valueCallback'); + + let testConstructCall; + binding.isConstructCall((result) => { testConstructCall = result; }); + assert.ok(!testConstructCall); + /* eslint-disable no-new, new-cap */ + new binding.isConstructCall((result) => { testConstructCall = result; }); + /* eslint-enable no-new, new-cap */ + assert.ok(testConstructCall); + + obj = {}; + binding.makeCallbackWithArgs(makeCallbackTestFunction(obj, '1', '2', '3'), obj, '1', '2', '3'); + binding.makeCallbackWithVector(makeCallbackTestFunction(obj, 4, 5, 6), obj, 4, 5, 6); + binding.makeCallbackWithCStyleArray(makeCallbackTestFunction(obj, 7, 8, 9), obj, 7, 8, 9); + assert.throws(() => { + binding.makeCallbackWithInvalidReceiver(() => {}); + }); +} + +function testLambda (binding) { + assert.ok(binding.lambdaWithNoCapture()); + assert.ok(binding.lambdaWithCapture()); + assert.ok(binding.lambdaWithMoveOnlyCapture()); +} diff --git a/test/node-addon-api/test/function_reference.cc b/test/node-addon-api/test/function_reference.cc new file mode 100644 index 0000000..b50eb46 --- /dev/null +++ b/test/node-addon-api/test/function_reference.cc @@ -0,0 +1,205 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +class FuncRefObject : public Napi::ObjectWrap { + public: + FuncRefObject(const Napi::CallbackInfo& info) + : Napi::ObjectWrap(info) { + Napi::Env env = info.Env(); + int argLen = info.Length(); + if (argLen <= 0 || !info[0].IsNumber()) { + Napi::TypeError::New(env, "First param should be a number") + .ThrowAsJavaScriptException(); + return; + } + Napi::Number value = info[0].As(); + this->_value = value.Int32Value(); + } + + Napi::Value GetValue(const Napi::CallbackInfo& info) { + int value = this->_value; + return Napi::Number::New(info.Env(), value); + } + + private: + int _value; +}; + +namespace { + +Value ConstructRefFromExisitingRef(const CallbackInfo& info) { + EscapableHandleScope scope(info.Env()); + FunctionReference ref; + FunctionReference movedRef; + ref.Reset(info[0].As()); + movedRef = std::move(ref); + + return scope.Escape(MaybeUnwrap(movedRef({}))); +} + +Value CallWithVectorArgs(const CallbackInfo& info) { + EscapableHandleScope scope(info.Env()); + std::vector newVec; + FunctionReference ref; + ref.Reset(info[0].As()); + + for (int i = 1; i < (int)info.Length(); i++) { + newVec.push_back(info[i]); + } + return scope.Escape(MaybeUnwrap(ref.Call(newVec))); +} + +Value CallWithInitList(const CallbackInfo& info) { + EscapableHandleScope scope(info.Env()); + FunctionReference ref; + ref.Reset(info[0].As()); + + return scope.Escape(MaybeUnwrap(ref.Call({info[1], info[2], info[3]}))); +} + +Value CallWithRecvInitList(const CallbackInfo& info) { + EscapableHandleScope scope(info.Env()); + FunctionReference ref; + ref.Reset(info[0].As()); + + return scope.Escape( + MaybeUnwrap(ref.Call(info[1], {info[2], info[3], info[4]}))); +} + +Value CallWithRecvVector(const CallbackInfo& info) { + EscapableHandleScope scope(info.Env()); + FunctionReference ref; + std::vector newVec; + ref.Reset(info[0].As()); + + for (int i = 2; i < (int)info.Length(); i++) { + newVec.push_back(info[i]); + } + return scope.Escape(MaybeUnwrap(ref.Call(info[1], newVec))); +} + +Value CallWithRecvArgc(const CallbackInfo& info) { + EscapableHandleScope scope(info.Env()); + FunctionReference ref; + ref.Reset(info[0].As()); + + size_t argLength = info.Length() > 2 ? info.Length() - 2 : 0; + std::unique_ptr args{argLength > 0 ? new napi_value[argLength] + : nullptr}; + for (size_t i = 0; i < argLength; ++i) { + args[i] = info[i + 2]; + } + + return scope.Escape(MaybeUnwrap(ref.Call(info[1], argLength, args.get()))); +} + +Value MakeAsyncCallbackWithInitList(const Napi::CallbackInfo& info) { + Napi::FunctionReference ref; + ref.Reset(info[0].As()); + + Napi::AsyncContext context(info.Env(), "func_ref_resources", {}); + + return MaybeUnwrap( + ref.MakeCallback(Napi::Object::New(info.Env()), {}, context)); +} + +Value MakeAsyncCallbackWithVector(const Napi::CallbackInfo& info) { + Napi::FunctionReference ref; + ref.Reset(info[0].As()); + std::vector newVec; + Napi::AsyncContext context(info.Env(), "func_ref_resources", {}); + + for (int i = 1; i < (int)info.Length(); i++) { + newVec.push_back(info[i]); + } + + return MaybeUnwrap( + ref.MakeCallback(Napi::Object::New(info.Env()), newVec, context)); +} + +Value MakeAsyncCallbackWithArgv(const Napi::CallbackInfo& info) { + Napi::FunctionReference ref; + ref.Reset(info[0].As()); + + size_t argLength = info.Length() > 1 ? info.Length() - 1 : 0; + std::unique_ptr args{argLength > 0 ? new napi_value[argLength] + : nullptr}; + for (size_t i = 0; i < argLength; ++i) { + args[i] = info[i + 1]; + } + + Napi::AsyncContext context(info.Env(), "func_ref_resources", {}); + return MaybeUnwrap(ref.MakeCallback(Napi::Object::New(info.Env()), + argLength, + argLength > 0 ? args.get() : nullptr, + context)); +} + +Value CreateFunctionReferenceUsingNew(const Napi::CallbackInfo& info) { + Napi::Function func = ObjectWrap::DefineClass( + info.Env(), + "MyObject", + {ObjectWrap::InstanceMethod("getValue", + &FuncRefObject::GetValue)}); + Napi::FunctionReference* constructor = new Napi::FunctionReference(); + *constructor = Napi::Persistent(func); + + return MaybeUnwrapOr(constructor->New({info[0].As()}), Object()); +} + +Value CreateFunctionReferenceUsingNewVec(const Napi::CallbackInfo& info) { + Napi::Function func = ObjectWrap::DefineClass( + info.Env(), + "MyObject", + {ObjectWrap::InstanceMethod("getValue", + &FuncRefObject::GetValue)}); + Napi::FunctionReference* constructor = new Napi::FunctionReference(); + *constructor = Napi::Persistent(func); + std::vector newVec; + newVec.push_back(info[0]); + + return MaybeUnwrapOr(constructor->New(newVec), Object()); +} + +Value Call(const CallbackInfo& info) { + EscapableHandleScope scope(info.Env()); + FunctionReference ref; + ref.Reset(info[0].As()); + + return scope.Escape(MaybeUnwrapOr(ref.Call({}), Value())); +} + +Value Construct(const CallbackInfo& info) { + EscapableHandleScope scope(info.Env()); + FunctionReference ref; + ref.Reset(info[0].As()); + + return scope.Escape(MaybeUnwrapOr(ref.New({}), Object())); +} +} // namespace + +Object InitFunctionReference(Env env) { + Object exports = Object::New(env); + exports["CreateFuncRefWithNew"] = + Function::New(env, CreateFunctionReferenceUsingNew); + exports["CreateFuncRefWithNewVec"] = + Function::New(env, CreateFunctionReferenceUsingNewVec); + exports["CallWithRecvArgc"] = Function::New(env, CallWithRecvArgc); + exports["CallWithRecvVector"] = Function::New(env, CallWithRecvVector); + exports["CallWithRecvInitList"] = Function::New(env, CallWithRecvInitList); + exports["CallWithInitList"] = Function::New(env, CallWithInitList); + exports["CallWithVec"] = Function::New(env, CallWithVectorArgs); + exports["ConstructWithMove"] = + Function::New(env, ConstructRefFromExisitingRef); + exports["AsyncCallWithInitList"] = + Function::New(env, MakeAsyncCallbackWithInitList); + exports["AsyncCallWithVector"] = + Function::New(env, MakeAsyncCallbackWithVector); + exports["AsyncCallWithArgv"] = Function::New(env, MakeAsyncCallbackWithArgv); + exports["call"] = Function::New(env, Call); + exports["construct"] = Function::New(env, Construct); + + return exports; +} diff --git a/test/node-addon-api/test/function_reference.js b/test/node-addon-api/test/function_reference.js new file mode 100644 index 0000000..7824ab9 --- /dev/null +++ b/test/node-addon-api/test/function_reference.js @@ -0,0 +1,156 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(async (binding) => { + await test(binding.functionreference); +}); + +function installAsyncHook () { + let id; + let destroyed; + let hook; + const events = []; + return new Promise((resolve, reject) => { + const interval = setInterval(() => { + if (destroyed) { + hook.disable(); + clearInterval(interval); + resolve(events); + } + }, 10); + + hook = asyncHook + .createHook({ + init (asyncId, type, triggerAsyncId, resource) { + if (id === undefined && type === 'func_ref_resources') { + id = asyncId; + events.push({ eventName: 'init', type, triggerAsyncId, resource }); + } + }, + before (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'before' }); + } + }, + after (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'after' }); + } + }, + destroy (asyncId) { + if (asyncId === id) { + events.push({ eventName: 'destroy' }); + destroyed = true; + } + } + }) + .enable(); + }); +} + +function canConstructRefFromExistingRef (binding) { + const testFunc = () => 240; + assert(binding.ConstructWithMove(testFunc) === 240); +} + +function canCallFunctionWithDifferentOverloads (binding) { + let outsideRef = {}; + const testFunc = (a, b) => a * a - b * b; + const testFuncB = (a, b, c) => a + b - c * c; + const testFuncC = (a, b, c) => { + outsideRef.a = a; + outsideRef.b = b; + outsideRef.c = c; + }; + const testFuncD = (a, b, c, d) => { + outsideRef.result = a + b * c - d; + return outsideRef.result; + }; + + assert(binding.CallWithVec(testFunc, 5, 4) === testFunc(5, 4)); + assert(binding.CallWithInitList(testFuncB, 2, 4, 5) === testFuncB(2, 4, 5)); + + binding.CallWithRecvVector(testFuncC, outsideRef, 1, 2, 4); + assert(outsideRef.a === 1 && outsideRef.b === 2 && outsideRef.c === 4); + + outsideRef = {}; + binding.CallWithRecvInitList(testFuncC, outsideRef, 1, 2, 4); + assert(outsideRef.a === 1 && outsideRef.b === 2 && outsideRef.c === 4); + + outsideRef = {}; + binding.CallWithRecvArgc(testFuncD, outsideRef, 2, 4, 5, 6); + assert(outsideRef.result === testFuncD(2, 4, 5, 6)); +} + +async function canCallAsyncFunctionWithDifferentOverloads (binding) { + const testFunc = () => 2100; + const testFuncB = (a, b, c, d) => a + b + c + d; + let hook = installAsyncHook(); + binding.AsyncCallWithInitList(testFunc); + let triggerAsyncId = asyncHook.executionAsyncId(); + let res = await hook; + assert.deepStrictEqual(res, [ + { + eventName: 'init', + type: 'func_ref_resources', + triggerAsyncId, + resource: {} + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + + hook = installAsyncHook(); + triggerAsyncId = asyncHook.executionAsyncId(); + assert( + binding.AsyncCallWithVector(testFuncB, 2, 4, 5, 6) === testFuncB(2, 4, 5, 6) + ); + res = await hook; + assert.deepStrictEqual(res, [ + { + eventName: 'init', + type: 'func_ref_resources', + triggerAsyncId, + resource: {} + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); + + hook = installAsyncHook(); + triggerAsyncId = asyncHook.executionAsyncId(); + assert( + binding.AsyncCallWithArgv(testFuncB, 2, 4, 5, 6) === testFuncB(2, 4, 5, 6) + ); +} +async function test (binding) { + const e = new Error('foobar'); + const functionMayThrow = () => { + throw e; + }; + const classMayThrow = class { + constructor () { + throw e; + } + }; + + const newRef = binding.CreateFuncRefWithNew(120); + assert(newRef.getValue() === 120); + + const newRefWithVecArg = binding.CreateFuncRefWithNewVec(80); + assert(newRefWithVecArg.getValue() === 80); + + assert.throws(() => { + binding.call(functionMayThrow); + }, /foobar/); + assert.throws(() => { + binding.construct(classMayThrow); + }, /foobar/); + + canConstructRefFromExistingRef(binding); + canCallFunctionWithDifferentOverloads(binding); + // quickjs-napi: canCallAsyncFunctionWithDifferentOverloads checks async_hooks events. +} diff --git a/test/node-addon-api/test/globalObject/global_object.cc b/test/node-addon-api/test/globalObject/global_object.cc new file mode 100644 index 0000000..00ef2ba --- /dev/null +++ b/test/node-addon-api/test/globalObject/global_object.cc @@ -0,0 +1,61 @@ +#include "napi.h" + +using namespace Napi; + +// Wrappers for testing Object::Get() for global Objects +Value GetPropertyWithCppStyleStringAsKey(const CallbackInfo& info); +Value GetPropertyWithCStyleStringAsKey(const CallbackInfo& info); +Value GetPropertyWithInt32AsKey(const CallbackInfo& info); +Value GetPropertyWithNapiValueAsKey(const CallbackInfo& info); +void CreateMockTestObject(const CallbackInfo& info); + +// Wrapper for testing Object::Set() for global Objects +void SetPropertyWithCStyleStringAsKey(const CallbackInfo& info); +void SetPropertyWithCppStyleStringAsKey(const CallbackInfo& info); +void SetPropertyWithInt32AsKey(const CallbackInfo& info); +void SetPropertyWithNapiValueAsKey(const CallbackInfo& info); + +Value HasPropertyWithCStyleStringAsKey(const CallbackInfo& info); +Value HasPropertyWithCppStyleStringAsKey(const CallbackInfo& info); +Value HasPropertyWithNapiValueAsKey(const CallbackInfo& info); + +Value DeletePropertyWithCStyleStringAsKey(const CallbackInfo& info); +Value DeletePropertyWithCppStyleStringAsKey(const CallbackInfo& info); +Value DeletePropertyWithInt32AsKey(const CallbackInfo& info); +Value DeletePropertyWithNapiValueAsKey(const CallbackInfo& info); + +Object InitGlobalObject(Env env) { + Object exports = Object::New(env); + exports["getPropertyWithInt32"] = + Function::New(env, GetPropertyWithInt32AsKey); + exports["getPropertyWithNapiValue"] = + Function::New(env, GetPropertyWithNapiValueAsKey); + exports["getPropertyWithCppString"] = + Function::New(env, GetPropertyWithCppStyleStringAsKey); + exports["getPropertyWithCString"] = + Function::New(env, GetPropertyWithCStyleStringAsKey); + exports["createMockTestObject"] = Function::New(env, CreateMockTestObject); + exports["setPropertyWithCStyleString"] = + Function::New(env, SetPropertyWithCStyleStringAsKey); + exports["setPropertyWithCppStyleString"] = + Function::New(env, SetPropertyWithCppStyleStringAsKey); + exports["setPropertyWithNapiValue"] = + Function::New(env, SetPropertyWithNapiValueAsKey); + exports["setPropertyWithInt32"] = + Function::New(env, SetPropertyWithInt32AsKey); + exports["hasPropertyWithCStyleString"] = + Function::New(env, HasPropertyWithCStyleStringAsKey); + exports["hasPropertyWithCppStyleString"] = + Function::New(env, HasPropertyWithCppStyleStringAsKey); + exports["hasPropertyWithNapiValue"] = + Function::New(env, HasPropertyWithNapiValueAsKey); + exports["deletePropertyWithCStyleString"] = + Function::New(env, DeletePropertyWithCStyleStringAsKey); + exports["deletePropertyWithCppStyleString"] = + Function::New(env, DeletePropertyWithCppStyleStringAsKey); + exports["deletePropertyWithInt32"] = + Function::New(env, DeletePropertyWithInt32AsKey); + exports["deletePropertyWithNapiValue"] = + Function::New(env, DeletePropertyWithNapiValueAsKey); + return exports; +} diff --git a/test/node-addon-api/test/globalObject/global_object_delete_property.cc b/test/node-addon-api/test/globalObject/global_object_delete_property.cc new file mode 100644 index 0000000..70738c2 --- /dev/null +++ b/test/node-addon-api/test/globalObject/global_object_delete_property.cc @@ -0,0 +1,31 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +Value DeletePropertyWithCStyleStringAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + String key = info[0].UnsafeAs(); + return Boolean::New( + info.Env(), MaybeUnwrap(globalObject.Delete(key.Utf8Value().c_str()))); +} + +Value DeletePropertyWithCppStyleStringAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + String key = info[0].UnsafeAs(); + return Boolean::New(info.Env(), + MaybeUnwrap(globalObject.Delete(key.Utf8Value()))); +} + +Value DeletePropertyWithInt32AsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + Number key = info[0].UnsafeAs(); + return Boolean::New(info.Env(), + MaybeUnwrap(globalObject.Delete(key.Uint32Value()))); +} + +Value DeletePropertyWithNapiValueAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + Name key = info[0].UnsafeAs(); + return Boolean::New(info.Env(), MaybeUnwrap(globalObject.Delete(key))); +} diff --git a/test/node-addon-api/test/globalObject/global_object_delete_property.js b/test/node-addon-api/test/globalObject/global_object_delete_property.js new file mode 100644 index 0000000..c8fa68e --- /dev/null +++ b/test/node-addon-api/test/globalObject/global_object_delete_property.js @@ -0,0 +1,58 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + const KEY_TYPE = { + C_STR: 'KEY_AS_C_STRING', + CPP_STR: 'KEY_AS_CPP_STRING', + NAPI: 'KEY_AS_NAPI_VALUES', + INT_32: 'KEY_AS_INT_32_NUM' + }; + + function assertNotGlobalObjectHasNoProperty (key, keyType) { + switch (keyType) { + case KEY_TYPE.NAPI: + assert.notStrictEqual(binding.globalObject.hasPropertyWithNapiValue(key), true); + break; + + case KEY_TYPE.C_STR: + assert.notStrictEqual(binding.globalObject.hasPropertyWithCStyleString(key), true); + break; + + case KEY_TYPE.CPP_STR: + assert.notStrictEqual(binding.globalObject.hasPropertyWithCppStyleString(key), true); + break; + + case KEY_TYPE.INT_32: + assert.notStrictEqual(binding.globalObject.hasPropertyWithInt32(key), true); + break; + } + } + + function assertErrMessageIsThrown (propertyCheckExistenceFunction, errMsg) { + assert.throws(() => { + propertyCheckExistenceFunction(undefined); + }, errMsg); + } + + binding.globalObject.createMockTestObject(); + + binding.globalObject.deletePropertyWithCStyleString('c_str_key'); + binding.globalObject.deletePropertyWithCppStyleString('cpp_string_key'); + binding.globalObject.deletePropertyWithCppStyleString('circular'); + binding.globalObject.deletePropertyWithInt32(15); + binding.globalObject.deletePropertyWithNapiValue('2'); + + assertNotGlobalObjectHasNoProperty('c_str_key', KEY_TYPE.C_STR); + assertNotGlobalObjectHasNoProperty('cpp_string_key', KEY_TYPE.CPP_STR); + assertNotGlobalObjectHasNoProperty('circular', KEY_TYPE.CPP_STR); + assertNotGlobalObjectHasNoProperty(15, true); + assertNotGlobalObjectHasNoProperty('2', KEY_TYPE.NAPI); + + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCppStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithInt32, 'Error: A number was expected'); +} diff --git a/test/node-addon-api/test/globalObject/global_object_get_property.cc b/test/node-addon-api/test/globalObject/global_object_get_property.cc new file mode 100644 index 0000000..81f727d --- /dev/null +++ b/test/node-addon-api/test/globalObject/global_object_get_property.cc @@ -0,0 +1,40 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +Value GetPropertyWithNapiValueAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + Name key = info[0].UnsafeAs(); + return MaybeUnwrap(globalObject.Get(key)); +} + +Value GetPropertyWithInt32AsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + Number key = info[0].UnsafeAs(); + return MaybeUnwrapOr(globalObject.Get(key.Uint32Value()), Value()); +} + +Value GetPropertyWithCStyleStringAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + String cStrkey = info[0].UnsafeAs(); + return MaybeUnwrapOr(globalObject.Get(cStrkey.Utf8Value().c_str()), Value()); +} + +Value GetPropertyWithCppStyleStringAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + String cppStrKey = info[0].UnsafeAs(); + return MaybeUnwrapOr(globalObject.Get(cppStrKey.Utf8Value()), Value()); +} + +void CreateMockTestObject(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + Number napi_key = Number::New(info.Env(), 2); + const char* CStringKey = "c_str_key"; + + globalObject.Set(napi_key, "napi_attribute"); + globalObject[CStringKey] = "c_string_attribute"; + globalObject[std::string("cpp_string_key")] = "cpp_string_attribute"; + globalObject[std::string("circular")] = globalObject; + globalObject[(uint32_t)15] = 15; +} diff --git a/test/node-addon-api/test/globalObject/global_object_get_property.js b/test/node-addon-api/test/globalObject/global_object_get_property.js new file mode 100644 index 0000000..ec72a84 --- /dev/null +++ b/test/node-addon-api/test/globalObject/global_object_get_property.js @@ -0,0 +1,56 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + const KEY_TYPE = { + C_STR: 'KEY_AS_C_STRING', + CPP_STR: 'KEY_AS_CPP_STRING', + NAPI: 'KEY_AS_NAPI_VALUES', + INT_32: 'KEY_AS_INT_32_NUM' + }; + + binding.globalObject.createMockTestObject(); + function assertGlobalObjectPropertyIs (key, attribute, keyType) { + let napiObjectAttr; + switch (keyType) { + case KEY_TYPE.NAPI: + napiObjectAttr = binding.globalObject.getPropertyWithNapiValue(key); + assert.deepStrictEqual(attribute, napiObjectAttr); + break; + + case KEY_TYPE.C_STR: + napiObjectAttr = binding.globalObject.getPropertyWithCString(key); + assert.deepStrictEqual(attribute, napiObjectAttr); + break; + + case KEY_TYPE.CPP_STR: + napiObjectAttr = binding.globalObject.getPropertyWithCppString(key); + assert.deepStrictEqual(attribute, napiObjectAttr); + break; + + case KEY_TYPE.INT_32: + napiObjectAttr = binding.globalObject.getPropertyWithInt32(key); + assert.deepStrictEqual(attribute, napiObjectAttr); + break; + } + } + + function assertErrMessageIsThrown (propertyFetchFunction, errMsg) { + assert.throws(() => { + propertyFetchFunction(undefined); + }, errMsg); + } + + assertGlobalObjectPropertyIs('2', global['2'], KEY_TYPE.NAPI); + assertGlobalObjectPropertyIs('c_str_key', global.c_str_key, KEY_TYPE.C_STR); + assertGlobalObjectPropertyIs('cpp_string_key', global.cpp_string_key, KEY_TYPE.CPP_STR); + assertGlobalObjectPropertyIs('circular', global.circular, KEY_TYPE.CPP_STR); + assertGlobalObjectPropertyIs(15, global['15'], KEY_TYPE.INT_32); + + assertErrMessageIsThrown(binding.globalObject.getPropertyWithCString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.getPropertyWithCppString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.getPropertyWithInt32, 'Error: A number was expected'); +} diff --git a/test/node-addon-api/test/globalObject/global_object_has_own_property.cc b/test/node-addon-api/test/globalObject/global_object_has_own_property.cc new file mode 100644 index 0000000..388788d --- /dev/null +++ b/test/node-addon-api/test/globalObject/global_object_has_own_property.cc @@ -0,0 +1,28 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +Value HasPropertyWithCStyleStringAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + String key = info[0].UnsafeAs(); + return Boolean::New( + info.Env(), + MaybeUnwrapOr(globalObject.HasOwnProperty(key.Utf8Value().c_str()), + false)); +} + +Value HasPropertyWithCppStyleStringAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + String key = info[0].UnsafeAs(); + return Boolean::New( + info.Env(), + MaybeUnwrapOr(globalObject.HasOwnProperty(key.Utf8Value()), false)); +} + +Value HasPropertyWithNapiValueAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + Name key = info[0].UnsafeAs(); + return Boolean::New(info.Env(), + MaybeUnwrap(globalObject.HasOwnProperty(key))); +} diff --git a/test/node-addon-api/test/globalObject/global_object_has_own_property.js b/test/node-addon-api/test/globalObject/global_object_has_own_property.js new file mode 100644 index 0000000..652c6b3 --- /dev/null +++ b/test/node-addon-api/test/globalObject/global_object_has_own_property.js @@ -0,0 +1,46 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + const KEY_TYPE = { + C_STR: 'KEY_AS_C_STRING', + CPP_STR: 'KEY_AS_CPP_STRING', + NAPI: 'KEY_AS_NAPI_VALUES', + INT_32: 'KEY_AS_INT_32_NUM' + }; + + function assertGlobalObjectHasProperty (key, keyType) { + switch (keyType) { + case KEY_TYPE.NAPI: + assert.strictEqual(binding.globalObject.hasPropertyWithNapiValue(key), true); + break; + + case KEY_TYPE.C_STR: + assert.strictEqual(binding.globalObject.hasPropertyWithCStyleString(key), true); + break; + + case KEY_TYPE.CPP_STR: + assert.strictEqual(binding.globalObject.hasPropertyWithCppStyleString(key), true); + break; + } + } + + function assertErrMessageIsThrown (propertyCheckExistenceFunction, errMsg) { + assert.throws(() => { + propertyCheckExistenceFunction(undefined); + }, errMsg); + } + + binding.globalObject.createMockTestObject(); + assertGlobalObjectHasProperty('c_str_key', KEY_TYPE.C_STR); + assertGlobalObjectHasProperty('cpp_string_key', KEY_TYPE.CPP_STR); + assertGlobalObjectHasProperty('circular', KEY_TYPE.CPP_STR); + assertGlobalObjectHasProperty('2', KEY_TYPE.NAPI); + + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCppStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithInt32, 'Error: A number was expected'); +} diff --git a/test/node-addon-api/test/globalObject/global_object_set_property.cc b/test/node-addon-api/test/globalObject/global_object_set_property.cc new file mode 100644 index 0000000..06da631 --- /dev/null +++ b/test/node-addon-api/test/globalObject/global_object_set_property.cc @@ -0,0 +1,31 @@ +#include "napi.h" + +using namespace Napi; + +void SetPropertyWithCStyleStringAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + String key = info[0].UnsafeAs(); + Value value = info[1]; + globalObject.Set(key.Utf8Value().c_str(), value); +} + +void SetPropertyWithCppStyleStringAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + String key = info[0].UnsafeAs(); + Value value = info[1]; + globalObject.Set(key.Utf8Value(), value); +} + +void SetPropertyWithInt32AsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + Number key = info[0].UnsafeAs(); + Value value = info[1]; + globalObject.Set(key.Uint32Value(), value); +} + +void SetPropertyWithNapiValueAsKey(const CallbackInfo& info) { + Object globalObject = info.Env().Global(); + Name key = info[0].UnsafeAs(); + Value value = info[1]; + globalObject.Set(key, value); +} diff --git a/test/node-addon-api/test/globalObject/global_object_set_property.js b/test/node-addon-api/test/globalObject/global_object_set_property.js new file mode 100644 index 0000000..ff4811c --- /dev/null +++ b/test/node-addon-api/test/globalObject/global_object_set_property.js @@ -0,0 +1,56 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + const KEY_TYPE = { + C_STR: 'KEY_AS_C_STRING', + CPP_STR: 'KEY_AS_CPP_STRING', + NAPI: 'KEY_AS_NAPI_VALUES', + INT_32: 'KEY_AS_INT_32_NUM' + }; + + function setGlobalObjectKeyValue (key, value, keyType) { + switch (keyType) { + case KEY_TYPE.CPP_STR: + binding.globalObject.setPropertyWithCppStyleString(key, value); + break; + + case KEY_TYPE.C_STR: + binding.globalObject.setPropertyWithCStyleString(key, value); + break; + + case KEY_TYPE.INT_32: + binding.globalObject.setPropertyWithInt32(key, value); + break; + + case KEY_TYPE.NAPI: + binding.globalObject.setPropertyWithNapiValue(key, value); + break; + } + } + + function assertErrMessageIsThrown (nativeObjectSetFunction, errMsg) { + assert.throws(() => { + nativeObjectSetFunction(undefined, 1); + }, errMsg); + } + + setGlobalObjectKeyValue('cKey', 'cValue', KEY_TYPE.CPP_STR); + setGlobalObjectKeyValue(1, 10, KEY_TYPE.INT_32); + setGlobalObjectKeyValue('napi_key', 'napi_value', KEY_TYPE.NAPI); + setGlobalObjectKeyValue('cppKey', 'cppValue', KEY_TYPE.CPP_STR); + setGlobalObjectKeyValue('circular', global, KEY_TYPE.NAPI); + + assert.deepStrictEqual(global.circular, global); + assert.deepStrictEqual(global.cppKey, 'cppValue'); + assert.deepStrictEqual(global.napi_key, 'napi_value'); + assert.deepStrictEqual(global[1], 10); + assert.deepStrictEqual(global.cKey, 'cValue'); + + assertErrMessageIsThrown(binding.globalObject.setPropertyWithCppStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.setPropertyWithCStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.setPropertyWithInt32, 'Error: A number was expected'); +} diff --git a/test/node-addon-api/test/handlescope.cc b/test/node-addon-api/test/handlescope.cc new file mode 100644 index 0000000..c68c1c3 --- /dev/null +++ b/test/node-addon-api/test/handlescope.cc @@ -0,0 +1,86 @@ +#include +#include +#include "napi.h" +#include "string.h" + +using namespace Napi; + +Value createScope(const CallbackInfo& info) { + { + HandleScope scope(info.Env()); + String::New(info.Env(), "inner-scope"); + } + return String::New(info.Env(), "scope"); +} + +Value createScopeFromExisting(const CallbackInfo& info) { + { + napi_handle_scope scope; + napi_open_handle_scope(info.Env(), &scope); + HandleScope scope_existing(info.Env(), scope); + String::New(scope_existing.Env(), "inner-existing-scope"); + } + return String::New(info.Env(), "existing_scope"); +} + +Value escapeFromScope(const CallbackInfo& info) { + Value result; + { + EscapableHandleScope scope(info.Env()); + result = scope.Escape(String::New(info.Env(), "inner-scope")); + } + return result; +} + +Value escapeFromExistingScope(const CallbackInfo& info) { + Value result; + { + napi_escapable_handle_scope scope; + napi_open_escapable_handle_scope(info.Env(), &scope); + EscapableHandleScope scope_existing(info.Env(), scope); + result = scope_existing.Escape( + String::New(scope_existing.Env(), "inner-existing-scope")); + } + return result; +} + +#define LOOP_MAX 1000000 +Value stressEscapeFromScope(const CallbackInfo& info) { + Value result; + for (int i = 0; i < LOOP_MAX; i++) { + EscapableHandleScope scope(info.Env()); + char buffer[128]; + snprintf(buffer, 128, "%d", i); + std::string name = std::string("inner-scope") + std::string(buffer); + Value newValue = String::New(info.Env(), name.c_str()); + if (i == (LOOP_MAX - 1)) { + result = scope.Escape(newValue); + } + } + return result; +} + +Value doubleEscapeFromScope(const CallbackInfo& info) { + Value result; + { + EscapableHandleScope scope(info.Env()); + result = scope.Escape(String::New(info.Env(), "inner-scope")); + result = scope.Escape(String::New(info.Env(), "inner-scope")); + } + return result; +} + +Object InitHandleScope(Env env) { + Object exports = Object::New(env); + + exports["createScope"] = Function::New(env, createScope); + exports["createScopeFromExisting"] = + Function::New(env, createScopeFromExisting); + exports["escapeFromScope"] = Function::New(env, escapeFromScope); + exports["escapeFromExistingScope"] = + Function::New(env, escapeFromExistingScope); + exports["stressEscapeFromScope"] = Function::New(env, stressEscapeFromScope); + exports["doubleEscapeFromScope"] = Function::New(env, doubleEscapeFromScope); + + return exports; +} diff --git a/test/node-addon-api/test/handlescope.js b/test/node-addon-api/test/handlescope.js new file mode 100644 index 0000000..ad45f95 --- /dev/null +++ b/test/node-addon-api/test/handlescope.js @@ -0,0 +1,16 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + assert.strictEqual(binding.handlescope.createScope(), 'scope'); + assert.strictEqual(binding.handlescope.createScopeFromExisting(), 'existing_scope'); + assert.strictEqual(binding.handlescope.escapeFromScope(), 'inner-scope'); + assert.strictEqual(binding.handlescope.escapeFromExistingScope(), 'inner-existing-scope'); + assert.strictEqual(binding.handlescope.stressEscapeFromScope(), 'inner-scope999999'); + assert.throws(() => binding.handlescope.doubleEscapeFromScope(), + Error, + ' napi_escape_handle already called on scope'); +} diff --git a/test/node-addon-api/test/index.js b/test/node-addon-api/test/index.js new file mode 100644 index 0000000..f0c0345 --- /dev/null +++ b/test/node-addon-api/test/index.js @@ -0,0 +1,160 @@ +'use strict'; + +const majorNodeVersion = process.versions.node.split('.')[0]; + +if (typeof global.gc !== 'function') { + // Construct the correct (version-dependent) command-line args. + const args = ['--expose-gc']; + const majorV8Version = process.versions.v8.split('.')[0]; + if (majorV8Version < 9) { + args.push('--no-concurrent-array-buffer-freeing'); + } + if (majorNodeVersion >= 14) { + args.push('--no-concurrent-array-buffer-sweeping'); + } + args.push(__filename); + + const child = require('./napi_child').spawnSync(process.argv[0], args, { + stdio: 'inherit' + }); + + if (child.signal) { + console.error(`Tests aborted with ${child.signal}`); + process.exitCode = 1; + } else { + process.exitCode = child.status; + } + process.exit(process.exitCode); +} + +const testModules = []; + +const fs = require('fs'); +const path = require('path'); + +let filterCondition = process.env.npm_config_filter || ''; +let filterConditionFiles = []; + +if (filterCondition !== '') { + filterCondition = require('../unit-test/matchModules').matchWildCards(process.env.npm_config_filter); + filterConditionFiles = filterCondition.split(' ').length > 0 ? filterCondition.split(' ') : [filterCondition]; +} + +const filterConditionsProvided = filterConditionFiles.length > 0; + +function checkFilterCondition (fileName, parsedFilepath) { + let result = false; + + if (!filterConditionsProvided) return true; + if (filterConditionFiles.includes(parsedFilepath)) result = true; + if (filterConditionFiles.includes(fileName)) result = true; + return result; +} + +// TODO(RaisinTen): Update this when the test filenames +// are changed into test_*.js. +function loadTestModules (currentDirectory = __dirname, pre = '') { + fs.readdirSync(currentDirectory).forEach((file) => { + if (currentDirectory === __dirname && ( + file === 'binding.cc' || + file === 'binding.gyp' || + file === 'build' || + file === 'common' || + file === 'child_processes' || + file === 'napi_child.js' || + file === 'testUtil.js' || + file === 'thunking_manual.cc' || + file === 'thunking_manual.js' || + file === 'index.js' || + file[0] === '.')) { + return; + } + const absoluteFilepath = path.join(currentDirectory, file); + const parsedFilepath = path.parse(file); + const parsedPath = path.parse(currentDirectory); + + if (fs.statSync(absoluteFilepath).isDirectory()) { + if (fs.existsSync(absoluteFilepath + '/index.js')) { + if (checkFilterCondition(parsedFilepath.name, parsedPath.base)) { + testModules.push(pre + file); + } + } else { + loadTestModules(absoluteFilepath, pre + file + '/'); + } + } else { + if (parsedFilepath.ext === '.js' && checkFilterCondition(parsedFilepath.name, parsedPath.base)) { + testModules.push(pre + parsedFilepath.name); + } + } + }); +} + +loadTestModules(); + +let napiVersion = Number(process.versions.napi); +if (process.env.NAPI_VERSION) { + // we need this so that we don't try run tests that rely + // on methods that are not available in the NAPI_VERSION + // specified + napiVersion = process.env.NAPI_VERSION; +} +console.log('napiVersion:' + napiVersion); + +if (napiVersion < 3) { + testModules.splice(testModules.indexOf('env_cleanup'), 1); + testModules.splice(testModules.indexOf('callbackscope'), 1); + testModules.splice(testModules.indexOf('version_management'), 1); +} + +if (napiVersion < 4 && !filterConditionsProvided) { + testModules.splice(testModules.indexOf('asyncprogressqueueworker'), 1); + testModules.splice(testModules.indexOf('asyncprogressworker'), 1); + testModules.splice(testModules.indexOf('threadsafe_function/threadsafe_function_ctx'), 1); + testModules.splice(testModules.indexOf('threadsafe_function/threadsafe_function_existing_tsfn'), 1); + testModules.splice(testModules.indexOf('threadsafe_function/threadsafe_function_ptr'), 1); + testModules.splice(testModules.indexOf('threadsafe_function/threadsafe_function_sum'), 1); + testModules.splice(testModules.indexOf('threadsafe_function/threadsafe_function_unref'), 1); + testModules.splice(testModules.indexOf('threadsafe_function/threadsafe_function'), 1); +} + +if (napiVersion < 5 && !filterConditionsProvided) { + testModules.splice(testModules.indexOf('date'), 1); +} + +if (napiVersion < 6 && !filterConditionsProvided) { + testModules.splice(testModules.indexOf('addon'), 1); + testModules.splice(testModules.indexOf('addon_data'), 1); + testModules.splice(testModules.indexOf('bigint'), 1); + testModules.splice(testModules.indexOf('typedarray-bigint'), 1); +} + +if (majorNodeVersion < 12 && !filterConditionsProvided) { + testModules.splice(testModules.indexOf('objectwrap_worker_thread'), 1); + testModules.splice(testModules.indexOf('error_terminating_environment'), 1); +} + +if (napiVersion < 8 && !filterConditionsProvided) { + testModules.splice(testModules.indexOf('object/object_freeze_seal'), 1); + testModules.splice(testModules.indexOf('type_taggable'), 1); +} + +if (napiVersion < 9 && !filterConditionsProvided) { + testModules.splice(testModules.indexOf('env_misc'), 1); +} + +(async function () { + console.log(`Testing with Node-API Version '${napiVersion}'.`); + + if (filterConditionsProvided) { console.log('Starting test suite\n', testModules); } else { console.log('Starting test suite\n'); } + + // Requiring each module runs tests in the module. + for (const name of testModules) { + console.log(`Running test '${name}'`); + await require('./' + name); + } + + console.log('\nAll tests passed!'); +})().catch((error) => { + console.log(error); + process.exit(1); +}); diff --git a/test/node-addon-api/test/maybe/check.cc b/test/node-addon-api/test/maybe/check.cc new file mode 100644 index 0000000..74acf7e --- /dev/null +++ b/test/node-addon-api/test/maybe/check.cc @@ -0,0 +1,69 @@ +#include "assert.h" +#include "napi.h" +#if defined(NODE_ADDON_API_ENABLE_MAYBE) + +using namespace Napi; + +namespace { + +void VoidCallback(const CallbackInfo& info) { + Napi::Function fn = info[0].As(); + Maybe ret = fn.Call({}); + + assert(ret.IsNothing() == true); + assert(ret.IsJust() == false); + + Napi::Value placeHolder = Napi::Number::New(info.Env(), 12345); + Napi::Value unwrappedValue = ret.UnwrapOr(placeHolder); + + assert(unwrappedValue.As().Uint32Value() == 12345); + + assert(ret.UnwrapTo(&placeHolder) == false); + assert(placeHolder.As().Uint32Value() == 12345); + + ret.Check(); +} + +void TestMaybeOperatorOverload(const CallbackInfo& info) { + Napi::Function fn_a = info[0].As(); + Napi::Function fn_b = info[1].As(); + + assert(fn_a.Call({}) == fn_a.Call({})); + assert(fn_a.Call({}) != fn_b.Call({})); +} + +void NormalJsCallback(const CallbackInfo& info) { + Napi::Function fn = info[0].As(); + uint32_t magic_number = info[1].As().Uint32Value(); + + Maybe ret = fn.Call({}); + + assert(ret.IsNothing() == false); + assert(ret.IsJust() == true); + + Napi::Value unwrappedValue = ret.Unwrap(); + assert(unwrappedValue.IsNumber() == true); + + assert(unwrappedValue.As().Uint32Value() == magic_number); + + unwrappedValue = + ret.UnwrapOr(Napi::Number::New(info.Env(), magic_number - 1)); + assert(unwrappedValue.As().Uint32Value() == magic_number); + + Napi::Value placeHolder = Napi::Number::New(info.Env(), magic_number - 1); + assert(ret.UnwrapTo(&placeHolder) == true); + assert(placeHolder.As().Uint32Value() == magic_number); +} + +} // end anonymous namespace + +Object InitMaybeCheck(Env env) { + Object exports = Object::New(env); + exports.Set("voidCallback", Function::New(env, VoidCallback)); + exports.Set("normalJsCallback", Function::New(env, NormalJsCallback)); + exports.Set("testMaybeOverloadOp", + Function::New(env, TestMaybeOperatorOverload)); + return exports; +} + +#endif diff --git a/test/node-addon-api/test/maybe/index.js b/test/node-addon-api/test/maybe/index.js new file mode 100644 index 0000000..65f8643 --- /dev/null +++ b/test/node-addon-api/test/maybe/index.js @@ -0,0 +1,50 @@ +'use strict'; + +const assert = require('assert'); +const { whichBuildType } = require('../common'); + +const napiChild = require('../napi_child'); + +module.exports = async function wrapTest () { + const buildType = await whichBuildType(); + test(require(`../build/${buildType}/binding_noexcept_maybe.node`).maybe_check); +}; + +function test (binding) { + if (process.argv.includes('child')) { + child(binding); + return; + } + const cp = napiChild.spawn(process.execPath, [__filename, 'child'], { + stdio: ['ignore', 'inherit', 'pipe'] + }); + cp.stderr.setEncoding('utf8'); + let stderr = ''; + cp.stderr.on('data', chunk => { + stderr += chunk; + }); + cp.on('exit', (code, signal) => { + if (process.platform === 'win32') { + assert.strictEqual(code, 128 + 6 /* SIGABRT */); + } else { + assert.strictEqual(signal, 'SIGABRT'); + } + assert.ok(stderr.match(/FATAL ERROR: Napi::Maybe::Check Maybe value is Nothing./)); + }); +} + +function child (binding) { + const MAGIC_NUMBER = 12459062; + binding.normalJsCallback(() => { + return MAGIC_NUMBER; + }, MAGIC_NUMBER); + + binding.testMaybeOverloadOp( + () => { return MAGIC_NUMBER; }, + () => { throw Error('Foobar'); } + ); + + binding.voidCallback(() => { + throw new Error('foobar'); + }); +} diff --git a/test/node-addon-api/test/memory_management.cc b/test/node-addon-api/test/memory_management.cc new file mode 100644 index 0000000..48bc389 --- /dev/null +++ b/test/node-addon-api/test/memory_management.cc @@ -0,0 +1,18 @@ +#include "napi.h" + +using namespace Napi; + +Value externalAllocatedMemory(const CallbackInfo& info) { + int64_t kSize = 1024 * 1024; + int64_t baseline = MemoryManagement::AdjustExternalMemory(info.Env(), 0); + int64_t tmp = MemoryManagement::AdjustExternalMemory(info.Env(), kSize); + tmp = MemoryManagement::AdjustExternalMemory(info.Env(), -kSize); + return Boolean::New(info.Env(), tmp == baseline); +} + +Object InitMemoryManagement(Env env) { + Object exports = Object::New(env); + exports["externalAllocatedMemory"] = + Function::New(env, externalAllocatedMemory); + return exports; +} diff --git a/test/node-addon-api/test/memory_management.js b/test/node-addon-api/test/memory_management.js new file mode 100644 index 0000000..af5dbb0 --- /dev/null +++ b/test/node-addon-api/test/memory_management.js @@ -0,0 +1,9 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + assert.strictEqual(binding.memory_management.externalAllocatedMemory(), true); +} diff --git a/test/node-addon-api/test/movable_callbacks.cc b/test/node-addon-api/test/movable_callbacks.cc new file mode 100644 index 0000000..9959d4d --- /dev/null +++ b/test/node-addon-api/test/movable_callbacks.cc @@ -0,0 +1,23 @@ +#include "napi.h" + +using namespace Napi; + +Value createExternal(const CallbackInfo& info) { + FunctionReference ref = Reference::New(info[0].As(), 1); + auto ret = External::New( + info.Env(), + nullptr, + [ref = std::move(ref)](Napi::Env /*env*/, char* /*data*/) { + ref.Call({}); + }); + + return ret; +} + +Object InitMovableCallbacks(Env env) { + Object exports = Object::New(env); + + exports["createExternal"] = Function::New(env, createExternal); + + return exports; +} diff --git a/test/node-addon-api/test/movable_callbacks.js b/test/node-addon-api/test/movable_callbacks.js new file mode 100644 index 0000000..c925b92 --- /dev/null +++ b/test/node-addon-api/test/movable_callbacks.js @@ -0,0 +1,21 @@ +'use strict'; + +const common = require('./common'); +const testUtil = require('./testUtil'); + +module.exports = require('./common').runTest(binding => test(binding.movable_callbacks)); + +async function test (binding) { + await testUtil.runGCTests([ + 'External', + () => { + const fn = common.mustCall(() => { + // noop + }, 1); + binding.createExternal(fn); + }, + () => { + // noop, wait for gc + } + ]); +} diff --git a/test/node-addon-api/test/name.cc b/test/node-addon-api/test/name.cc new file mode 100644 index 0000000..d94a393 --- /dev/null +++ b/test/node-addon-api/test/name.cc @@ -0,0 +1,124 @@ +#include "napi.h" + +#include + +using namespace Napi; + +const char* testValueUtf8 = "123456789"; +const char16_t* testValueUtf16 = NAPI_WIDE_TEXT("123456789"); + +Value EchoString(const CallbackInfo& info) { + String value = info[0].As(); + String encoding = info[1].As(); + + if (encoding.Utf8Value() == "utf8") { + return String::New(info.Env(), value.Utf8Value().c_str()); + } else if (encoding.Utf8Value() == "utf16") { + return String::New(info.Env(), value.Utf16Value().c_str()); + } else { + Error::New(info.Env(), "Invalid encoding.").ThrowAsJavaScriptException(); + return Value(); + } +} + +Value CreateString(const CallbackInfo& info) { + String encoding = info[0].As(); + Value length = info[1]; + + if (encoding.Utf8Value() == "utf8") { + if (length.IsUndefined()) { + return String::New(info.Env(), testValueUtf8); + } else { + return String::New( + info.Env(), testValueUtf8, length.As().Uint32Value()); + } + } else if (encoding.Utf8Value() == "utf16") { + if (length.IsUndefined()) { + return String::New(info.Env(), testValueUtf16); + } else { + return String::New( + info.Env(), testValueUtf16, length.As().Uint32Value()); + } + } else { + Error::New(info.Env(), "Invalid encoding.").ThrowAsJavaScriptException(); + return Value(); + } +} + +Value CreateStringFromStringView(const CallbackInfo& info) { + return String::New(info.Env(), std::string_view("hello1")); +} + +Value CheckString(const CallbackInfo& info) { + String value = info[0].As(); + String encoding = info[1].As(); + Value length = info[2]; + + if (encoding.Utf8Value() == "utf8") { + std::string testValue = testValueUtf8; + if (!length.IsUndefined()) { + testValue = testValue.substr(0, length.As().Uint32Value()); + } + + std::string stringValue = value; + return Boolean::New(info.Env(), stringValue == testValue); + } else if (encoding.Utf8Value() == "utf16") { + std::u16string testValue = testValueUtf16; + if (!length.IsUndefined()) { + testValue = testValue.substr(0, length.As().Uint32Value()); + } + + std::u16string stringValue = value; + return Boolean::New(info.Env(), stringValue == testValue); + } else { + Error::New(info.Env(), "Invalid encoding.").ThrowAsJavaScriptException(); + return Value(); + } +} + +Value CreateSymbol(const CallbackInfo& info) { + Value description = info[0]; + + if (!description.IsUndefined()) { + return Symbol::New(info.Env(), description.As()); + } else { + return Symbol::New(info.Env()); + } +} + +Value CreateSymbolFromStringView(const CallbackInfo& info) { + return Symbol::New(info.Env(), std::string_view("hello2")); +} + +Value CheckSymbol(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].Type() == napi_symbol); +} + +void NullStringShouldThrow(const CallbackInfo& info) { + const char* nullStr = nullptr; + String::New(info.Env(), nullStr); +} + +void NullString16ShouldThrow(const CallbackInfo& info) { + const char16_t* nullStr = nullptr; + String::New(info.Env(), nullStr); +} + +Object InitName(Env env) { + Object exports = Object::New(env); + + exports["echoString"] = Function::New(env, EchoString); + exports["createString"] = Function::New(env, CreateString); + exports["createStringFromStringView"] = + Function::New(env, CreateStringFromStringView); + exports["nullStringShouldThrow"] = Function::New(env, NullStringShouldThrow); + exports["nullString16ShouldThrow"] = + Function::New(env, NullString16ShouldThrow); + exports["checkString"] = Function::New(env, CheckString); + exports["createSymbol"] = Function::New(env, CreateSymbol); + exports["createSymbolFromStringView"] = + Function::New(env, CreateSymbolFromStringView); + exports["checkSymbol"] = Function::New(env, CheckSymbol); + + return exports; +} diff --git a/test/node-addon-api/test/name.js b/test/node-addon-api/test/name.js new file mode 100644 index 0000000..8113565 --- /dev/null +++ b/test/node-addon-api/test/name.js @@ -0,0 +1,64 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + const expected = '123456789'; + + assert.throws(binding.name.nullStringShouldThrow, { + name: 'Error', + message: 'Error in native callback' + }); + assert.ok(binding.name.checkString(expected, 'utf8')); + assert.ok(binding.name.checkString(expected, 'utf16')); + assert.ok(binding.name.checkString(expected.substr(0, 3), 'utf8', 3)); + assert.ok(binding.name.checkString(expected.substr(0, 3), 'utf16', 3)); + + const str1 = binding.name.createString('utf8'); + assert.strictEqual(str1, expected); + assert.ok(binding.name.checkString(str1, 'utf8')); + assert.ok(binding.name.checkString(str1, 'utf16')); + + const substr1 = binding.name.createString('utf8', 3); + assert.strictEqual(substr1, expected.substr(0, 3)); + assert.ok(binding.name.checkString(substr1, 'utf8', 3)); + assert.ok(binding.name.checkString(substr1, 'utf16', 3)); + + const str2 = binding.name.createString('utf16'); + assert.strictEqual(str1, expected); + assert.ok(binding.name.checkString(str2, 'utf8')); + assert.ok(binding.name.checkString(str2, 'utf16')); + + const substr2 = binding.name.createString('utf16', 3); + assert.strictEqual(substr1, expected.substr(0, 3)); + assert.ok(binding.name.checkString(substr2, 'utf8', 3)); + assert.ok(binding.name.checkString(substr2, 'utf16', 3)); + + // eslint-disable-next-line symbol-description + assert.ok(binding.name.checkSymbol(Symbol())); + assert.ok(binding.name.checkSymbol(Symbol('test'))); + + const sym1 = binding.name.createSymbol(); + assert.strictEqual(typeof sym1, 'symbol'); + assert.ok(binding.name.checkSymbol(sym1)); + + const sym2 = binding.name.createSymbol('test'); + assert.strictEqual(typeof sym2, 'symbol'); + assert.ok(binding.name.checkSymbol(sym1)); + + // Check for off-by-one errors which might only appear for strings of certain sizes, + // due to how std::string increments its capacity in chunks. + const longString = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; + for (let i = 10; i <= longString.length; i++) { + const str = longString.substr(0, i); + assert.strictEqual(binding.name.echoString(str, 'utf8'), str); + assert.strictEqual(binding.name.echoString(str, 'utf16'), str); + } + + assert.strictEqual(binding.name.createStringFromStringView(), 'hello1'); + const symFromStringView = binding.name.createSymbolFromStringView(); + assert.strictEqual(typeof symFromStringView, 'symbol'); + assert.strictEqual(symFromStringView.description, 'hello2'); +} diff --git a/test/node-addon-api/test/napi_child.js b/test/node-addon-api/test/napi_child.js new file mode 100644 index 0000000..e3f89fd --- /dev/null +++ b/test/node-addon-api/test/napi_child.js @@ -0,0 +1,14 @@ +// Makes sure that child processes are spawned appropriately. +exports.spawnSync = function (command, args, options) { + if (require('../index').needsFlag) { + args.splice(0, 0, '--napi-modules'); + } + return require('child_process').spawnSync(command, args, options); +}; + +exports.spawn = function (command, args, options) { + if (require('../index').needsFlag) { + args.splice(0, 0, '--napi-modules'); + } + return require('child_process').spawn(command, args, options); +}; diff --git a/test/node-addon-api/test/object/delete_property.cc b/test/node-addon-api/test/object/delete_property.cc new file mode 100644 index 0000000..b05af20 --- /dev/null +++ b/test/node-addon-api/test/object/delete_property.cc @@ -0,0 +1,38 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +Value DeletePropertyWithUint32(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Number key = info[1].As(); + return Boolean::New(info.Env(), MaybeUnwrap(obj.Delete(key.Uint32Value()))); +} + +Value DeletePropertyWithNapiValue(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Name key = info[1].As(); + return Boolean::New( + info.Env(), + MaybeUnwrapOr(obj.Delete(static_cast(key)), false)); +} + +Value DeletePropertyWithNapiWrapperValue(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Name key = info[1].As(); + return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Delete(key), false)); +} + +Value DeletePropertyWithCStyleString(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + String jsKey = info[1].As(); + return Boolean::New( + info.Env(), MaybeUnwrapOr(obj.Delete(jsKey.Utf8Value().c_str()), false)); +} + +Value DeletePropertyWithCppStyleString(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + String jsKey = info[1].As(); + return Boolean::New(info.Env(), + MaybeUnwrapOr(obj.Delete(jsKey.Utf8Value()), false)); +} diff --git a/test/node-addon-api/test/object/delete_property.js b/test/node-addon-api/test/object/delete_property.js new file mode 100644 index 0000000..fa8a5f1 --- /dev/null +++ b/test/node-addon-api/test/object/delete_property.js @@ -0,0 +1,41 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + function testDeleteProperty (nativeDeleteProperty) { + const obj = { one: 1, two: 2 }; + Object.defineProperty(obj, 'three', { configurable: false, value: 3 }); + assert.strictEqual(nativeDeleteProperty(obj, 'one'), true); + assert.strictEqual(nativeDeleteProperty(obj, 'missing'), true); + + /* Returns true for all cases except when the property is an own non- + configurable property, in which case, false is returned in non-strict mode. */ + assert.strictEqual(nativeDeleteProperty(obj, 'three'), false); + assert.deepStrictEqual(obj, { two: 2 }); + } + + function testShouldThrowErrorIfKeyIsInvalid (nativeDeleteProperty) { + assert.throws(() => { + nativeDeleteProperty(undefined, 'test'); + }, /Cannot convert undefined or null to object/); + } + + const testObj = { 15: 42, three: 3 }; + + binding.object.deletePropertyWithUint32(testObj, 15); + + assert.strictEqual(Object.prototype.hasOwnProperty.call(testObj, 15), false); + + testDeleteProperty(binding.object.deletePropertyWithNapiValue); + testDeleteProperty(binding.object.deletePropertyWithNapiWrapperValue); + testDeleteProperty(binding.object.deletePropertyWithCStyleString); + testDeleteProperty(binding.object.deletePropertyWithCppStyleString); + + testShouldThrowErrorIfKeyIsInvalid(binding.object.deletePropertyWithNapiValue); + testShouldThrowErrorIfKeyIsInvalid(binding.object.deletePropertyWithNapiWrapperValue); + testShouldThrowErrorIfKeyIsInvalid(binding.object.deletePropertyWithCStyleString); + testShouldThrowErrorIfKeyIsInvalid(binding.object.deletePropertyWithCppStyleString); +} diff --git a/test/node-addon-api/test/object/finalizer.cc b/test/node-addon-api/test/object/finalizer.cc new file mode 100644 index 0000000..6122e5e --- /dev/null +++ b/test/node-addon-api/test/object/finalizer.cc @@ -0,0 +1,30 @@ +#include "napi.h" + +using namespace Napi; + +static int dummy; + +Value AddFinalizer(const CallbackInfo& info) { + ObjectReference* ref = new ObjectReference; + *ref = Persistent(Object::New(info.Env())); + info[0].As().AddFinalizer( + [](Napi::Env /*env*/, ObjectReference* ref) { + ref->Set("finalizerCalled", true); + delete ref; + }, + ref); + return ref->Value(); +} + +Value AddFinalizerWithHint(const CallbackInfo& info) { + ObjectReference* ref = new ObjectReference; + *ref = Persistent(Object::New(info.Env())); + info[0].As().AddFinalizer( + [](Napi::Env /*env*/, ObjectReference* ref, int* dummy_p) { + ref->Set("finalizerCalledWithCorrectHint", dummy_p == &dummy); + delete ref; + }, + ref, + &dummy); + return ref->Value(); +} diff --git a/test/node-addon-api/test/object/finalizer.js b/test/node-addon-api/test/object/finalizer.js new file mode 100644 index 0000000..be6c98a --- /dev/null +++ b/test/node-addon-api/test/object/finalizer.js @@ -0,0 +1,28 @@ +'use strict'; + +const assert = require('assert'); +const testUtil = require('../testUtil'); + +module.exports = require('../common').runTest(test); + +function createWeakRef (binding, bindingToTest) { + return binding.object[bindingToTest]({}); +} + +function test (binding) { + let obj1; + let obj2; + return testUtil.runGCTests([ + 'addFinalizer', + () => { + obj1 = createWeakRef(binding, 'addFinalizer'); + }, + () => assert.deepStrictEqual(obj1, { finalizerCalled: true }), + + 'addFinalizerWithHint', + () => { + obj2 = createWeakRef(binding, 'addFinalizerWithHint'); + }, + () => assert.deepStrictEqual(obj2, { finalizerCalledWithCorrectHint: true }) + ]); +} diff --git a/test/node-addon-api/test/object/get_property.cc b/test/node-addon-api/test/object/get_property.cc new file mode 100644 index 0000000..2791ad2 --- /dev/null +++ b/test/node-addon-api/test/object/get_property.cc @@ -0,0 +1,34 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +Value GetPropertyWithNapiValue(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Name key = info[1].As(); + return MaybeUnwrapOr(obj.Get(static_cast(key)), Value()); +} + +Value GetPropertyWithNapiWrapperValue(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Name key = info[1].As(); + return MaybeUnwrapOr(obj.Get(key), Value()); +} + +Value GetPropertyWithUint32(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Number key = info[1].As(); + return MaybeUnwrap(obj.Get(key.Uint32Value())); +} + +Value GetPropertyWithCStyleString(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + String jsKey = info[1].As(); + return MaybeUnwrapOr(obj.Get(jsKey.Utf8Value().c_str()), Value()); +} + +Value GetPropertyWithCppStyleString(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + String jsKey = info[1].As(); + return MaybeUnwrapOr(obj.Get(jsKey.Utf8Value()), Value()); +} diff --git a/test/node-addon-api/test/object/get_property.js b/test/node-addon-api/test/object/get_property.js new file mode 100644 index 0000000..fd5e987 --- /dev/null +++ b/test/node-addon-api/test/object/get_property.js @@ -0,0 +1,40 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + function testGetProperty (nativeGetProperty) { + const obj = { test: 1 }; + assert.strictEqual(nativeGetProperty(obj, 'test'), 1); + } + + function testShouldReturnUndefinedIfKeyIsNotPresent (nativeGetProperty) { + const obj = { }; + assert.strictEqual(nativeGetProperty(obj, 'test'), undefined); + } + + function testShouldThrowErrorIfKeyIsInvalid (nativeGetProperty) { + assert.throws(() => { + nativeGetProperty(undefined, 'test'); + }, /Cannot convert undefined or null to object/); + } + + const testObject = { 42: 100 }; + const property = binding.object.getPropertyWithUint32(testObject, 42); + assert.strictEqual(property, 100); + + const nativeFunctions = [ + binding.object.getPropertyWithNapiValue, + binding.object.getPropertyWithNapiWrapperValue, + binding.object.getPropertyWithCStyleString, + binding.object.getPropertyWithCppStyleString + ]; + + nativeFunctions.forEach((nativeFunction) => { + testGetProperty(nativeFunction); + testShouldReturnUndefinedIfKeyIsNotPresent(nativeFunction); + testShouldThrowErrorIfKeyIsInvalid(nativeFunction); + }); +} diff --git a/test/node-addon-api/test/object/has_own_property.cc b/test/node-addon-api/test/object/has_own_property.cc new file mode 100644 index 0000000..b566fef --- /dev/null +++ b/test/node-addon-api/test/object/has_own_property.cc @@ -0,0 +1,34 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +Value HasOwnPropertyWithNapiValue(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Name key = info[1].As(); + return Boolean::New( + info.Env(), + MaybeUnwrapOr(obj.HasOwnProperty(static_cast(key)), false)); +} + +Value HasOwnPropertyWithNapiWrapperValue(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Name key = info[1].As(); + return Boolean::New(info.Env(), + MaybeUnwrapOr(obj.HasOwnProperty(key), false)); +} + +Value HasOwnPropertyWithCStyleString(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + String jsKey = info[1].As(); + return Boolean::New( + info.Env(), + MaybeUnwrapOr(obj.HasOwnProperty(jsKey.Utf8Value().c_str()), false)); +} + +Value HasOwnPropertyWithCppStyleString(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + String jsKey = info[1].As(); + return Boolean::New( + info.Env(), MaybeUnwrapOr(obj.HasOwnProperty(jsKey.Utf8Value()), false)); +} diff --git a/test/node-addon-api/test/object/has_own_property.js b/test/node-addon-api/test/object/has_own_property.js new file mode 100644 index 0000000..1315a47 --- /dev/null +++ b/test/node-addon-api/test/object/has_own_property.js @@ -0,0 +1,34 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + function testHasOwnProperty (nativeHasOwnProperty) { + const obj = { one: 1 }; + + Object.defineProperty(obj, 'two', { value: 2 }); + + assert.strictEqual(nativeHasOwnProperty(obj, 'one'), true); + assert.strictEqual(nativeHasOwnProperty(obj, 'two'), true); + assert.strictEqual('toString' in obj, true); + assert.strictEqual(nativeHasOwnProperty(obj, 'toString'), false); + } + + function testShouldThrowErrorIfKeyIsInvalid (nativeHasOwnProperty) { + assert.throws(() => { + nativeHasOwnProperty(undefined, 'test'); + }, /Cannot convert undefined or null to object/); + } + + testHasOwnProperty(binding.object.hasOwnPropertyWithNapiValue); + testHasOwnProperty(binding.object.hasOwnPropertyWithNapiWrapperValue); + testHasOwnProperty(binding.object.hasOwnPropertyWithCStyleString); + testHasOwnProperty(binding.object.hasOwnPropertyWithCppStyleString); + + testShouldThrowErrorIfKeyIsInvalid(binding.object.hasOwnPropertyWithNapiValue); + testShouldThrowErrorIfKeyIsInvalid(binding.object.hasOwnPropertyWithNapiWrapperValue); + testShouldThrowErrorIfKeyIsInvalid(binding.object.hasOwnPropertyWithCStyleString); + testShouldThrowErrorIfKeyIsInvalid(binding.object.hasOwnPropertyWithCppStyleString); +} diff --git a/test/node-addon-api/test/object/has_property.cc b/test/node-addon-api/test/object/has_property.cc new file mode 100644 index 0000000..46c13de --- /dev/null +++ b/test/node-addon-api/test/object/has_property.cc @@ -0,0 +1,38 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +Value HasPropertyWithNapiValue(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Name key = info[1].As(); + return Boolean::New( + info.Env(), MaybeUnwrapOr(obj.Has(static_cast(key)), false)); +} + +Value HasPropertyWithNapiWrapperValue(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Name key = info[1].As(); + return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Has(key), false)); +} + +Value HasPropertyWithCStyleString(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + String jsKey = info[1].As(); + return Boolean::New(info.Env(), + MaybeUnwrapOr(obj.Has(jsKey.Utf8Value().c_str()), false)); +} + +Value HasPropertyWithUint32(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Number jsKey = info[1].As(); + return Boolean::New(info.Env(), + MaybeUnwrapOr(obj.Has(jsKey.Uint32Value()), false)); +} + +Value HasPropertyWithCppStyleString(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + String jsKey = info[1].As(); + return Boolean::New(info.Env(), + MaybeUnwrapOr(obj.Has(jsKey.Utf8Value()), false)); +} diff --git a/test/node-addon-api/test/object/has_property.js b/test/node-addon-api/test/object/has_property.js new file mode 100644 index 0000000..f2b3a8e --- /dev/null +++ b/test/node-addon-api/test/object/has_property.js @@ -0,0 +1,37 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + function testHasProperty (nativeHasProperty) { + const obj = { one: 1 }; + + Object.defineProperty(obj, 'two', { value: 2 }); + + assert.strictEqual(nativeHasProperty(obj, 'one'), true); + assert.strictEqual(nativeHasProperty(obj, 'two'), true); + assert.strictEqual('toString' in obj, true); + assert.strictEqual(nativeHasProperty(obj, 'toString'), true); + } + + function testShouldThrowErrorIfKeyIsInvalid (nativeHasProperty) { + assert.throws(() => { + nativeHasProperty(undefined, 'test'); + }, /Cannot convert undefined or null to object/); + } + + const objectWithInt32Key = { 12: 101 }; + assert.strictEqual(binding.object.hasPropertyWithUint32(objectWithInt32Key, 12), true); + + testHasProperty(binding.object.hasPropertyWithNapiValue); + testHasProperty(binding.object.hasPropertyWithNapiWrapperValue); + testHasProperty(binding.object.hasPropertyWithCStyleString); + testHasProperty(binding.object.hasPropertyWithCppStyleString); + + testShouldThrowErrorIfKeyIsInvalid(binding.object.hasPropertyWithNapiValue); + testShouldThrowErrorIfKeyIsInvalid(binding.object.hasPropertyWithNapiWrapperValue); + testShouldThrowErrorIfKeyIsInvalid(binding.object.hasPropertyWithCStyleString); + testShouldThrowErrorIfKeyIsInvalid(binding.object.hasPropertyWithCppStyleString); +} diff --git a/test/node-addon-api/test/object/object.cc b/test/node-addon-api/test/object/object.cc new file mode 100644 index 0000000..60aae76 --- /dev/null +++ b/test/node-addon-api/test/object/object.cc @@ -0,0 +1,448 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +// Native wrappers for testing Object::Get() +Value GetPropertyWithUint32(const CallbackInfo& info); +Value GetPropertyWithNapiValue(const CallbackInfo& info); +Value GetPropertyWithNapiWrapperValue(const CallbackInfo& info); +Value GetPropertyWithCStyleString(const CallbackInfo& info); +Value GetPropertyWithCppStyleString(const CallbackInfo& info); + +// Native wrappers for testing Object::Set() +Value SetPropertyWithUint32(const CallbackInfo& info); +Value SetPropertyWithNapiValue(const CallbackInfo& info); +Value SetPropertyWithNapiWrapperValue(const CallbackInfo& info); +Value SetPropertyWithCStyleString(const CallbackInfo& info); +Value SetPropertyWithCppStyleString(const CallbackInfo& info); + +// Native wrappers for testing Object::Delete() +Value DeletePropertyWithUint32(const CallbackInfo& info); +Value DeletePropertyWithNapiValue(const CallbackInfo& info); +Value DeletePropertyWithNapiWrapperValue(const CallbackInfo& info); +Value DeletePropertyWithCStyleString(const CallbackInfo& info); +Value DeletePropertyWithCppStyleString(const CallbackInfo& info); + +// Native wrappers for testing Object::HasOwnProperty() +Value HasOwnPropertyWithNapiValue(const CallbackInfo& info); +Value HasOwnPropertyWithNapiWrapperValue(const CallbackInfo& info); +Value HasOwnPropertyWithCStyleString(const CallbackInfo& info); +Value HasOwnPropertyWithCppStyleString(const CallbackInfo& info); + +// Native wrappers for testing Object::Has() +Value HasPropertyWithUint32(const CallbackInfo& info); +Value HasPropertyWithNapiValue(const CallbackInfo& info); +Value HasPropertyWithNapiWrapperValue(const CallbackInfo& info); +Value HasPropertyWithCStyleString(const CallbackInfo& info); +Value HasPropertyWithCppStyleString(const CallbackInfo& info); + +// Native wrappers for testing Object::AddFinalizer() +Value AddFinalizer(const CallbackInfo& info); +Value AddFinalizerWithHint(const CallbackInfo& info); + +// Native wrappers for testing Object::operator [] +Value SubscriptGetWithCStyleString(const CallbackInfo& info); +Value SubscriptGetWithCppStyleString(const CallbackInfo& info); +Value SubscriptGetAtIndex(const CallbackInfo& info); +void SubscriptSetWithCStyleString(const CallbackInfo& info); +void SubscriptSetWithCppStyleString(const CallbackInfo& info); +void SubscriptSetAtIndex(const CallbackInfo& info); + +static bool testValue = true; +// Used to test void* Data() integrity +struct UserDataHolder { + int32_t value; +}; + +Value TestGetter(const CallbackInfo& info) { + return Boolean::New(info.Env(), testValue); +} + +void TestSetter(const CallbackInfo& info) { + testValue = info[0].As(); +} + +Value TestGetterWithUserData(const CallbackInfo& info) { + const UserDataHolder* holder = reinterpret_cast(info.Data()); + return Number::New(info.Env(), holder->value); +} + +void TestSetterWithUserData(const CallbackInfo& info) { + UserDataHolder* holder = reinterpret_cast(info.Data()); + holder->value = info[0].As().Int32Value(); +} + +Value TestFunction(const CallbackInfo& info) { + return Boolean::New(info.Env(), true); +} + +Value TestFunctionWithUserData(const CallbackInfo& info) { + UserDataHolder* holder = reinterpret_cast(info.Data()); + return Number::New(info.Env(), holder->value); +} + +Value EmptyConstructor(const CallbackInfo& info) { + auto env = info.Env(); + bool isEmpty = info[0].As(); + Object object = isEmpty ? Object() : Object(env, Object::New(env)); + return Boolean::New(env, object.IsEmpty()); +} + +Value ConstructorFromObject(const CallbackInfo& info) { + auto env = info.Env(); + Object object = info[0].As(); + return Object(env, object); +} + +Array GetPropertyNames(const CallbackInfo& info) { + Object obj = info[0].As(); + Array arr = MaybeUnwrap(obj.GetPropertyNames()); + return arr; +} + +void DefineProperties(const CallbackInfo& info) { + Object obj = info[0].As(); + String nameType = info[1].As(); + Env env = info.Env(); + + Boolean trueValue = Boolean::New(env, true); + UserDataHolder* holder = new UserDataHolder(); + holder->value = 1234; + + if (nameType.Utf8Value() == "literal") { + obj.DefineProperties({ + PropertyDescriptor::Accessor(env, obj, "readonlyAccessor", TestGetter), + PropertyDescriptor::Accessor( + env, obj, "readwriteAccessor", TestGetter, TestSetter), + PropertyDescriptor::Accessor(env, + obj, + "readonlyAccessorWithUserData", + TestGetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor(env, + obj, + "readwriteAccessorWithUserData", + TestGetterWithUserData, + TestSetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Accessor("readonlyAccessorT"), + PropertyDescriptor::Accessor( + "readwriteAccessorT"), + PropertyDescriptor::Accessor( + "readonlyAccessorWithUserDataT", + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor( + "readwriteAccessorWithUserDataT", + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Value("readonlyValue", trueValue), + PropertyDescriptor::Value("readwriteValue", trueValue, napi_writable), + PropertyDescriptor::Value( + "enumerableValue", trueValue, napi_enumerable), + PropertyDescriptor::Value( + "configurableValue", trueValue, napi_configurable), + PropertyDescriptor::Function(env, obj, "function", TestFunction), + PropertyDescriptor::Function(env, + obj, + "functionWithUserData", + TestFunctionWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + }); + } else if (nameType.Utf8Value() == "string") { + // VS2013 has lifetime issues when passing temporary objects into the + // constructor of another object. It generates code to destruct the object + // as soon as the constructor call returns. Since this isn't a common case + // for using std::string objects, I'm refactoring the test to work around + // the issue. + std::string str1("readonlyAccessor"); + std::string str2("readwriteAccessor"); + std::string str1a("readonlyAccessorWithUserData"); + std::string str2a("readwriteAccessorWithUserData"); + + std::string str1t("readonlyAccessorT"); + std::string str2t("readwriteAccessorT"); + std::string str1at("readonlyAccessorWithUserDataT"); + std::string str2at("readwriteAccessorWithUserDataT"); + + std::string str3("readonlyValue"); + std::string str4("readwriteValue"); + std::string str5("enumerableValue"); + std::string str6("configurableValue"); + std::string str7("function"); + std::string str8("functionWithUserData"); + + obj.DefineProperties({ + PropertyDescriptor::Accessor(env, obj, str1, TestGetter), + PropertyDescriptor::Accessor(env, obj, str2, TestGetter, TestSetter), + PropertyDescriptor::Accessor(env, + obj, + str1a, + TestGetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor(env, + obj, + str2a, + TestGetterWithUserData, + TestSetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Accessor(str1t), + PropertyDescriptor::Accessor(str2t), + PropertyDescriptor::Accessor( + str1at, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor( + str2at, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Value(str3, trueValue), + PropertyDescriptor::Value(str4, trueValue, napi_writable), + PropertyDescriptor::Value(str5, trueValue, napi_enumerable), + PropertyDescriptor::Value(str6, trueValue, napi_configurable), + PropertyDescriptor::Function(env, obj, str7, TestFunction), + PropertyDescriptor::Function(env, + obj, + str8, + TestFunctionWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + }); + } else if (nameType.Utf8Value() == "value") { + obj.DefineProperties({ + PropertyDescriptor::Accessor( + env, obj, Napi::String::New(env, "readonlyAccessor"), TestGetter), + PropertyDescriptor::Accessor( + env, + obj, + Napi::String::New(env, "readwriteAccessor"), + TestGetter, + TestSetter), + PropertyDescriptor::Accessor( + env, + obj, + Napi::String::New(env, "readonlyAccessorWithUserData"), + TestGetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor( + env, + obj, + Napi::String::New(env, "readwriteAccessorWithUserData"), + TestGetterWithUserData, + TestSetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Accessor( + Napi::String::New(env, "readonlyAccessorT")), + PropertyDescriptor::Accessor( + Napi::String::New(env, "readwriteAccessorT")), + PropertyDescriptor::Accessor( + Napi::String::New(env, "readonlyAccessorWithUserDataT"), + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor( + Napi::String::New(env, "readwriteAccessorWithUserDataT"), + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Value(Napi::String::New(env, "readonlyValue"), + trueValue), + PropertyDescriptor::Value( + Napi::String::New(env, "readwriteValue"), trueValue, napi_writable), + PropertyDescriptor::Value(Napi::String::New(env, "enumerableValue"), + trueValue, + napi_enumerable), + PropertyDescriptor::Value(Napi::String::New(env, "configurableValue"), + trueValue, + napi_configurable), + PropertyDescriptor::Function( + env, obj, Napi::String::New(env, "function"), TestFunction), + PropertyDescriptor::Function( + env, + obj, + Napi::String::New(env, "functionWithUserData"), + TestFunctionWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + }); + } +} + +void DefineValueProperty(const CallbackInfo& info) { + Object obj = info[0].As(); + Name name = info[1].As(); + Value value = info[2]; + + obj.DefineProperty(PropertyDescriptor::Value(name, value)); +} + +Value CreateObjectUsingMagic(const CallbackInfo& info) { + Env env = info.Env(); + Object obj = Object::New(env); + obj["cp_false"] = false; + obj["cp_true"] = true; + obj[std::string("s_true")] = true; + obj[std::string("s_false")] = false; + obj["0"] = 0; + obj[(uint32_t)42] = 120; + obj["0.0f"] = 0.0f; + obj["0.0"] = 0.0; + obj["-1"] = -1; + obj["foo2"] = u"foo"; + obj[std::string("foo4")] = NAPI_WIDE_TEXT("foo"); + obj[std::string("foo5")] = "foo"; + obj[std::string("foo6")] = std::u16string(NAPI_WIDE_TEXT("foo")); + obj[std::string("foo7")] = std::string("foo"); + obj[std::string("circular")] = obj; + obj["circular2"] = obj; + return obj; +} + +#ifdef NAPI_CPP_EXCEPTIONS +Value Sum(const CallbackInfo& info) { + Object object = info[0].As(); + int64_t sum = 0; + + for (const auto& e : object) { + sum += static_cast(e.second).As().Int64Value(); + } + + return Number::New(info.Env(), sum); +} + +void Increment(const CallbackInfo& info) { + Env env = info.Env(); + Object object = info[0].As(); + + for (auto e : object) { + int64_t value = static_cast(e.second).As().Int64Value(); + ++value; + e.second = Napi::Number::New(env, value); + } +} +#endif // NAPI_CPP_EXCEPTIONS + +Value InstanceOf(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Function constructor = info[1].As(); + return Boolean::New(info.Env(), MaybeUnwrap(obj.InstanceOf(constructor))); +} + +Value GetPrototype(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + return MaybeUnwrap(obj.GetPrototype()); +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE +Value SetPrototype(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Object prototype = info[1].UnsafeAs(); + return Boolean::New(info.Env(), MaybeUnwrap(obj.SetPrototype(prototype))); +} +#endif // NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE + +Object InitObject(Env env) { + Object exports = Object::New(env); + + exports["emptyConstructor"] = Function::New(env, EmptyConstructor); + exports["constructorFromObject"] = Function::New(env, ConstructorFromObject); + + exports["GetPropertyNames"] = Function::New(env, GetPropertyNames); + exports["defineProperties"] = Function::New(env, DefineProperties); + exports["defineValueProperty"] = Function::New(env, DefineValueProperty); + + exports["getPropertyWithUint32"] = Function::New(env, GetPropertyWithUint32); + exports["getPropertyWithNapiValue"] = + Function::New(env, GetPropertyWithNapiValue); + exports["getPropertyWithNapiWrapperValue"] = + Function::New(env, GetPropertyWithNapiWrapperValue); + exports["getPropertyWithCStyleString"] = + Function::New(env, GetPropertyWithCStyleString); + exports["getPropertyWithCppStyleString"] = + Function::New(env, GetPropertyWithCppStyleString); + + exports["setPropertyWithUint32"] = Function::New(env, SetPropertyWithUint32); + exports["setPropertyWithNapiValue"] = + Function::New(env, SetPropertyWithNapiValue); + exports["setPropertyWithNapiWrapperValue"] = + Function::New(env, SetPropertyWithNapiWrapperValue); + exports["setPropertyWithCStyleString"] = + Function::New(env, SetPropertyWithCStyleString); + exports["setPropertyWithCppStyleString"] = + Function::New(env, SetPropertyWithCppStyleString); + + exports["deletePropertyWithUint32"] = + Function::New(env, DeletePropertyWithUint32); + exports["deletePropertyWithNapiValue"] = + Function::New(env, DeletePropertyWithNapiValue); + exports["deletePropertyWithNapiWrapperValue"] = + Function::New(env, DeletePropertyWithNapiWrapperValue); + exports["deletePropertyWithCStyleString"] = + Function::New(env, DeletePropertyWithCStyleString); + exports["deletePropertyWithCppStyleString"] = + Function::New(env, DeletePropertyWithCppStyleString); + + exports["hasOwnPropertyWithNapiValue"] = + Function::New(env, HasOwnPropertyWithNapiValue); + exports["hasOwnPropertyWithNapiWrapperValue"] = + Function::New(env, HasOwnPropertyWithNapiWrapperValue); + exports["hasOwnPropertyWithCStyleString"] = + Function::New(env, HasOwnPropertyWithCStyleString); + exports["hasOwnPropertyWithCppStyleString"] = + Function::New(env, HasOwnPropertyWithCppStyleString); + + exports["hasPropertyWithUint32"] = Function::New(env, HasPropertyWithUint32); + exports["hasPropertyWithNapiValue"] = + Function::New(env, HasPropertyWithNapiValue); + exports["hasPropertyWithNapiWrapperValue"] = + Function::New(env, HasPropertyWithNapiWrapperValue); + exports["hasPropertyWithCStyleString"] = + Function::New(env, HasPropertyWithCStyleString); + exports["hasPropertyWithCppStyleString"] = + Function::New(env, HasPropertyWithCppStyleString); + + exports["createObjectUsingMagic"] = + Function::New(env, CreateObjectUsingMagic); +#ifdef NAPI_CPP_EXCEPTIONS + exports["sum"] = Function::New(env, Sum); + exports["increment"] = Function::New(env, Increment); +#endif // NAPI_CPP_EXCEPTIONS + + exports["addFinalizer"] = Function::New(env, AddFinalizer); + exports["addFinalizerWithHint"] = Function::New(env, AddFinalizerWithHint); + + exports["instanceOf"] = Function::New(env, InstanceOf); + + exports["subscriptGetWithCStyleString"] = + Function::New(env, SubscriptGetWithCStyleString); + exports["subscriptGetWithCppStyleString"] = + Function::New(env, SubscriptGetWithCppStyleString); + exports["subscriptGetAtIndex"] = Function::New(env, SubscriptGetAtIndex); + exports["subscriptSetWithCStyleString"] = + Function::New(env, SubscriptSetWithCStyleString); + exports["subscriptSetWithCppStyleString"] = + Function::New(env, SubscriptSetWithCppStyleString); + exports["subscriptSetAtIndex"] = Function::New(env, SubscriptSetAtIndex); + + exports["getPrototype"] = Function::New(env, GetPrototype); +#ifdef NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE + exports["setPrototype"] = Function::New(env, SetPrototype); +#endif // NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE + + return exports; +} diff --git a/test/node-addon-api/test/object/object.js b/test/node-addon-api/test/object/object.js new file mode 100644 index 0000000..1348894 --- /dev/null +++ b/test/node-addon-api/test/object/object.js @@ -0,0 +1,230 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + function assertPropertyIs (obj, key, attribute) { + const propDesc = Object.getOwnPropertyDescriptor(obj, key); + assert.ok(propDesc); + assert.ok(propDesc[attribute]); + } + + function assertPropertyIsNot (obj, key, attribute) { + const propDesc = Object.getOwnPropertyDescriptor(obj, key); + assert.ok(propDesc); + assert.ok(!propDesc[attribute]); + } + + function testDefineProperties (nameType) { + const obj = {}; + binding.object.defineProperties(obj, nameType); + + // accessors + assertPropertyIsNot(obj, 'readonlyAccessor', 'enumerable'); + assertPropertyIsNot(obj, 'readonlyAccessor', 'configurable'); + assert.strictEqual(obj.readonlyAccessor, true); + + assertPropertyIsNot(obj, 'readonlyAccessorWithUserData', 'enumerable'); + assertPropertyIsNot(obj, 'readonlyAccessorWithUserData', 'configurable'); + assert.strictEqual(obj.readonlyAccessorWithUserData, 1234, nameType); + + assertPropertyIsNot(obj, 'readwriteAccessor', 'enumerable'); + assertPropertyIsNot(obj, 'readwriteAccessor', 'configurable'); + obj.readwriteAccessor = false; + assert.strictEqual(obj.readwriteAccessor, false); + obj.readwriteAccessor = true; + assert.strictEqual(obj.readwriteAccessor, true); + + assertPropertyIsNot(obj, 'readwriteAccessorWithUserData', 'enumerable'); + assertPropertyIsNot(obj, 'readwriteAccessorWithUserData', 'configurable'); + obj.readwriteAccessorWithUserData = 2; + assert.strictEqual(obj.readwriteAccessorWithUserData, 2); + obj.readwriteAccessorWithUserData = -14; + assert.strictEqual(obj.readwriteAccessorWithUserData, -14); + + // templated accessors + assertPropertyIsNot(obj, 'readonlyAccessorT', 'enumerable'); + assertPropertyIsNot(obj, 'readonlyAccessorT', 'configurable'); + assert.strictEqual(obj.readonlyAccessorT, true); + + assertPropertyIsNot(obj, 'readonlyAccessorWithUserDataT', 'enumerable'); + assertPropertyIsNot(obj, 'readonlyAccessorWithUserDataT', 'configurable'); + assert.strictEqual(obj.readonlyAccessorWithUserDataT, -14, nameType); + + assertPropertyIsNot(obj, 'readwriteAccessorT', 'enumerable'); + assertPropertyIsNot(obj, 'readwriteAccessorT', 'configurable'); + obj.readwriteAccessorT = false; + assert.strictEqual(obj.readwriteAccessorT, false); + obj.readwriteAccessorT = true; + assert.strictEqual(obj.readwriteAccessorT, true); + + assertPropertyIsNot(obj, 'readwriteAccessorWithUserDataT', 'enumerable'); + assertPropertyIsNot(obj, 'readwriteAccessorWithUserDataT', 'configurable'); + obj.readwriteAccessorWithUserDataT = 2; + assert.strictEqual(obj.readwriteAccessorWithUserDataT, 2); + obj.readwriteAccessorWithUserDataT = -14; + assert.strictEqual(obj.readwriteAccessorWithUserDataT, -14); + + // values + assertPropertyIsNot(obj, 'readonlyValue', 'writable'); + assertPropertyIsNot(obj, 'readonlyValue', 'enumerable'); + assertPropertyIsNot(obj, 'readonlyValue', 'configurable'); + assert.strictEqual(obj.readonlyValue, true); + + assertPropertyIs(obj, 'readwriteValue', 'writable'); + assertPropertyIsNot(obj, 'readwriteValue', 'enumerable'); + assertPropertyIsNot(obj, 'readwriteValue', 'configurable'); + obj.readwriteValue = false; + assert.strictEqual(obj.readwriteValue, false); + obj.readwriteValue = true; + assert.strictEqual(obj.readwriteValue, true); + + assertPropertyIsNot(obj, 'enumerableValue', 'writable'); + assertPropertyIs(obj, 'enumerableValue', 'enumerable'); + assertPropertyIsNot(obj, 'enumerableValue', 'configurable'); + + assertPropertyIsNot(obj, 'configurableValue', 'writable'); + assertPropertyIsNot(obj, 'configurableValue', 'enumerable'); + assertPropertyIs(obj, 'configurableValue', 'configurable'); + + // functions + assertPropertyIsNot(obj, 'function', 'writable'); + assertPropertyIsNot(obj, 'function', 'enumerable'); + assertPropertyIsNot(obj, 'function', 'configurable'); + assert.strictEqual(obj.function(), true); + assert.strictEqual(obj.functionWithUserData(), obj.readonlyAccessorWithUserDataT); + } + + testDefineProperties('literal'); + testDefineProperties('string'); + testDefineProperties('value'); + + // eslint-disable-next-line no-lone-blocks + { + assert.strictEqual(binding.object.emptyConstructor(true), true); + assert.strictEqual(binding.object.emptyConstructor(false), false); + } + + { + const expected = { one: 1, two: 2, three: 3 }; + const actual = binding.object.constructorFromObject(expected); + assert.deepStrictEqual(actual, expected); + } + + { + const obj = {}; + const testSym = Symbol('testSym'); + binding.object.defineValueProperty(obj, testSym, 1); + assert.strictEqual(obj[testSym], 1); + } + + { + const testSym = Symbol('testSym'); + const obj = { one: 1, two: 2, three: 3, [testSym]: 4 }; + const arr = binding.object.GetPropertyNames(obj); + assert.deepStrictEqual(arr, ['one', 'two', 'three']); + } + + { + const magicObject = binding.object.createObjectUsingMagic(); + assert.deepStrictEqual(magicObject, { + 0: 0, + 42: 120, + cp_false: false, + cp_true: true, + s_true: true, + s_false: false, + '0.0f': 0, + '0.0': 0, + '-1': -1, + foo2: 'foo', + foo4: 'foo', + foo5: 'foo', + foo6: 'foo', + foo7: 'foo', + circular: magicObject, + circular2: magicObject + }); + } + + { + function Ctor () {} + + assert.strictEqual(binding.object.instanceOf(new Ctor(), Ctor), true); + assert.strictEqual(binding.object.instanceOf(new Ctor(), Object), true); + assert.strictEqual(binding.object.instanceOf({}, Ctor), false); + assert.strictEqual(binding.object.instanceOf(null, Ctor), false); + } + + if ('sum' in binding.object) { + { + const obj = { + '-forbid': -0x4B1D, + '-feedcode': -0xFEEDC0DE, + '+office': +0x0FF1CE, + '+forbid': +0x4B1D, + '+deadbeef': +0xDEADBEEF, + '+feedcode': +0xFEEDC0DE + }; + + let sum = 0; + for (const key in obj) { + sum += obj[key]; + } + + assert.strictEqual(binding.object.sum(obj), sum); + } + + { + const obj = new Proxy({ + '-forbid': -0x4B1D, + '-feedcode': -0xFEEDC0DE, + '+office': +0x0FF1CE, + '+forbid': +0x4B1D, + '+deadbeef': +0xDEADBEEF, + '+feedcode': +0xFEEDC0DE + }, { + getOwnPropertyDescriptor (target, p) { + throw new Error('getOwnPropertyDescriptor error'); + }, + ownKeys (target) { + throw new Error('ownKeys error'); + } + }); + + assert.throws(() => { + binding.object.sum(obj); + }, /ownKeys error/); + } + } + + if ('increment' in binding.object) { + const obj = { + a: 0, + b: 1, + c: 2 + }; + + binding.object.increment(obj); + + assert.deepStrictEqual(obj, { + a: 1, + b: 2, + c: 3 + }); + } + + for (const prototype of [null, {}, Object.prototype]) { + const obj = Object.create(prototype); + assert.strictEqual(binding.object.getPrototype(obj), prototype); + } + + if ('setPrototype' in binding.object) { + const prototype = {}; + const obj = Object.create(null); + assert.strictEqual(binding.object.setPrototype(obj, prototype), true); + assert.strictEqual(Object.getPrototypeOf(obj), prototype); + } +} diff --git a/test/node-addon-api/test/object/object_deprecated.cc b/test/node-addon-api/test/object/object_deprecated.cc new file mode 100644 index 0000000..e5b9f01 --- /dev/null +++ b/test/node-addon-api/test/object/object_deprecated.cc @@ -0,0 +1,70 @@ +#include "napi.h" + +using namespace Napi; + +static bool testValue = true; + +namespace { + +Value TestGetter(const CallbackInfo& info) { + return Boolean::New(info.Env(), testValue); +} + +void TestSetter(const CallbackInfo& info) { + testValue = info[0].As(); +} + +Value TestFunction(const CallbackInfo& info) { + return Boolean::New(info.Env(), true); +} + +void DefineProperties(const CallbackInfo& info) { + Object obj = info[0].As(); + String nameType = info[1].As(); + Env env = info.Env(); + + if (nameType.Utf8Value() == "literal") { + obj.DefineProperties({ + PropertyDescriptor::Accessor("readonlyAccessor", TestGetter), + PropertyDescriptor::Accessor( + "readwriteAccessor", TestGetter, TestSetter), + PropertyDescriptor::Function("function", TestFunction), + }); + } else if (nameType.Utf8Value() == "string") { + // VS2013 has lifetime issues when passing temporary objects into the + // constructor of another object. It generates code to destruct the object + // as soon as the constructor call returns. Since this isn't a common case + // for using std::string objects, I'm refactoring the test to work around + // the issue. + std::string str1("readonlyAccessor"); + std::string str2("readwriteAccessor"); + std::string str7("function"); + + obj.DefineProperties({ + PropertyDescriptor::Accessor(str1, TestGetter), + PropertyDescriptor::Accessor(str2, TestGetter, TestSetter), + PropertyDescriptor::Function(str7, TestFunction), + }); + } else if (nameType.Utf8Value() == "value") { + obj.DefineProperties({ + PropertyDescriptor::Accessor(Napi::String::New(env, "readonlyAccessor"), + TestGetter), + PropertyDescriptor::Accessor( + Napi::String::New(env, "readwriteAccessor"), + TestGetter, + TestSetter), + PropertyDescriptor::Function(Napi::String::New(env, "function"), + TestFunction), + }); + } +} + +} // end of anonymous namespace + +Object InitObjectDeprecated(Env env) { + Object exports = Object::New(env); + + exports["defineProperties"] = Function::New(env, DefineProperties); + + return exports; +} diff --git a/test/node-addon-api/test/object/object_deprecated.js b/test/node-addon-api/test/object/object_deprecated.js new file mode 100644 index 0000000..06cc099 --- /dev/null +++ b/test/node-addon-api/test/object/object_deprecated.js @@ -0,0 +1,42 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + if (!('object_deprecated' in binding)) { + return; + } + + function assertPropertyIsNot (obj, key, attribute) { + const propDesc = Object.getOwnPropertyDescriptor(obj, key); + assert.ok(propDesc); + assert.ok(!propDesc[attribute]); + } + + function testDefineProperties (nameType) { + const obj = {}; + binding.object.defineProperties(obj, nameType); + + assertPropertyIsNot(obj, 'readonlyAccessor', 'enumerable'); + assertPropertyIsNot(obj, 'readonlyAccessor', 'configurable'); + assert.strictEqual(obj.readonlyAccessor, true); + + assertPropertyIsNot(obj, 'readwriteAccessor', 'enumerable'); + assertPropertyIsNot(obj, 'readwriteAccessor', 'configurable'); + obj.readwriteAccessor = false; + assert.strictEqual(obj.readwriteAccessor, false); + obj.readwriteAccessor = true; + assert.strictEqual(obj.readwriteAccessor, true); + + assertPropertyIsNot(obj, 'function', 'writable'); + assertPropertyIsNot(obj, 'function', 'enumerable'); + assertPropertyIsNot(obj, 'function', 'configurable'); + assert.strictEqual(obj.function(), true); + } + + testDefineProperties('literal'); + testDefineProperties('string'); + testDefineProperties('value'); +} diff --git a/test/node-addon-api/test/object/object_freeze_seal.cc b/test/node-addon-api/test/object/object_freeze_seal.cc new file mode 100644 index 0000000..40aaeb4 --- /dev/null +++ b/test/node-addon-api/test/object/object_freeze_seal.cc @@ -0,0 +1,25 @@ +#include "napi.h" +#include "test_helper.h" + +#if (NAPI_VERSION > 7) + +using namespace Napi; + +Value Freeze(const CallbackInfo& info) { + Object obj = info[0].As(); + return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Freeze(), false)); +} + +Value Seal(const CallbackInfo& info) { + Object obj = info[0].As(); + return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Seal(), false)); +} + +Object InitObjectFreezeSeal(Env env) { + Object exports = Object::New(env); + exports["freeze"] = Function::New(env, Freeze); + exports["seal"] = Function::New(env, Seal); + return exports; +} + +#endif diff --git a/test/node-addon-api/test/object/object_freeze_seal.js b/test/node-addon-api/test/object/object_freeze_seal.js new file mode 100644 index 0000000..7a8b5ca --- /dev/null +++ b/test/node-addon-api/test/object/object_freeze_seal.js @@ -0,0 +1,61 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + { + const obj = { x: 'a', y: 'b', z: 'c' }; + assert.strictEqual(binding.object_freeze_seal.freeze(obj), true); + assert.strictEqual(Object.isFrozen(obj), true); + assert.throws(() => { + obj.x = 10; + }, TypeError); // quickjs-napi: V8 message /Cannot assign to read only property 'x' of object '#/ + assert.throws(() => { + obj.w = 15; + }, TypeError); // quickjs-napi: V8 message /Cannot add property w, object is not extensible/ + assert.throws(() => { + delete obj.x; + }, TypeError); // quickjs-napi: V8 message /Cannot delete property 'x' of #/ + } + + { + const obj = new Proxy({ x: 'a', y: 'b', z: 'c' }, { + preventExtensions () { + throw new Error('foo'); + } + }); + + assert.throws(() => { + binding.object_freeze_seal.freeze(obj); + }, /foo/); + } + + { + const obj = { x: 'a', y: 'b', z: 'c' }; + assert.strictEqual(binding.object_freeze_seal.seal(obj), true); + assert.strictEqual(Object.isSealed(obj), true); + assert.throws(() => { + obj.w = 'd'; + }, TypeError); // quickjs-napi: V8 message /Cannot add property w, object is not extensible/ + assert.throws(() => { + delete obj.x; + }, TypeError); // quickjs-napi: V8 message /Cannot delete property 'x' of #/ + // Sealed objects allow updating existing properties, + // so this should not throw. + obj.x = 'd'; + } + + { + const obj = new Proxy({ x: 'a', y: 'b', z: 'c' }, { + preventExtensions () { + throw new Error('foo'); + } + }); + + assert.throws(() => { + binding.object_freeze_seal.seal(obj); + }, /foo/); + } +} diff --git a/test/node-addon-api/test/object/set_property.cc b/test/node-addon-api/test/object/set_property.cc new file mode 100644 index 0000000..da8c93b --- /dev/null +++ b/test/node-addon-api/test/object/set_property.cc @@ -0,0 +1,45 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +Value SetPropertyWithNapiValue(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Name key = info[1].As(); + Value value = info[2]; + return Boolean::New( + info.Env(), + MaybeUnwrapOr(obj.Set(static_cast(key), value), false)); +} + +Value SetPropertyWithNapiWrapperValue(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Name key = info[1].As(); + Value value = info[2]; + return Boolean::New(info.Env(), MaybeUnwrapOr(obj.Set(key, value), false)); +} + +Value SetPropertyWithUint32(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + Number key = info[1].As(); + Value value = info[2]; + return Boolean::New(info.Env(), + MaybeUnwrapOr(obj.Set(key.Uint32Value(), value), false)); +} + +Value SetPropertyWithCStyleString(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + String jsKey = info[1].As(); + Value value = info[2]; + return Boolean::New( + info.Env(), + MaybeUnwrapOr(obj.Set(jsKey.Utf8Value().c_str(), value), false)); +} + +Value SetPropertyWithCppStyleString(const CallbackInfo& info) { + Object obj = info[0].UnsafeAs(); + String jsKey = info[1].As(); + Value value = info[2]; + return Boolean::New(info.Env(), + MaybeUnwrapOr(obj.Set(jsKey.Utf8Value(), value), false)); +} diff --git a/test/node-addon-api/test/object/set_property.js b/test/node-addon-api/test/object/set_property.js new file mode 100644 index 0000000..b2a5fa1 --- /dev/null +++ b/test/node-addon-api/test/object/set_property.js @@ -0,0 +1,30 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + function testSetProperty (nativeSetProperty, key = 'test') { + const obj = {}; + assert.strictEqual(nativeSetProperty(obj, key, 1), true); + assert.strictEqual(obj[key], 1); + } + + function testShouldThrowErrorIfKeyIsInvalid (nativeSetProperty) { + assert.throws(() => { + nativeSetProperty(undefined, 'test', 1); + }, /Cannot convert undefined or null to object/); + } + + testSetProperty(binding.object.setPropertyWithNapiValue); + testSetProperty(binding.object.setPropertyWithNapiWrapperValue); + testSetProperty(binding.object.setPropertyWithCStyleString); + testSetProperty(binding.object.setPropertyWithCppStyleString); + testSetProperty(binding.object.setPropertyWithUint32, 12); + + testShouldThrowErrorIfKeyIsInvalid(binding.object.setPropertyWithNapiValue); + testShouldThrowErrorIfKeyIsInvalid(binding.object.setPropertyWithNapiWrapperValue); + testShouldThrowErrorIfKeyIsInvalid(binding.object.setPropertyWithCStyleString); + testShouldThrowErrorIfKeyIsInvalid(binding.object.setPropertyWithCppStyleString); +} diff --git a/test/node-addon-api/test/object/subscript_operator.cc b/test/node-addon-api/test/object/subscript_operator.cc new file mode 100644 index 0000000..15bb746 --- /dev/null +++ b/test/node-addon-api/test/object/subscript_operator.cc @@ -0,0 +1,58 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +Value SubscriptGetWithCStyleString(const CallbackInfo& info) { + String jsKey = info[1].As(); + + // make sure const case compiles + const Object obj2 = info[0].As(); + MaybeUnwrap(obj2[jsKey.Utf8Value().c_str()]).As(); + + Object obj = info[0].As(); + return obj[jsKey.Utf8Value().c_str()]; +} + +Value SubscriptGetWithCppStyleString(const CallbackInfo& info) { + String jsKey = info[1].As(); + + // make sure const case compiles + const Object obj2 = info[0].As(); + MaybeUnwrap(obj2[jsKey.Utf8Value()]).As(); + + Object obj = info[0].As(); + return obj[jsKey.Utf8Value()]; +} + +Value SubscriptGetAtIndex(const CallbackInfo& info) { + uint32_t index = info[1].As(); + + // make sure const case compiles + const Object obj2 = info[0].As(); + MaybeUnwrap(obj2[index]).As(); + + Object obj = info[0].As(); + return obj[index]; +} + +void SubscriptSetWithCStyleString(const CallbackInfo& info) { + Object obj = info[0].As(); + String jsKey = info[1].As(); + Value value = info[2]; + obj[jsKey.Utf8Value().c_str()] = value; +} + +void SubscriptSetWithCppStyleString(const CallbackInfo& info) { + Object obj = info[0].As(); + String jsKey = info[1].As(); + Value value = info[2]; + obj[jsKey.Utf8Value()] = value; +} + +void SubscriptSetAtIndex(const CallbackInfo& info) { + Object obj = info[0].As(); + uint32_t index = info[1].As(); + Value value = info[2]; + obj[index] = value; +} diff --git a/test/node-addon-api/test/object/subscript_operator.js b/test/node-addon-api/test/object/subscript_operator.js new file mode 100644 index 0000000..4d0c544 --- /dev/null +++ b/test/node-addon-api/test/object/subscript_operator.js @@ -0,0 +1,17 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +function test (binding) { + function testProperty (obj, key, value, nativeGetProperty, nativeSetProperty) { + nativeSetProperty(obj, key, value); + assert.strictEqual(nativeGetProperty(obj, key), value); + } + + testProperty({}, 'key', 'value', binding.object.subscriptGetWithCStyleString, binding.object.subscriptSetWithCStyleString); + testProperty({ key: 'override me' }, 'key', 'value', binding.object.subscriptGetWithCppStyleString, binding.object.subscriptSetWithCppStyleString); + testProperty({}, 0, 'value', binding.object.subscriptGetAtIndex, binding.object.subscriptSetAtIndex); + testProperty({ key: 'override me' }, 0, 'value', binding.object.subscriptGetAtIndex, binding.object.subscriptSetAtIndex); +} diff --git a/test/node-addon-api/test/object_reference.cc b/test/node-addon-api/test/object_reference.cc new file mode 100644 index 0000000..691b5f6 --- /dev/null +++ b/test/node-addon-api/test/object_reference.cc @@ -0,0 +1,437 @@ +/* ObjectReference can be used to create references to Values that +are not Objects by creating a blank Object and setting Values to +it. Subclasses of Objects can only be set using an ObjectReference +by first casting it as an Object. */ +#include "assert.h" +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +ObjectReference weak; +ObjectReference persistent; +ObjectReference reference; + +ObjectReference casted_weak; +ObjectReference casted_persistent; +ObjectReference casted_reference; + +// Set keys can be one of: +// C style string, std::string& utf8, and const char * + +// Set values can be one of: +// Napi::Value +// napi_value (req static_cast) +// const char* (c style string) +// boolean +// double + +enum VAL_TYPES { JS = 0, C_STR, CPP_STR, BOOL, INT, DOUBLE, JS_CAST }; + +// Test that Set() with std::string key and value accepts temporaries (rvalues). +// This verifies that the parameter is `const std::string&` rather than +// `std::string&`. +void SetWithTempString(const Napi::CallbackInfo& info) { + Env env = info.Env(); + HandleScope scope(env); + + Napi::ObjectReference ref = Persistent(Object::New(env)); + ref.SuppressDestruct(); + + ref.Set(std::string("tempKey"), std::string("tempValue")); + ref.Set(std::string("anotherKey"), info[0].As().Utf8Value()); + + assert(MaybeUnwrap(ref.Get("tempKey")).As().Utf8Value() == + "tempValue"); + assert(MaybeUnwrap(ref.Get("anotherKey")).As().Utf8Value() == + info[0].As().Utf8Value()); +} + +void MoveOperatorsTest(const Napi::CallbackInfo& info) { + Napi::ObjectReference existingRef; + Napi::ObjectReference existingRef2; + Napi::Object testObject = Napi::Object::New(info.Env()); + testObject.Set("testProp", "tProp"); + + // ObjectReference(Reference&& other); + Napi::Reference refObj = + Napi::Reference::New(testObject); + Napi::ObjectReference objRef = std::move(refObj); + std::string prop = MaybeUnwrap(objRef.Get("testProp")).As(); + assert(prop == "tProp"); + + // ObjectReference& operator=(Reference&& other); + Napi::Reference refObj2 = + Napi::Reference::New(testObject); + existingRef = std::move(refObj2); + prop = MaybeUnwrap(existingRef.Get("testProp")).As(); + assert(prop == "tProp"); + + // ObjectReference(ObjectReference&& other); + Napi::ObjectReference objRef3 = std::move(existingRef); + prop = MaybeUnwrap(objRef3.Get("testProp")).As(); + assert(prop == "tProp"); + + // ObjectReference& operator=(ObjectReference&& other); + existingRef2 = std::move(objRef3); + prop = MaybeUnwrap(objRef.Get("testProp")).As(); + assert(prop == "tProp"); +} + +void SetObjectWithCStringKey(Napi::ObjectReference& obj, + Napi::Value key, + Napi::Value val, + int valType) { + std::string c_key = key.As().Utf8Value(); + switch (valType) { + case JS: + obj.Set(c_key.c_str(), val); + break; + + case JS_CAST: + obj.Set(c_key.c_str(), static_cast(val)); + break; + + case C_STR: { + std::string c_val = val.As().Utf8Value(); + obj.Set(c_key.c_str(), c_val.c_str()); + break; + } + + case BOOL: + obj.Set(c_key.c_str(), val.As().Value()); + break; + + case DOUBLE: + obj.Set(c_key.c_str(), val.As().DoubleValue()); + break; + } +} + +void SetObjectWithCppStringKey(Napi::ObjectReference& obj, + Napi::Value key, + Napi::Value val, + int valType) { + std::string c_key = key.As(); + switch (valType) { + case JS: + obj.Set(c_key, val); + break; + + case JS_CAST: + obj.Set(c_key, static_cast(val)); + break; + + case CPP_STR: { + std::string c_val = val.As(); + obj.Set(c_key, c_val); + break; + } + + case BOOL: + obj.Set(c_key, val.As().Value()); + break; + + case DOUBLE: + obj.Set(c_key, val.As().DoubleValue()); + break; + } +} + +void SetObjectWithIntKey(Napi::ObjectReference& obj, + Napi::Value key, + Napi::Value val, + int valType) { + uint32_t c_key = key.As().Uint32Value(); + switch (valType) { + case JS: + obj.Set(c_key, val); + break; + + case JS_CAST: + obj.Set(c_key, static_cast(val)); + break; + + case C_STR: { + std::string c_val = val.As(); + obj.Set(c_key, c_val.c_str()); + break; + } + + case CPP_STR: { + std::string cpp_val = val.As(); + obj.Set(c_key, cpp_val); + break; + } + + case BOOL: + obj.Set(c_key, val.As().Value()); + break; + + case DOUBLE: + obj.Set(c_key, val.As().DoubleValue()); + break; + } +} + +void SetObject(const Napi::CallbackInfo& info) { + Env env = info.Env(); + HandleScope scope(env); + + weak = Weak(Object::New(env)); + weak.SuppressDestruct(); + + persistent = Persistent(Object::New(env)); + persistent.SuppressDestruct(); + + reference = Reference::New(Object::New(env), 2); + reference.SuppressDestruct(); + + Napi::Object configObject = info[0].As(); + + int keyType = + MaybeUnwrap(configObject.Get("keyType")).As().Uint32Value(); + int valType = + MaybeUnwrap(configObject.Get("valType")).As().Uint32Value(); + Napi::Value key = MaybeUnwrap(configObject.Get("key")); + Napi::Value val = MaybeUnwrap(configObject.Get("val")); + + switch (keyType) { + case CPP_STR: + SetObjectWithCppStringKey(weak, key, val, valType); + SetObjectWithCppStringKey(persistent, key, val, valType); + SetObjectWithCppStringKey(reference, key, val, valType); + break; + + case C_STR: + SetObjectWithCStringKey(weak, key, val, valType); + SetObjectWithCStringKey(persistent, key, val, valType); + SetObjectWithCStringKey(reference, key, val, valType); + break; + + case INT: + SetObjectWithIntKey(weak, key, val, valType); + SetObjectWithIntKey(persistent, key, val, valType); + SetObjectWithIntKey(reference, key, val, valType); + + default: + break; + } +} + +void SetCastedObjects(const CallbackInfo& info) { + Env env = info.Env(); + HandleScope scope(env); + + Array ex = Array::New(env); + ex.Set((uint32_t)0, String::New(env, "hello")); + ex.Set(1, String::New(env, "world")); + ex.Set(2, String::New(env, "!")); + + casted_weak = Weak(ex.As()); + casted_weak.SuppressDestruct(); + + casted_persistent = Persistent(ex.As()); + casted_persistent.SuppressDestruct(); + + casted_reference = Reference::New(ex.As(), 2); + casted_reference.SuppressDestruct(); +} + +// info[0] is a flag to determine if the weak, persistent, or +// multiple reference ObjectReference is being requested. +Value GetFromValue(const CallbackInfo& info) { + Env env = info.Env(); + + if (info[0] == String::New(env, "weak")) { + if (weak.IsEmpty()) { + return String::New(env, "No Referenced Value"); + } else { + return weak.Value(); + } + } else if (info[0] == String::New(env, "persistent")) { + return persistent.Value(); + } else { + return reference.Value(); + } +} + +Value GetHelper(ObjectReference& ref, + Object& configObject, + const Napi::Env& env) { + int keyType = + MaybeUnwrap(configObject.Get("keyType")).As().Uint32Value(); + if (ref.IsEmpty()) { + return String::New(env, "No referenced Value"); + } + + switch (keyType) { + case C_STR: { + std::string c_key = + MaybeUnwrap(configObject.Get("key")).As().Utf8Value(); + return MaybeUnwrap(ref.Get(c_key.c_str())); + break; + } + case CPP_STR: { + std::string cpp_key = + MaybeUnwrap(configObject.Get("key")).As().Utf8Value(); + return MaybeUnwrap(ref.Get(cpp_key)); + break; + } + case INT: { + uint32_t key = + MaybeUnwrap(configObject.Get("key")).As().Uint32Value(); + return MaybeUnwrap(ref.Get(key)); + break; + } + + default: + return String::New(env, "Error: Reached end of getter"); + break; + } +} + +Value GetFromGetters(const CallbackInfo& info) { + std::string object_req = info[0].As(); + Object configObject = info[1].As(); + if (object_req == "weak") { + return GetHelper(weak, configObject, info.Env()); + } else if (object_req == "persistent") { + return GetHelper(persistent, configObject, info.Env()); + } + + return GetHelper(reference, configObject, info.Env()); +} + +// info[0] is a flag to determine if the weak, persistent, or +// multiple reference ObjectReference is being requested. +// info[1] is the key, and it be either a String or a Number. +Value GetFromGetter(const CallbackInfo& info) { + Env env = info.Env(); + + if (info[0] == String::New(env, "weak")) { + if (weak.IsEmpty()) { + return String::New(env, "No Referenced Value"); + } else { + if (info[1].IsString()) { + return MaybeUnwrap(weak.Get(info[1].As().Utf8Value())); + } else if (info[1].IsNumber()) { + return MaybeUnwrap(weak.Get(info[1].As().Uint32Value())); + } + } + } else if (info[0] == String::New(env, "persistent")) { + if (info[1].IsString()) { + return MaybeUnwrap(persistent.Get(info[1].As().Utf8Value())); + } else if (info[1].IsNumber()) { + return MaybeUnwrap(persistent.Get(info[1].As().Uint32Value())); + } + } else { + if (info[0].IsString()) { + return MaybeUnwrap(reference.Get(info[0].As().Utf8Value())); + } else if (info[0].IsNumber()) { + return MaybeUnwrap(reference.Get(info[0].As().Uint32Value())); + } + } + + return String::New(env, "Error: Reached end of getter"); +} + +// info[0] is a flag to determine if the weak, persistent, or +// multiple reference ObjectReference is being requested. +Value GetCastedFromValue(const CallbackInfo& info) { + Env env = info.Env(); + + if (info[0] == String::New(env, "weak")) { + if (casted_weak.IsEmpty()) { + return String::New(env, "No Referenced Value"); + } else { + return casted_weak.Value(); + } + } else if (info[0] == String::New(env, "persistent")) { + return casted_persistent.Value(); + } else { + return casted_reference.Value(); + } +} + +// info[0] is a flag to determine if the weak, persistent, or +// multiple reference ObjectReference is being requested. +// info[1] is the key and it must be a Number. +Value GetCastedFromGetter(const CallbackInfo& info) { + Env env = info.Env(); + + if (info[0] == String::New(env, "weak")) { + if (casted_weak.IsEmpty()) { + return String::New(env, "No Referenced Value"); + } else { + return MaybeUnwrap(casted_weak.Get(info[1].As())); + } + } else if (info[0] == String::New(env, "persistent")) { + return MaybeUnwrap(casted_persistent.Get(info[1].As())); + } else { + return MaybeUnwrap(casted_reference.Get(info[1].As())); + } +} + +// info[0] is a flag to determine if the weak, persistent, or +// multiple reference ObjectReference is being requested. +Number UnrefObjects(const CallbackInfo& info) { + Env env = info.Env(); + uint32_t num; + + if (info[0] == String::New(env, "weak")) { + num = weak.Unref(); + } else if (info[0] == String::New(env, "persistent")) { + num = persistent.Unref(); + } else if (info[0] == String::New(env, "references")) { + num = reference.Unref(); + } else if (info[0] == String::New(env, "casted weak")) { + num = casted_weak.Unref(); + } else if (info[0] == String::New(env, "casted persistent")) { + num = casted_persistent.Unref(); + } else { + num = casted_reference.Unref(); + } + + return Number::New(env, num); +} + +// info[0] is a flag to determine if the weak, persistent, or +// multiple reference ObjectReference is being requested. +Number RefObjects(const CallbackInfo& info) { + Env env = info.Env(); + uint32_t num; + + if (info[0] == String::New(env, "weak")) { + num = weak.Ref(); + } else if (info[0] == String::New(env, "persistent")) { + num = persistent.Ref(); + } else if (info[0] == String::New(env, "references")) { + num = reference.Ref(); + } else if (info[0] == String::New(env, "casted weak")) { + num = casted_weak.Ref(); + } else if (info[0] == String::New(env, "casted persistent")) { + num = casted_persistent.Ref(); + } else { + num = casted_reference.Ref(); + } + + return Number::New(env, num); +} + +Object InitObjectReference(Env env) { + Object exports = Object::New(env); + + exports["setCastedObjects"] = Function::New(env, SetCastedObjects); + exports["setObject"] = Function::New(env, SetObject); + exports["getCastedFromValue"] = Function::New(env, GetCastedFromValue); + exports["getFromGetters"] = Function::New(env, GetFromGetters); + exports["getCastedFromGetter"] = Function::New(env, GetCastedFromGetter); + exports["getFromValue"] = Function::New(env, GetFromValue); + exports["unrefObjects"] = Function::New(env, UnrefObjects); + exports["refObjects"] = Function::New(env, RefObjects); + exports["moveOpTest"] = Function::New(env, MoveOperatorsTest); + exports["setWithTempString"] = Function::New(env, SetWithTempString); + + return exports; +} diff --git a/test/node-addon-api/test/object_reference.js b/test/node-addon-api/test/object_reference.js new file mode 100644 index 0000000..5b713dc --- /dev/null +++ b/test/node-addon-api/test/object_reference.js @@ -0,0 +1,264 @@ +/* + * First tests are for setting and getting the ObjectReference on the + * casted Array as Object. Then the tests are for the ObjectReference + * to an empty Object. They test setting the ObjectReference with a C + * string, a JavaScript string, and a JavaScript Number as the keys. + * Then getting the value of those keys through the Reference function + * Value() and through the ObjectReference getters. Finally, they test + * Unref() and Ref() to determine if the reference count is as + * expected and errors are thrown when expected. + */ + +'use strict'; + +const assert = require('assert'); +const testUtil = require('./testUtil'); + +module.exports = require('./common').runTest(test); + +const enumType = { + JS: 0, // Napi::Value + C_STR: 1, // const char * + CPP_STR: 2, // std::string + BOOL: 3, // bool + INT: 4, // uint32_t + DOUBLE: 5, // double + JS_CAST: 6 // napi_value +}; + +const configObjects = [ + { keyType: enumType.C_STR, valType: enumType.JS, key: 'hello', val: 'worlds' }, + { keyType: enumType.C_STR, valType: enumType.C_STR, key: 'hello', val: 'worldd' }, + { keyType: enumType.C_STR, valType: enumType.BOOL, key: 'hello', val: false }, + { keyType: enumType.C_STR, valType: enumType.DOUBLE, key: 'hello', val: 3.56 }, + { keyType: enumType.C_STR, valType: enumType.JS_CAST, key: 'hello_cast', val: 'world' }, + { keyType: enumType.CPP_STR, valType: enumType.JS, key: 'hello_cpp', val: 'world_js' }, + { keyType: enumType.CPP_STR, valType: enumType.JS_CAST, key: 'hello_cpp', val: 'world_js_cast' }, + { keyType: enumType.CPP_STR, valType: enumType.CPP_STR, key: 'hello_cpp', val: 'world_cpp_str' }, + { keyType: enumType.CPP_STR, valType: enumType.BOOL, key: 'hello_cpp', val: true }, + { keyType: enumType.CPP_STR, valType: enumType.DOUBLE, key: 'hello_cpp', val: 3.58 }, + { keyType: enumType.INT, valType: enumType.JS, key: 1, val: 'hello world' }, + { keyType: enumType.INT, valType: enumType.JS_CAST, key: 2, val: 'hello world' }, + { keyType: enumType.INT, valType: enumType.C_STR, key: 3, val: 'hello world' }, + { keyType: enumType.INT, valType: enumType.CPP_STR, key: 8, val: 'hello world' }, + { keyType: enumType.INT, valType: enumType.BOOL, key: 3, val: false }, + { keyType: enumType.INT, valType: enumType.DOUBLE, key: 4, val: 3.14159 } +]; + +function test (binding) { + binding.objectreference.moveOpTest(); + binding.objectreference.setWithTempString('testValue'); + + function testCastedEqual (testToCompare) { + const compareTest = ['hello', 'world', '!']; + if (testToCompare instanceof Array) { + assert.deepEqual(compareTest, testToCompare); + } else if (testToCompare instanceof String) { + assert.deepEqual('No Referenced Value', testToCompare); + } else { + assert.fail(); + } + } + + return testUtil.runGCTests([ + 'Weak Casted Array', + () => { + binding.objectreference.setCastedObjects(); + const test = binding.objectreference.getCastedFromValue('weak'); + const test2 = []; + test2[0] = binding.objectreference.getCastedFromGetter('weak', 0); + test2[1] = binding.objectreference.getCastedFromGetter('weak', 1); + test2[2] = binding.objectreference.getCastedFromGetter('weak', 2); + + testCastedEqual(test); + testCastedEqual(test2); + }, + + 'Persistent Casted Array', + () => { + binding.objectreference.setCastedObjects(); + const test = binding.objectreference.getCastedFromValue('persistent'); + const test2 = []; + test2[0] = binding.objectreference.getCastedFromGetter('persistent', 0); + test2[1] = binding.objectreference.getCastedFromGetter('persistent', 1); + test2[2] = binding.objectreference.getCastedFromGetter('persistent', 2); + + assert.ok(test instanceof Array); + assert.ok(test2 instanceof Array); + testCastedEqual(test); + testCastedEqual(test2); + }, + + 'References Casted Array', + () => { + binding.objectreference.setCastedObjects(); + const test = binding.objectreference.getCastedFromValue(); + const test2 = []; + test2[0] = binding.objectreference.getCastedFromGetter('reference', 0); + test2[1] = binding.objectreference.getCastedFromGetter('reference', 1); + test2[2] = binding.objectreference.getCastedFromGetter('reference', 2); + + assert.ok(test instanceof Array); + assert.ok(test2 instanceof Array); + testCastedEqual(test); + testCastedEqual(test2); + }, + + 'Weak', + () => { + for (const configObject of configObjects) { + binding.objectreference.setObject(configObject); + const test = binding.objectreference.getFromValue('weak'); + const test2 = binding.objectreference.getFromGetters('weak', configObject); + + const assertObject = { + [configObject.key]: configObject.val + }; + assert.deepEqual(assertObject, test); + assert.equal(configObject.val, test2); + } + }, () => { + const configObjA = { keyType: enumType.INT, valType: enumType.JS, key: 0, val: 'hello' }; + const configObjB = { keyType: enumType.INT, valType: enumType.JS, key: 1, val: 'world' }; + binding.objectreference.setObject(configObjA); + binding.objectreference.setObject(configObjB); + + const test = binding.objectreference.getFromValue('weak'); + const test2 = binding.objectreference.getFromGetters('weak', configObjA); + const test3 = binding.objectreference.getFromGetters('weak', configObjB); + assert.deepEqual({ 1: 'world' }, test); + assert.equal(undefined, test2); + assert.equal('world', test3); + }, + () => { + binding.objectreference.setObject({ keyType: enumType.JS, valType: enumType.JS, key: 'hello', val: 'world' }); + assert.doesNotThrow( + () => { + let rcount = binding.objectreference.refObjects('weak'); + assert.equal(rcount, 1); + rcount = binding.objectreference.unrefObjects('weak'); + assert.equal(rcount, 0); + }, + Error + ); + assert.throws( + () => { + binding.objectreference.unrefObjects('weak'); + }, + Error + ); + }, + + 'Persistent', + () => { + for (const configObject of configObjects) { + binding.objectreference.setObject(configObject); + const test = binding.objectreference.getFromValue('persistent'); + const test2 = binding.objectreference.getFromGetters('persistent', configObject); + const assertObject = { + [configObject.key]: configObject.val + }; + + assert.deepEqual(assertObject, test); + assert.equal(configObject.val, test2); + } + }, + () => { + binding.objectreference.setObject({ keyType: enumType.CPP_STR, valType: enumType.JS, key: 'hello', val: 'world' }); + const test = binding.objectreference.getFromValue('persistent'); + const test2 = binding.objectreference.getFromValue('persistent', 'hello'); + + assert.deepEqual({ hello: 'world' }, test); + assert.deepEqual({ hello: 'world' }, test2); + assert.deepEqual(test, test2); + }, + () => { + const configObjA = { keyType: enumType.INT, valType: enumType.JS, key: 0, val: 'hello' }; + const configObjB = { keyType: enumType.INT, valType: enumType.JS, key: 1, val: 'world' }; + binding.objectreference.setObject(configObjA); + binding.objectreference.setObject(configObjB); + + const test = binding.objectreference.getFromValue('persistent'); + const test2 = binding.objectreference.getFromGetters('persistent', configObjA); + const test3 = binding.objectreference.getFromGetters('persistent', configObjB); + + assert.deepEqual({ 1: 'world' }, test); + assert.equal(undefined, test2); + assert.equal('world', test3); + }, + () => { + binding.objectreference.setObject({ keyType: enumType.CPP_STR, valType: enumType.JS, key: 'hello', val: 'world' }); + assert.doesNotThrow( + () => { + let rcount = binding.objectreference.unrefObjects('persistent'); + assert.equal(rcount, 0); + rcount = binding.objectreference.refObjects('persistent'); + assert.equal(rcount, 1); + rcount = binding.objectreference.unrefObjects('persistent'); + assert.equal(rcount, 0); + rcount = binding.objectreference.refObjects('persistent'); + assert.equal(rcount, 1); + rcount = binding.objectreference.unrefObjects('persistent'); + assert.equal(rcount, 0); + }, + Error + ); + assert.throws( + () => { + binding.objectreference.unrefObjects('persistent'); + }, + Error + ); + }, + + 'References', + () => { + for (const configObject of configObjects) { + binding.objectreference.setObject(configObject); + const test = binding.objectreference.getFromValue(); + const test2 = binding.objectreference.getFromGetters('reference', configObject); + const assertObject = { + [configObject.key]: configObject.val + }; + assert.deepEqual(assertObject, test); + assert.equal(configObject.val, test2); + } + }, + () => { + const configObjA = { keyType: enumType.INT, valType: enumType.JS, key: 0, val: 'hello' }; + const configObjB = { keyType: enumType.INT, valType: enumType.JS, key: 1, val: 'world' }; + binding.objectreference.setObject(configObjA); + binding.objectreference.setObject(configObjB); + const test = binding.objectreference.getFromValue(); + + const test2 = binding.objectreference.getFromGetters('reference', configObjA); + const test3 = binding.objectreference.getFromGetters('reference', configObjB); + + assert.deepEqual({ 1: 'world' }, test); + assert.equal(undefined, test2); + assert.equal('world', test3); + }, + () => { + binding.objectreference.setObject({ keyType: enumType.CPP_STR, valType: enumType.JS, key: 'hello', val: 'world' }); + assert.doesNotThrow( + () => { + let rcount = binding.objectreference.unrefObjects('references'); + assert.equal(rcount, 1); + rcount = binding.objectreference.refObjects('references'); + assert.equal(rcount, 2); + rcount = binding.objectreference.unrefObjects('references'); + assert.equal(rcount, 1); + rcount = binding.objectreference.unrefObjects('references'); + assert.equal(rcount, 0); + }, + Error + ); + assert.throws( + () => { + binding.objectreference.unrefObjects('references'); + }, + Error + ); + } + ]); +} diff --git a/test/node-addon-api/test/objectwrap.cc b/test/node-addon-api/test/objectwrap.cc new file mode 100644 index 0000000..1ee0c9a --- /dev/null +++ b/test/node-addon-api/test/objectwrap.cc @@ -0,0 +1,295 @@ +#include +#include "test_helper.h" + +Napi::ObjectReference testStaticContextRef; + +Napi::Value StaticGetter(const Napi::CallbackInfo& /*info*/) { + return MaybeUnwrap(testStaticContextRef.Value().Get("value")); +} + +void StaticSetter(const Napi::CallbackInfo& /*info*/, + const Napi::Value& value) { + testStaticContextRef.Value().Set("value", value); +} + +void StaticMethodVoidCb(const Napi::CallbackInfo& info) { + StaticSetter(info, info[0].As()); +} + +Napi::Value TestStaticMethod(const Napi::CallbackInfo& info) { + std::string str = MaybeUnwrap(info[0].ToString()); + return Napi::String::New(info.Env(), str + " static"); +} + +Napi::Value TestStaticMethodInternal(const Napi::CallbackInfo& info) { + std::string str = MaybeUnwrap(info[0].ToString()); + return Napi::String::New(info.Env(), str + " static internal"); +} + +class Test : public Napi::ObjectWrap { + public: + Test(const Napi::CallbackInfo& info) : Napi::ObjectWrap(info) { + if (info.Length() > 0) { + finalizeCb_ = Napi::Persistent(info[0].As()); + } + // Create an own instance property. + info.This().As().DefineProperty( + Napi::PropertyDescriptor::Accessor(info.Env(), + info.This().As(), + "ownProperty", + OwnPropertyGetter, + napi_enumerable, + this)); + + // Create an own instance property with a templated function. + info.This().As().DefineProperty( + Napi::PropertyDescriptor::Accessor( + "ownPropertyT", napi_enumerable, this)); + + bufref_ = Napi::Persistent(Napi::Buffer::New( + Env(), + static_cast(malloc(1)), + 1, + [](Napi::Env, uint8_t* bufaddr) { free(bufaddr); })); + } + + static Napi::Value OwnPropertyGetter(const Napi::CallbackInfo& info) { + return static_cast(info.Data())->Getter(info); + } + + static Napi::Value CanUnWrap(const Napi::CallbackInfo& info) { + Napi::Object wrappedObject = info[0].As(); + std::string expectedString = info[1].As(); + Test* nativeObject = Test::Unwrap(wrappedObject); + std::string strVal = MaybeUnwrap(nativeObject->Getter(info).ToString()); + + return Napi::Boolean::New(info.Env(), strVal == expectedString); + } + + void Setter(const Napi::CallbackInfo& /*info*/, const Napi::Value& value) { + value_ = MaybeUnwrap(value.ToString()); + } + + Napi::Value Getter(const Napi::CallbackInfo& info) { + return Napi::String::New(info.Env(), value_); + } + + Napi::Value TestMethod(const Napi::CallbackInfo& info) { + std::string str = MaybeUnwrap(info[0].ToString()); + return Napi::String::New(info.Env(), str + " instance"); + } + + Napi::Value TestMethodInternal(const Napi::CallbackInfo& info) { + std::string str = MaybeUnwrap(info[0].ToString()); + return Napi::String::New(info.Env(), str + " instance internal"); + } + + Napi::Value ToStringTag(const Napi::CallbackInfo& info) { + return Napi::String::From(info.Env(), "TestTag"); + } + + // creates dummy array, returns `([value])[Symbol.iterator]()` + Napi::Value Iterator(const Napi::CallbackInfo& info) { + Napi::Array array = Napi::Array::New(info.Env()); + array.Set(array.Length(), Napi::String::From(info.Env(), value_)); + return MaybeUnwrap( + MaybeUnwrap(array.Get(MaybeUnwrap( + Napi::Symbol::WellKnown(info.Env(), "iterator")))) + .As() + .Call(array, {})); + } + + void TestVoidMethodT(const Napi::CallbackInfo& info) { + value_ = MaybeUnwrap(info[0].ToString()); + } + + Napi::Value TestMethodT(const Napi::CallbackInfo& info) { + return Napi::String::New(info.Env(), value_); + } + + static Napi::Value TestStaticMethodT(const Napi::CallbackInfo& info) { + return Napi::String::New(info.Env(), s_staticMethodText); + } + + static void TestStaticVoidMethodT(const Napi::CallbackInfo& info) { + s_staticMethodText = MaybeUnwrap(info[0].ToString()); + } + + static void Initialize(Napi::Env env, Napi::Object exports) { + Napi::Symbol kTestStaticValueInternal = + Napi::Symbol::New(env, "kTestStaticValueInternal"); + Napi::Symbol kTestStaticAccessorInternal = + Napi::Symbol::New(env, "kTestStaticAccessorInternal"); + Napi::Symbol kTestStaticAccessorTInternal = + Napi::Symbol::New(env, "kTestStaticAccessorTInternal"); + Napi::Symbol kTestStaticMethodInternal = + Napi::Symbol::New(env, "kTestStaticMethodInternal"); + Napi::Symbol kTestStaticMethodTInternal = + Napi::Symbol::New(env, "kTestStaticMethodTInternal"); + Napi::Symbol kTestStaticVoidMethodTInternal = + Napi::Symbol::New(env, "kTestStaticVoidMethodTInternal"); + Napi::Symbol kTestStaticVoidMethodInternal = + Napi::Symbol::New(env, "kTestStaticVoidMethodInternal"); + Napi::Symbol kTestValueInternal = + Napi::Symbol::New(env, "kTestValueInternal"); + Napi::Symbol kTestAccessorInternal = + Napi::Symbol::New(env, "kTestAccessorInternal"); + Napi::Symbol kTestAccessorTInternal = + Napi::Symbol::New(env, "kTestAccessorTInternal"); + Napi::Symbol kTestMethodInternal = + Napi::Symbol::New(env, "kTestMethodInternal"); + Napi::Symbol kTestMethodTInternal = + Napi::Symbol::New(env, "kTestMethodTInternal"); + Napi::Symbol kTestVoidMethodTInternal = + Napi::Symbol::New(env, "kTestVoidMethodTInternal"); + + exports.Set( + "Test", + DefineClass( + env, + "Test", + { + + // expose symbols for testing + StaticValue("kTestStaticValueInternal", + kTestStaticValueInternal), + StaticValue("kTestStaticAccessorInternal", + kTestStaticAccessorInternal), + StaticValue("kTestStaticAccessorTInternal", + kTestStaticAccessorTInternal), + StaticValue("kTestStaticMethodInternal", + kTestStaticMethodInternal), + StaticValue("kTestStaticMethodTInternal", + kTestStaticMethodTInternal), + StaticValue("kTestStaticVoidMethodInternal", + kTestStaticVoidMethodInternal), + StaticValue("kTestStaticVoidMethodTInternal", + kTestStaticVoidMethodTInternal), + StaticValue("kTestValueInternal", kTestValueInternal), + StaticValue("kTestAccessorInternal", kTestAccessorInternal), + StaticValue("kTestAccessorTInternal", kTestAccessorTInternal), + StaticValue("kTestMethodInternal", kTestMethodInternal), + StaticValue("kTestMethodTInternal", kTestMethodTInternal), + StaticValue("kTestVoidMethodTInternal", + kTestVoidMethodTInternal), + + // test data + StaticValue("testStaticValue", + Napi::String::New(env, "value"), + napi_enumerable), + StaticValue(kTestStaticValueInternal, + Napi::Number::New(env, 5), + napi_default), + + StaticAccessor("testStaticGetter", + &StaticGetter, + nullptr, + napi_enumerable), + StaticAccessor( + "testStaticSetter", nullptr, &StaticSetter, napi_default), + StaticAccessor("testStaticGetSet", + &StaticGetter, + &StaticSetter, + napi_enumerable), + StaticAccessor(kTestStaticAccessorInternal, + &StaticGetter, + &StaticSetter, + napi_enumerable), + StaticAccessor<&StaticGetter>("testStaticGetterT"), + StaticAccessor<&StaticGetter, &StaticSetter>( + "testStaticGetSetT"), + StaticAccessor<&StaticGetter, &StaticSetter>( + kTestStaticAccessorTInternal), + StaticMethod( + "testStaticVoidMethod", &StaticMethodVoidCb, napi_default), + StaticMethod(kTestStaticVoidMethodInternal, + &StaticMethodVoidCb, + napi_default), + StaticMethod( + "testStaticMethod", &TestStaticMethod, napi_enumerable), + StaticMethod(kTestStaticMethodInternal, + &TestStaticMethodInternal, + napi_default), + StaticMethod<&TestStaticVoidMethodT>("testStaticVoidMethodT"), + StaticMethod<&TestStaticMethodT>("testStaticMethodT"), + StaticMethod<&TestStaticVoidMethodT>( + kTestStaticVoidMethodTInternal), + StaticMethod<&TestStaticMethodT>(kTestStaticMethodTInternal), + StaticMethod("canUnWrap", &CanUnWrap, napi_enumerable), + InstanceValue("testValue", + Napi::Boolean::New(env, true), + napi_enumerable), + InstanceValue(kTestValueInternal, + Napi::Boolean::New(env, false), + napi_enumerable), + + InstanceAccessor( + "testGetter", &Test::Getter, nullptr, napi_enumerable), + InstanceAccessor( + "testSetter", nullptr, &Test::Setter, napi_default), + InstanceAccessor("testGetSet", + &Test::Getter, + &Test::Setter, + napi_enumerable), + InstanceAccessor(kTestAccessorInternal, + &Test::Getter, + &Test::Setter, + napi_enumerable), + InstanceAccessor<&Test::Getter>("testGetterT"), + InstanceAccessor<&Test::Getter, &Test::Setter>("testGetSetT"), + InstanceAccessor<&Test::Getter, &Test::Setter>( + kTestAccessorInternal), + + InstanceMethod( + "testMethod", &Test::TestMethod, napi_enumerable), + InstanceMethod(kTestMethodInternal, + &Test::TestMethodInternal, + napi_default), + InstanceMethod<&Test::TestMethodT>("testMethodT"), + InstanceMethod<&Test::TestVoidMethodT>("testVoidMethodT"), + InstanceMethod<&Test::TestMethodT>(kTestMethodTInternal), + InstanceMethod<&Test::TestVoidMethodT>( + kTestVoidMethodTInternal), + + // conventions + InstanceAccessor( + MaybeUnwrap(Napi::Symbol::WellKnown(env, "toStringTag")), + &Test::ToStringTag, + nullptr, + napi_enumerable), + InstanceMethod( + MaybeUnwrap(Napi::Symbol::WellKnown(env, "iterator")), + &Test::Iterator, + napi_default), + + })); + } + + void Finalize(Napi::Env env) { + if (finalizeCb_.IsEmpty()) { + return; + } + + finalizeCb_.Call(env.Global(), {Napi::Boolean::New(env, true)}); + finalizeCb_.Unref(); + } + + private: + std::string value_; + Napi::FunctionReference finalizeCb_; + + static std::string s_staticMethodText; + + Napi::Reference> bufref_; +}; + +std::string Test::s_staticMethodText; + +Napi::Object InitObjectWrap(Napi::Env env) { + testStaticContextRef = Napi::Persistent(Napi::Object::New(env)); + testStaticContextRef.SuppressDestruct(); + + Napi::Object exports = Napi::Object::New(env); + Test::Initialize(env, exports); + return exports; +} diff --git a/test/node-addon-api/test/objectwrap.js b/test/node-addon-api/test/objectwrap.js new file mode 100644 index 0000000..a0d2780 --- /dev/null +++ b/test/node-addon-api/test/objectwrap.js @@ -0,0 +1,309 @@ +/* eslint-disable no-lone-blocks */ +'use strict'; + +const assert = require('assert'); +const testUtil = require('./testUtil'); + +module.exports = require('./common').runTest(test); + +async function test (binding) { + const Test = binding.objectwrap.Test; + + const testValue = (obj, clazz) => { + assert.strictEqual(obj.testValue, true); + assert.strictEqual(obj[clazz.kTestValueInternal], false); + }; + + const testAccessor = (obj, clazz) => { + // read-only, write-only + { + obj.testSetter = 'instance getter'; + assert.strictEqual(obj.testGetter, 'instance getter'); + assert.strictEqual(obj.testGetterT, 'instance getter'); + + obj.testSetter = 'instance getter 2'; + assert.strictEqual(obj.testGetter, 'instance getter 2'); + assert.strictEqual(obj.testGetterT, 'instance getter 2'); + + assert.throws(() => clazz.prototype.testGetter, /Invalid argument/); + assert.throws(() => clazz.prototype.testGetterT, /Invalid argument/); + } + + // read write-only + { + let error; + // eslint-disable-next-line no-unused-vars + try { const read = obj.testSetter; } catch (e) { error = e; } + // no error + assert.strictEqual(error, undefined); + + // read is undefined + assert.strictEqual(obj.testSetter, undefined); + } + + // write read-only + { + let error; + try { obj.testGetter = 'write'; } catch (e) { error = e; } + assert.strictEqual(error.name, 'TypeError'); + + try { obj.testGetterT = 'write'; } catch (e) { error = e; } + assert.strictEqual(error.name, 'TypeError'); + } + + // rw + { + obj.testGetSet = 'instance getset'; + assert.strictEqual(obj.testGetSet, 'instance getset'); + + obj.testGetSet = 'instance getset 2'; + assert.strictEqual(obj.testGetSet, 'instance getset 2'); + + obj.testGetSetT = 'instance getset 3'; + assert.strictEqual(obj.testGetSetT, 'instance getset 3'); + + obj.testGetSetT = 'instance getset 4'; + assert.strictEqual(obj.testGetSetT, 'instance getset 4'); + + assert.throws(() => { clazz.prototype.testGetSet = 'instance getset'; }, /Invalid argument/); + assert.throws(() => { clazz.prototype.testGetSetT = 'instance getset'; }, /Invalid argument/); + } + + // rw symbol + { + obj[clazz.kTestAccessorInternal] = 'instance internal getset'; + assert.strictEqual(obj[clazz.kTestAccessorInternal], 'instance internal getset'); + + obj[clazz.kTestAccessorInternal] = 'instance internal getset 2'; + assert.strictEqual(obj[clazz.kTestAccessorInternal], 'instance internal getset 2'); + + obj[clazz.kTestAccessorTInternal] = 'instance internal getset 3'; + assert.strictEqual(obj[clazz.kTestAccessorTInternal], 'instance internal getset 3'); + + obj[clazz.kTestAccessorTInternal] = 'instance internal getset 4'; + assert.strictEqual(obj[clazz.kTestAccessorTInternal], 'instance internal getset 4'); + } + + // own property + { + obj.testSetter = 'own property value'; + // Make sure the properties are enumerable. + assert(Object.getOwnPropertyNames(obj).indexOf('ownProperty') >= 0); + assert(Object.getOwnPropertyNames(obj).indexOf('ownPropertyT') >= 0); + + // Make sure the properties return the right value. + assert.strictEqual(obj.ownProperty, 'own property value'); + assert.strictEqual(obj.ownPropertyT, 'own property value'); + } + }; + + const testMethod = (obj, clazz) => { + assert.strictEqual(obj.testMethod('method'), 'method instance'); + assert.strictEqual(obj[clazz.kTestMethodInternal]('method'), 'method instance internal'); + obj.testVoidMethodT('method<>(const char*)'); + assert.strictEqual(obj.testMethodT(), 'method<>(const char*)'); + obj[clazz.kTestVoidMethodTInternal]('method<>(Symbol)'); + assert.strictEqual(obj[clazz.kTestMethodTInternal](), 'method<>(Symbol)'); + assert.throws(() => clazz.prototype.testMethod('method')); + assert.throws(() => clazz.prototype.testMethodT()); + assert.throws(() => clazz.prototype.testVoidMethodT('method<>(const char*)')); + }; + + const testEnumerables = (obj, clazz) => { + // Object.keys: only object without prototype + assert(Object.keys(obj).length === 2); + assert(Object.keys(obj).includes('ownProperty')); + assert(Object.keys(obj).indexOf('ownPropertyT') >= 0); + + // for..in: object and prototype + { + const keys = []; + for (const key in obj) { + keys.push(key); + } + + assert(keys.length === 6); + // on prototype + assert(keys.includes('testGetSet')); + assert(keys.includes('testGetter')); + assert(keys.includes('testValue')); + assert(keys.includes('testMethod')); + // on object only + assert(keys.includes('ownProperty')); + assert(keys.includes('ownPropertyT')); + } + }; + + const testConventions = (obj, clazz) => { + // test @@toStringTag + { + assert.strictEqual(obj[Symbol.toStringTag], 'TestTag'); + assert.strictEqual('' + obj, '[object TestTag]'); + } + + // test @@iterator + { + obj.testSetter = 'iterator'; + const values = []; + + for (const item of obj) { + values.push(item); + } + + assert.deepEqual(values, ['iterator']); + } + }; + + const testStaticValue = (clazz) => { + assert.strictEqual(clazz.testStaticValue, 'value'); + assert.strictEqual(clazz[clazz.kTestStaticValueInternal], 5); + }; + + const testStaticAccessor = (clazz) => { + // read-only, write-only + { + const tempObj = {}; + clazz.testStaticSetter = tempObj; + assert.strictEqual(clazz.testStaticGetter, tempObj); + assert.strictEqual(clazz.testStaticGetterT, tempObj); + + const tempArray = []; + clazz.testStaticSetter = tempArray; + assert.strictEqual(clazz.testStaticGetter, tempArray); + assert.strictEqual(clazz.testStaticGetterT, tempArray); + } + + // read write-only + { + let error; + // eslint-disable-next-line no-unused-vars + try { const read = clazz.testStaticSetter; } catch (e) { error = e; } + // no error + assert.strictEqual(error, undefined); + + // read is undefined + assert.strictEqual(clazz.testStaticSetter, undefined); + } + + // write-read-only + { + let error; + try { clazz.testStaticGetter = 'write'; } catch (e) { error = e; } + assert.strictEqual(error.name, 'TypeError'); + try { clazz.testStaticGetterT = 'write'; } catch (e) { error = e; } + assert.strictEqual(error.name, 'TypeError'); + } + + // rw + { + clazz.testStaticGetSet = 9; + assert.strictEqual(clazz.testStaticGetSet, 9); + + clazz.testStaticGetSet = 4; + assert.strictEqual(clazz.testStaticGetSet, 4); + + clazz.testStaticGetSetT = -9; + assert.strictEqual(clazz.testStaticGetSetT, -9); + + clazz.testStaticGetSetT = -4; + assert.strictEqual(clazz.testStaticGetSetT, -4); + } + + // rw symbol + { + clazz[clazz.kTestStaticAccessorInternal] = 'static internal getset'; + assert.strictEqual(clazz[clazz.kTestStaticAccessorInternal], 'static internal getset'); + clazz[clazz.kTestStaticAccessorTInternal] = 'static internal getset <>'; + assert.strictEqual(clazz[clazz.kTestStaticAccessorTInternal], 'static internal getset <>'); + } + }; + + const testStaticMethod = (clazz) => { + clazz.testStaticVoidMethod(52); + assert.strictEqual(clazz.testStaticGetter, 52); + clazz[clazz.kTestStaticVoidMethodInternal](94); + assert.strictEqual(clazz.testStaticGetter, 94); + assert.strictEqual(clazz.testStaticMethod('method'), 'method static'); + assert.strictEqual(clazz[clazz.kTestStaticMethodInternal]('method'), 'method static internal'); + clazz.testStaticVoidMethodT('static method<>(const char*)'); + assert.strictEqual(clazz.testStaticMethodT(), 'static method<>(const char*)'); + clazz[clazz.kTestStaticVoidMethodTInternal]('static method<>(Symbol)'); + assert.strictEqual(clazz[clazz.kTestStaticMethodTInternal](), 'static method<>(Symbol)'); + }; + + const testStaticEnumerables = (clazz) => { + // Object.keys + assert.deepEqual(Object.keys(clazz), [ + 'testStaticValue', + 'testStaticGetter', + 'testStaticGetSet', + 'testStaticMethod', + 'canUnWrap' + ]); + + // for..in + { + const keys = []; + for (const key in clazz) { + keys.push(key); + } + + assert.deepEqual(keys, [ + 'testStaticValue', + 'testStaticGetter', + 'testStaticGetSet', + 'testStaticMethod', + 'canUnWrap' + ]); + } + }; + + async function testFinalize (clazz) { + let finalizeCalled = false; + await testUtil.runGCTests([ + 'test finalize', + () => { + const finalizeCb = function (called) { + finalizeCalled = called; + }; + + // Scope Test instance so that it can be gc'd. + // eslint-disable-next-line no-new + (() => { new Test(finalizeCb); })(); + }, + () => assert.strictEqual(finalizeCalled, true) + ]); + } + + const testUnwrap = (obj, clazz) => { + obj.testSetter = 'unwrapTest'; + assert(clazz.canUnWrap(obj, 'unwrapTest')); + }; + + const testObj = (obj, clazz) => { + testValue(obj, clazz); + testAccessor(obj, clazz); + testMethod(obj, clazz); + + testEnumerables(obj, clazz); + + testConventions(obj, clazz); + testUnwrap(obj, clazz); + }; + + async function testClass (clazz) { + testStaticValue(clazz); + testStaticAccessor(clazz); + testStaticMethod(clazz); + + testStaticEnumerables(clazz); + await testFinalize(clazz); + } + + // `Test` is needed for accessing exposed symbols + testObj(new Test(), Test); + await testClass(Test); + + // Make sure the C++ object can be garbage collected without issues. + await testUtil.runGCTests(['one last gc', () => {}, () => {}]); +} diff --git a/test/node-addon-api/test/objectwrap_constructor_exception.cc b/test/node-addon-api/test/objectwrap_constructor_exception.cc new file mode 100644 index 0000000..2661355 --- /dev/null +++ b/test/node-addon-api/test/objectwrap_constructor_exception.cc @@ -0,0 +1,26 @@ +#include + +class ConstructorExceptionTest + : public Napi::ObjectWrap { + public: + ConstructorExceptionTest(const Napi::CallbackInfo& info) + : Napi::ObjectWrap(info) { + Napi::Error error = Napi::Error::New(info.Env(), "an exception"); +#ifdef NAPI_DISABLE_CPP_EXCEPTIONS + error.ThrowAsJavaScriptException(); +#else + throw error; +#endif // NAPI_DISABLE_CPP_EXCEPTIONS + } + + static void Initialize(Napi::Env env, Napi::Object exports) { + const char* name = "ConstructorExceptionTest"; + exports.Set(name, DefineClass(env, name, {})); + } +}; + +Napi::Object InitObjectWrapConstructorException(Napi::Env env) { + Napi::Object exports = Napi::Object::New(env); + ConstructorExceptionTest::Initialize(env, exports); + return exports; +} diff --git a/test/node-addon-api/test/objectwrap_constructor_exception.js b/test/node-addon-api/test/objectwrap_constructor_exception.js new file mode 100644 index 0000000..2fbed81 --- /dev/null +++ b/test/node-addon-api/test/objectwrap_constructor_exception.js @@ -0,0 +1,18 @@ +'use strict'; + +const assert = require('assert'); +const testUtil = require('./testUtil'); + +function test (binding) { + return testUtil.runGCTests([ + 'objectwrap constructor exception', + () => { + const { ConstructorExceptionTest } = binding.objectwrapConstructorException; + assert.throws(() => (new ConstructorExceptionTest()), /an exception/); + }, + // Do on gc before returning. + () => {} + ]); +} + +module.exports = require('./common').runTest(test); diff --git a/test/node-addon-api/test/objectwrap_function.cc b/test/node-addon-api/test/objectwrap_function.cc new file mode 100644 index 0000000..0ce074c --- /dev/null +++ b/test/node-addon-api/test/objectwrap_function.cc @@ -0,0 +1,43 @@ +#include +#include +#include "test_helper.h" + +class FunctionTest : public Napi::ObjectWrap { + public: + FunctionTest(const Napi::CallbackInfo& info) + : Napi::ObjectWrap(info) {} + + static Napi::Value OnCalledAsFunction(const Napi::CallbackInfo& info) { + // If called with a "true" argument, throw an exeption to test the handling. + if (!info[0].IsUndefined() && MaybeUnwrap(info[0].ToBoolean())) { + NAPI_THROW(Napi::Error::New(info.Env(), "an exception"), Napi::Value()); + } + // Otherwise, act as a factory. + std::vector args; + for (size_t i = 0; i < info.Length(); i++) args.push_back(info[i]); + return MaybeUnwrap(GetConstructor(info.Env()).New(args)); + } + + static void Initialize(Napi::Env env, Napi::Object exports) { + const char* name = "FunctionTest"; + Napi::Function func = DefineClass(env, name, {}); + Napi::FunctionReference* ctor = new Napi::FunctionReference(); + *ctor = Napi::Persistent(func); + env.SetInstanceData(ctor); + exports.Set(name, func); + } + + static Napi::Function GetConstructor(Napi::Env env) { + return env.GetInstanceData()->Value(); + } +}; + +Napi::Value ObjectWrapFunctionFactory(const Napi::CallbackInfo& info) { + Napi::Object exports = Napi::Object::New(info.Env()); + FunctionTest::Initialize(info.Env(), exports); + return exports; +} + +Napi::Object InitObjectWrapFunction(Napi::Env env) { + return Napi::Function::New(env, "FunctionFactory"); +} diff --git a/test/node-addon-api/test/objectwrap_function.js b/test/node-addon-api/test/objectwrap_function.js new file mode 100644 index 0000000..6718339 --- /dev/null +++ b/test/node-addon-api/test/objectwrap_function.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = require('./common').runTestInChildProcess({ + suite: 'objectwrap_function', + testName: 'runTest' +}); diff --git a/test/node-addon-api/test/objectwrap_multiple_inheritance.cc b/test/node-addon-api/test/objectwrap_multiple_inheritance.cc new file mode 100644 index 0000000..30daaba --- /dev/null +++ b/test/node-addon-api/test/objectwrap_multiple_inheritance.cc @@ -0,0 +1,30 @@ +#include + +class TestMIBase { + public: + TestMIBase() : test(0) {} + virtual void dummy() {} + uint32_t test; +}; + +class TestMI : public TestMIBase, public Napi::ObjectWrap { + public: + TestMI(const Napi::CallbackInfo& info) : Napi::ObjectWrap(info) {} + + Napi::Value GetTest(const Napi::CallbackInfo& info) { + return Napi::Number::New(info.Env(), test); + } + + static void Initialize(Napi::Env env, Napi::Object exports) { + exports.Set( + "TestMI", + DefineClass( + env, "TestMI", {InstanceAccessor<&TestMI::GetTest>("test")})); + } +}; + +Napi::Object InitObjectWrapMultipleInheritance(Napi::Env env) { + Napi::Object exports = Napi::Object::New(env); + TestMI::Initialize(env, exports); + return exports; +} diff --git a/test/node-addon-api/test/objectwrap_multiple_inheritance.js b/test/node-addon-api/test/objectwrap_multiple_inheritance.js new file mode 100644 index 0000000..5264904 --- /dev/null +++ b/test/node-addon-api/test/objectwrap_multiple_inheritance.js @@ -0,0 +1,13 @@ +'use strict'; + +const assert = require('assert'); + +const test = bindingName => { + const binding = require(bindingName); + const TestMI = binding.objectwrap_multiple_inheritance.TestMI; + const testmi = new TestMI(); + + assert.strictEqual(testmi.test, 0); +}; + +module.exports = require('./common').runTestWithBindingPath(test); diff --git a/test/node-addon-api/test/objectwrap_removewrap.cc b/test/node-addon-api/test/objectwrap_removewrap.cc new file mode 100644 index 0000000..a714186 --- /dev/null +++ b/test/node-addon-api/test/objectwrap_removewrap.cc @@ -0,0 +1,45 @@ +#include +#include + +namespace { + +static int dtor_called = 0; + +class DtorCounter { + public: + ~DtorCounter() { + assert(dtor_called == 0); + dtor_called++; + } +}; + +Napi::Value GetDtorCalled(const Napi::CallbackInfo& info) { + return Napi::Number::New(info.Env(), dtor_called); +} + +class Test : public Napi::ObjectWrap { + public: + Test(const Napi::CallbackInfo& info) : Napi::ObjectWrap(info) { +#ifdef NAPI_CPP_EXCEPTIONS + throw Napi::Error::New(Env(), "Some error"); +#else + Napi::Error::New(Env(), "Some error").ThrowAsJavaScriptException(); +#endif + } + + static void Initialize(Napi::Env env, Napi::Object exports) { + exports.Set("Test", DefineClass(env, "Test", {})); + exports.Set("getDtorCalled", Napi::Function::New(env, GetDtorCalled)); + } + + private: + DtorCounter dtor_counter_; +}; + +} // anonymous namespace + +Napi::Object InitObjectWrapRemoveWrap(Napi::Env env) { + Napi::Object exports = Napi::Object::New(env); + Test::Initialize(env, exports); + return exports; +} diff --git a/test/node-addon-api/test/objectwrap_removewrap.js b/test/node-addon-api/test/objectwrap_removewrap.js new file mode 100644 index 0000000..012ebc4 --- /dev/null +++ b/test/node-addon-api/test/objectwrap_removewrap.js @@ -0,0 +1,32 @@ +'use strict'; + +if (process.argv[2] === 'child') { + // Create a single wrapped instance then exit. + // eslint-disable-next-line no-new + new (require(process.argv[3]).objectwrap.Test)(); +} else { + const assert = require('assert'); + const testUtil = require('./testUtil'); + + module.exports = require('./common').runTestWithBindingPath(test); + + function test (bindingName) { + return testUtil.runGCTests([ + 'objectwrap removewrap test', + () => { + const binding = require(bindingName); + const Test = binding.objectwrap_removewrap.Test; + const getDtorCalled = binding.objectwrap_removewrap.getDtorCalled; + + assert.strictEqual(getDtorCalled(), 0); + assert.throws(() => { + // eslint-disable-next-line no-new + new Test(); + }); + assert.strictEqual(getDtorCalled(), 1); + }, + // Test that gc does not crash. + () => {} + ]); + } +} diff --git a/test/node-addon-api/test/objectwrap_worker_thread.js b/test/node-addon-api/test/objectwrap_worker_thread.js new file mode 100644 index 0000000..59dfb9c --- /dev/null +++ b/test/node-addon-api/test/objectwrap_worker_thread.js @@ -0,0 +1,20 @@ +'use strict'; +const path = require('path'); +const { Worker, isMainThread } = require('worker_threads'); +const { runTestWithBuildType, whichBuildType } = require('./common'); + +module.exports = runTestWithBuildType(test); + +async function test () { + if (isMainThread) { + const buildType = await whichBuildType(); + const worker = new Worker(__filename, { workerData: buildType }); + return new Promise((resolve, reject) => { + worker.on('exit', () => { + resolve(); + }); + }, () => {}); + } else { + await require(path.join(__dirname, 'objectwrap.js')); + } +} diff --git a/test/node-addon-api/test/promise.cc b/test/node-addon-api/test/promise.cc new file mode 100644 index 0000000..06ba22b --- /dev/null +++ b/test/node-addon-api/test/promise.cc @@ -0,0 +1,111 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +Value IsPromise(const CallbackInfo& info) { + return Boolean::New(info.Env(), info[0].IsPromise()); +} + +Value ResolvePromise(const CallbackInfo& info) { + auto deferred = Promise::Deferred::New(info.Env()); + deferred.Resolve(info[0]); + return deferred.Promise(); +} + +Value RejectPromise(const CallbackInfo& info) { + auto deferred = Promise::Deferred::New(info.Env()); + deferred.Reject(info[0]); + return deferred.Promise(); +} + +Value PromiseReturnsCorrectEnv(const CallbackInfo& info) { + auto deferred = Promise::Deferred::New(info.Env()); + return Boolean::New(info.Env(), deferred.Env() == info.Env()); +} + +Value ThenMethodOnFulfilled(const CallbackInfo& info) { + auto deferred = Promise::Deferred::New(info.Env()); + Function onFulfilled = info[0].As(); + + Promise resultPromise = MaybeUnwrap(deferred.Promise().Then(onFulfilled)); + + bool isPromise = resultPromise.IsPromise(); + deferred.Resolve(Number::New(info.Env(), 42)); + + Object result = Object::New(info.Env()); + result["isPromise"] = Boolean::New(info.Env(), isPromise); + result["promise"] = resultPromise; + + return result; +} + +Value ThenMethodOnFulfilledOnRejectedResolve(const CallbackInfo& info) { + auto deferred = Promise::Deferred::New(info.Env()); + Function onFulfilled = info[0].As(); + Function onRejected = info[1].As(); + + Promise resultPromise = + MaybeUnwrap(deferred.Promise().Then(onFulfilled, onRejected)); + + bool isPromise = resultPromise.IsPromise(); + deferred.Resolve(Number::New(info.Env(), 42)); + + Object result = Object::New(info.Env()); + result["isPromise"] = Boolean::New(info.Env(), isPromise); + result["promise"] = resultPromise; + + return result; +} + +Value ThenMethodOnFulfilledOnRejectedReject(const CallbackInfo& info) { + auto deferred = Promise::Deferred::New(info.Env()); + Function onFulfilled = info[0].As(); + Function onRejected = info[1].As(); + + Promise resultPromise = + MaybeUnwrap(deferred.Promise().Then(onFulfilled, onRejected)); + + bool isPromise = resultPromise.IsPromise(); + deferred.Reject(String::New(info.Env(), "Rejected")); + + Object result = Object::New(info.Env()); + result["isPromise"] = Boolean::New(info.Env(), isPromise); + result["promise"] = resultPromise; + + return result; +} + +Value CatchMethod(const CallbackInfo& info) { + auto deferred = Promise::Deferred::New(info.Env()); + Function onRejected = info[0].As(); + + Promise resultPromise = MaybeUnwrap(deferred.Promise().Catch(onRejected)); + + bool isPromise = resultPromise.IsPromise(); + deferred.Reject(String::New(info.Env(), "Rejected")); + + Object result = Object::New(info.Env()); + result["isPromise"] = Boolean::New(info.Env(), isPromise); + result["promise"] = resultPromise; + + return result; +} + +Object InitPromise(Env env) { + Object exports = Object::New(env); + + exports["isPromise"] = Function::New(env, IsPromise); + exports["resolvePromise"] = Function::New(env, ResolvePromise); + exports["rejectPromise"] = Function::New(env, RejectPromise); + exports["promiseReturnsCorrectEnv"] = + Function::New(env, PromiseReturnsCorrectEnv); + exports["thenMethodOnFulfilled"] = Function::New(env, ThenMethodOnFulfilled); + exports["thenMethodOnFulfilledOnRejectedResolve"] = + Function::New(env, ThenMethodOnFulfilledOnRejectedResolve); + exports["thenMethodOnFulfilledOnRejectedReject"] = + Function::New(env, ThenMethodOnFulfilledOnRejectedReject); + exports["catchMethod"] = Function::New(env, CatchMethod); + + return exports; +} diff --git a/test/node-addon-api/test/promise.js b/test/node-addon-api/test/promise.js new file mode 100644 index 0000000..e61a783 --- /dev/null +++ b/test/node-addon-api/test/promise.js @@ -0,0 +1,43 @@ +'use strict'; + +const assert = require('assert'); +const common = require('./common'); + +module.exports = common.runTest(test); + +async function test (binding) { + assert.strictEqual(binding.promise.isPromise({}), false); + + const resolving = binding.promise.resolvePromise('resolved'); + await assert.strictEqual(binding.promise.isPromise(resolving), true); + resolving.then(common.mustCall()).catch(common.mustNotCall()); + + const rejecting = binding.promise.rejectPromise('error'); + await assert.strictEqual(binding.promise.isPromise(rejecting), true); + rejecting.then(common.mustNotCall()).catch(common.mustCall()); + + assert(binding.promise.promiseReturnsCorrectEnv()); + + const onFulfilled = (value) => value * 2; + const onRejected = (reason) => reason + '!'; + + const thenOnFulfilled = binding.promise.thenMethodOnFulfilled(onFulfilled); + assert.strictEqual(thenOnFulfilled.isPromise, true); + const onFulfilledValue = await thenOnFulfilled.promise; + assert.strictEqual(onFulfilledValue, 84); + + const thenResolve = binding.promise.thenMethodOnFulfilledOnRejectedResolve(onFulfilled, onRejected); + assert.strictEqual(thenResolve.isPromise, true); + const thenResolveValue = await thenResolve.promise; + assert.strictEqual(thenResolveValue, 84); + + const thenRejected = binding.promise.thenMethodOnFulfilledOnRejectedReject(onFulfilled, onRejected); + assert.strictEqual(thenRejected.isPromise, true); + const rejectedValue = await thenRejected.promise; + assert.strictEqual(rejectedValue, 'Rejected!'); + + const catchMethod = binding.promise.catchMethod(onRejected); + assert.strictEqual(catchMethod.isPromise, true); + const catchValue = await catchMethod.promise; + assert.strictEqual(catchValue, 'Rejected!'); +} diff --git a/test/node-addon-api/test/reference.cc b/test/node-addon-api/test/reference.cc new file mode 100644 index 0000000..b83c434 --- /dev/null +++ b/test/node-addon-api/test/reference.cc @@ -0,0 +1,78 @@ +#include "assert.h" +#include "napi.h" +#include "test_helper.h" +using namespace Napi; + +static Reference> weak; + +static void RefMoveAssignTests(const Napi::CallbackInfo& info) { + Napi::Object obj = Napi::Object::New(info.Env()); + obj.Set("tPro", "tTEST"); + Napi::Reference ref = Napi::Reference::New(obj); + ref.SuppressDestruct(); + + napi_ref obj_ref = static_cast(ref); + Napi::Reference existingRef = + Napi::Reference(info.Env(), obj_ref); + assert(ref == existingRef); + assert(!(ref != existingRef)); + + std::string val = + MaybeUnwrap(existingRef.Value().Get("tPro")).As(); + assert(val == "tTEST"); + // ------------------------------------------------------------ // + Napi::Reference copyMoveRef = std::move(existingRef); + assert(copyMoveRef == ref); + + Napi::Reference copyAssignRef; + copyAssignRef = std::move(copyMoveRef); + assert(copyAssignRef == ref); +} + +static void ReferenceRefTests(const Napi::CallbackInfo& info) { + Napi::Object obj = Napi::Object::New(info.Env()); + Napi::Reference ref = Napi::Reference::New(obj); + + assert(ref.Ref() == 1); + assert(ref.Unref() == 0); +} + +static void ReferenceResetTests(const Napi::CallbackInfo& info) { + Napi::Object obj = Napi::Object::New(info.Env()); + Napi::Reference ref = Napi::Reference::New(obj); + assert(!ref.IsEmpty()); + + ref.Reset(); + assert(ref.IsEmpty()); + + Napi::Object newObject = Napi::Object::New(info.Env()); + newObject.Set("n-api", "node"); + + ref.Reset(newObject, 1); + assert(!ref.IsEmpty()); + + std::string val = MaybeUnwrap(ref.Value().Get("n-api")).As(); + assert(val == "node"); +} + +void CreateWeakArray(const CallbackInfo& info) { + weak = Weak(Buffer::New(info.Env(), 1)); + weak.SuppressDestruct(); +} + +napi_value AccessWeakArrayEmpty(const CallbackInfo& info) { + Buffer value = weak.Value(); + return Napi::Boolean::New(info.Env(), value.IsEmpty()); +} + +Object InitReference(Env env) { + Object exports = Object::New(env); + + exports["createWeakArray"] = Function::New(env, CreateWeakArray); + exports["accessWeakArrayEmpty"] = Function::New(env, AccessWeakArrayEmpty); + + exports["refMoveAssignTest"] = Function::New(env, RefMoveAssignTests); + exports["referenceRefTest"] = Function::New(env, ReferenceRefTests); + exports["refResetTest"] = Function::New(env, ReferenceResetTests); + return exports; +} diff --git a/test/node-addon-api/test/reference.js b/test/node-addon-api/test/reference.js new file mode 100644 index 0000000..2b4c403 --- /dev/null +++ b/test/node-addon-api/test/reference.js @@ -0,0 +1,20 @@ +'use strict'; + +const assert = require('assert'); +const testUtil = require('./testUtil'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + return testUtil.runGCTests([ + 'test reference', + () => binding.reference.createWeakArray(), + () => assert.strictEqual(true, binding.reference.accessWeakArrayEmpty()), + 'test reference move op', + () => binding.reference.refMoveAssignTest(), + 'test reference ref', + () => binding.reference.referenceRefTest(), + 'test reference reset', + () => binding.reference.refResetTest() + ]); +} diff --git a/test/node-addon-api/test/run_script.cc b/test/node-addon-api/test/run_script.cc new file mode 100644 index 0000000..e957df9 --- /dev/null +++ b/test/node-addon-api/test/run_script.cc @@ -0,0 +1,56 @@ +#include "napi.h" +#include "test_helper.h" + +using namespace Napi; + +namespace { + +Value RunPlainString(const CallbackInfo& info) { + Env env = info.Env(); + return MaybeUnwrap(env.RunScript("1 + 2 + 3")); +} + +Value RunStdString(const CallbackInfo& info) { + Env env = info.Env(); + std::string str = "1 + 2 + 3"; + return MaybeUnwrap(env.RunScript(str)); +} + +Value RunJsString(const CallbackInfo& info) { + Env env = info.Env(); + return MaybeUnwrapOr(env.RunScript(info[0].UnsafeAs()), Value()); +} + +Value RunWithContext(const CallbackInfo& info) { + Env env = info.Env(); + + Array keys = MaybeUnwrap(info[1].As().GetPropertyNames()); + std::string code = "("; + for (unsigned int i = 0; i < keys.Length(); i++) { + if (i != 0) code += ","; + code += MaybeUnwrap(keys.Get(i)).As().Utf8Value(); + } + code += ") => " + info[0].As().Utf8Value(); + + Value ret = MaybeUnwrap(env.RunScript(code)); + Function fn = ret.As(); + std::vector args; + for (unsigned int i = 0; i < keys.Length(); i++) { + Value key = MaybeUnwrap(keys.Get(i)); + args.push_back(MaybeUnwrap(info[1].As().Get(key))); + } + return MaybeUnwrap(fn.Call(args)); +} + +} // end anonymous namespace + +Object InitRunScript(Env env) { + Object exports = Object::New(env); + + exports["plainString"] = Function::New(env, RunPlainString); + exports["stdString"] = Function::New(env, RunStdString); + exports["jsString"] = Function::New(env, RunJsString); + exports["withContext"] = Function::New(env, RunWithContext); + + return exports; +} diff --git a/test/node-addon-api/test/run_script.js b/test/node-addon-api/test/run_script.js new file mode 100644 index 0000000..81b5879 --- /dev/null +++ b/test/node-addon-api/test/run_script.js @@ -0,0 +1,45 @@ +'use strict'; + +const assert = require('assert'); +const testUtil = require('./testUtil'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + return testUtil.runGCTests([ + 'Plain C string', + () => { + const sum = binding.run_script.plainString(); + assert.strictEqual(sum, 1 + 2 + 3); + }, + + 'std::string', + () => { + const sum = binding.run_script.stdString(); + assert.strictEqual(sum, 1 + 2 + 3); + }, + + 'JavaScript string', + () => { + const sum = binding.run_script.jsString('1 + 2 + 3'); + assert.strictEqual(sum, 1 + 2 + 3); + }, + + 'JavaScript, but not a string', + () => { + assert.throws(() => { + binding.run_script.jsString(true); + }, { + name: 'TypeError', + message: 'A string was expected' + }); + }, + + 'With context', + () => { + const a = 1; const b = 2; const c = 3; + const sum = binding.run_script.withContext('a + b + c', { a, b, c }); + assert.strictEqual(sum, a + b + c); + } + ]); +} diff --git a/test/node-addon-api/test/shared_array_buffer.cc b/test/node-addon-api/test/shared_array_buffer.cc new file mode 100644 index 0000000..57f6649 --- /dev/null +++ b/test/node-addon-api/test/shared_array_buffer.cc @@ -0,0 +1,104 @@ +#include "napi.h" + +using namespace Napi; + +namespace { + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +Value TestIsSharedArrayBuffer(const CallbackInfo& info) { + if (info.Length() < 1) { + Error::New(info.Env(), "Wrong number of arguments") + .ThrowAsJavaScriptException(); + return Value(); + } + + return Boolean::New(info.Env(), info[0].IsSharedArrayBuffer()); +} + +Value TestCreateSharedArrayBuffer(const CallbackInfo& info) { + if (info.Length() < 1) { + Error::New(info.Env(), "Wrong number of arguments") + .ThrowAsJavaScriptException(); + return Value(); + } else if (!info[0].IsNumber()) { + Error::New(info.Env(), + "Wrong type of arguments. Expects a number as first argument.") + .ThrowAsJavaScriptException(); + return Value(); + } + + auto byte_length = info[0].As().Uint32Value(); + if (byte_length == 0) { + Error::New(info.Env(), + "Invalid byte length. Expects a non-negative integer.") + .ThrowAsJavaScriptException(); + return Value(); + } + + return SharedArrayBuffer::New(info.Env(), byte_length); +} + +Value TestGetSharedArrayBufferInfo(const CallbackInfo& info) { + if (info.Length() < 1) { + Error::New(info.Env(), "Wrong number of arguments") + .ThrowAsJavaScriptException(); + return Value(); + } else if (!info[0].IsSharedArrayBuffer()) { + Error::New(info.Env(), + "Wrong type of arguments. Expects a SharedArrayBuffer as first " + "argument.") + .ThrowAsJavaScriptException(); + return Value(); + } + + auto byte_length = info[0].As().ByteLength(); + + return Number::New(info.Env(), byte_length); +} + +Value TestSharedArrayBufferData(const CallbackInfo& info) { + if (info.Length() < 1) { + Error::New(info.Env(), "Wrong number of arguments") + .ThrowAsJavaScriptException(); + return Value(); + } else if (!info[0].IsSharedArrayBuffer()) { + Error::New(info.Env(), + "Wrong type of arguments. Expects a SharedArrayBuffer as first " + "argument.") + .ThrowAsJavaScriptException(); + return Value(); + } + + auto byte_length = info[0].As().ByteLength(); + void* data = info[0].As().Data(); + + if (byte_length > 0 && data != nullptr) { + uint8_t* bytes = static_cast(data); + for (size_t i = 0; i < byte_length; i++) { + bytes[i] = i % 256; + } + + return Boolean::New(info.Env(), true); + } + + return Boolean::New(info.Env(), false); +} +#endif +} // end anonymous namespace + +Object InitSharedArrayBuffer(Env env) { + Object exports = Object::New(env); + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + exports["testIsSharedArrayBuffer"] = + Function::New(env, TestIsSharedArrayBuffer); + exports["testCreateSharedArrayBuffer"] = + Function::New(env, TestCreateSharedArrayBuffer); + exports["testGetSharedArrayBufferInfo"] = + Function::New(env, TestGetSharedArrayBufferInfo); + exports["testSharedArrayBufferData"] = + Function::New(env, TestSharedArrayBufferData); +#endif + + return exports; +} diff --git a/test/node-addon-api/test/shared_array_buffer.js b/test/node-addon-api/test/shared_array_buffer.js new file mode 100644 index 0000000..018021a --- /dev/null +++ b/test/node-addon-api/test/shared_array_buffer.js @@ -0,0 +1,55 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +let skippedMessageShown = false; + +function test ({ hasSharedArrayBuffer, sharedarraybuffer }) { + if (!hasSharedArrayBuffer) { + if (!skippedMessageShown) { + console.log(' >Skipped (no SharedArrayBuffer support)'); + skippedMessageShown = true; + } + return; + } + + { + const sab = new SharedArrayBuffer(16); + const ab = new ArrayBuffer(16); + const obj = {}; + const arr = []; + + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(sab), true); + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(ab), false); + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(obj), false); + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(arr), false); + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(null), false); + assert.strictEqual(sharedarraybuffer.testIsSharedArrayBuffer(undefined), false); + } + + { + const sab = sharedarraybuffer.testCreateSharedArrayBuffer(16); + assert(sab instanceof SharedArrayBuffer); + assert.strictEqual(sab.byteLength, 16); + } + + { + const sab = new SharedArrayBuffer(32); + const byteLength = sharedarraybuffer.testGetSharedArrayBufferInfo(sab); + assert.strictEqual(byteLength, 32); + } + + { + const sab = new SharedArrayBuffer(8); + const result = sharedarraybuffer.testSharedArrayBufferData(sab); + assert.strictEqual(result, true); + + // Check if data was written correctly + const view = new Uint8Array(sab); + for (let i = 0; i < 8; i++) { + assert.strictEqual(view[i], i % 256); + } + } +} diff --git a/test/node-addon-api/test/symbol.cc b/test/node-addon-api/test/symbol.cc new file mode 100644 index 0000000..e7c8b74 --- /dev/null +++ b/test/node-addon-api/test/symbol.cc @@ -0,0 +1,209 @@ +#include + +#include +#include + +#include "test_helper.h" +using namespace Napi; + +namespace { + +struct StringLike { + operator std::string() const { return "unexpected-string-key"; } + operator std::string_view() const { return value; } + + std::string value; +}; + +struct RvalueStringLike { + operator std::string() && { return "unexpected-rvalue-string-key"; } + operator std::string_view() && { return value; } + + std::string value; +}; + +struct StringOnlyLike { + operator std::string() const { return value; } + + std::string value; +}; + +struct BothBases : std::string, std::string_view {}; + +struct ViewAndNapiString : std::string_view, Napi::String {}; + +struct StringReferenceLike { + operator std::string&() const { return stringValue; } + operator std::string&&() const { return std::move(stringValue); } + operator std::string_view() const { return viewValue; } + + mutable std::string stringValue; + std::string_view viewValue; +}; + +struct ImplicitAndExplicitStringViewLike { + operator std::string() const { return "unexpected-string-key"; } + + // Copy-initialization must ignore the explicit conversion below. + // Direct-initialization would prefer it for a non-const lvalue. + operator std::string_view() const& { return value; } + + explicit operator std::string_view() & { + return "unexpected-explicit-string-view-key"; + } + + std::string_view value; +}; + +} // namespace + +Symbol CreateNewSymbolWithNoArgs(const Napi::CallbackInfo&) { + return Napi::Symbol(); +} + +Symbol CreateNewSymbolWithCppStrDesc(const Napi::CallbackInfo& info) { + String cppStrKey = info[0].As(); + return Napi::Symbol::New(info.Env(), cppStrKey.Utf8Value()); +} + +Symbol CreateNewSymbolWithCStrDesc(const Napi::CallbackInfo& info) { + String cStrKey = info[0].As(); + return Napi::Symbol::New(info.Env(), cStrKey.Utf8Value().c_str()); +} + +Symbol CreateNewSymbolWithNapiString(const Napi::CallbackInfo& info) { + String strKey = info[0].As(); + return Napi::Symbol::New(info.Env(), strKey); +} + +Symbol GetWellknownSymbol(const Napi::CallbackInfo& info) { + String registrySymbol = info[0].As(); + return MaybeUnwrap( + Napi::Symbol::WellKnown(info.Env(), registrySymbol.Utf8Value().c_str())); +} + +Symbol FetchSymbolFromGlobalRegistry(const Napi::CallbackInfo& info) { + String registrySymbol = info[0].As(); + return MaybeUnwrap(Napi::Symbol::For(info.Env(), registrySymbol)); +} + +Symbol FetchSymbolFromGlobalRegistryWithCppKey(const Napi::CallbackInfo& info) { + String cppStringKey = info[0].As(); + return MaybeUnwrap(Napi::Symbol::For(info.Env(), cppStringKey.Utf8Value())); +} + +Symbol FetchSymbolFromGlobalRegistryWithStringViewKey( + const Napi::CallbackInfo& info) { + String cppStringKey = info[0].As(); + std::string key = cppStringKey.Utf8Value(); + return MaybeUnwrap(Napi::Symbol::For(info.Env(), std::string_view(key))); +} + +Symbol FetchSymbolFromGlobalRegistryWithStringLikeKey( + const Napi::CallbackInfo& info) { + StringLike key{info[0].As().Utf8Value()}; + return MaybeUnwrap(Napi::Symbol::For(info.Env(), key)); +} + +Symbol FetchSymbolFromGlobalRegistryWithRvalueStringLikeKey( + const Napi::CallbackInfo& info) { + return MaybeUnwrap(Napi::Symbol::For( + info.Env(), RvalueStringLike{info[0].As().Utf8Value()})); +} + +Symbol FetchSymbolFromGlobalRegistryWithStringOnlyLikeKey( + const Napi::CallbackInfo& info) { + StringOnlyLike key{info[0].As().Utf8Value()}; + return MaybeUnwrap(Napi::Symbol::For(info.Env(), key)); +} + +Symbol FetchSymbolFromGlobalRegistryWithBothBasesKey( + const Napi::CallbackInfo& info) { + std::string value = info[0].As().Utf8Value(); + BothBases key; + static_cast(key) = "unexpected-string-key"; + static_cast(key) = value; + return MaybeUnwrap(Symbol::For(info.Env(), key)); +} + +Symbol FetchSymbolFromGlobalRegistryWithViewAndNapiStringKey( + const Napi::CallbackInfo& info) { + Env env = info.Env(); + std::string value = info[0].As().Utf8Value(); + ViewAndNapiString key; + static_cast(key) = value; + static_cast(key) = + Napi::String::New(env, "unexpected-napi-string-key"); + return MaybeUnwrap(Symbol::For(env, key)); +} + +Symbol FetchSymbolFromGlobalRegistryWithStringReferenceKey( + const Napi::CallbackInfo& info) { + std::string value = info[0].As().Utf8Value(); + StringReferenceLike key{"unexpected-string-reference-key", value}; + return MaybeUnwrap(Symbol::For(info.Env(), key)); +} + +Symbol FetchSymbolFromGlobalRegistryWithImplicitViewKey( + const Napi::CallbackInfo& info) { + std::string value = info[0].As().Utf8Value(); + ImplicitAndExplicitStringViewLike key{value}; + return MaybeUnwrap(Symbol::For(info.Env(), key)); +} + +Symbol FetchSymbolFromGlobalRegistryWithCKey(const Napi::CallbackInfo& info) { + String cppStringKey = info[0].As(); + return MaybeUnwrap( + Napi::Symbol::For(info.Env(), cppStringKey.Utf8Value().c_str())); +} + +Symbol TestUndefinedSymbolsCanBeCreated(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + return MaybeUnwrap(Napi::Symbol::For(env, env.Undefined())); +} + +Symbol TestNullSymbolsCanBeCreated(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + return MaybeUnwrap(Napi::Symbol::For(env, env.Null())); +} + +Object InitSymbol(Env env) { + Object exports = Object::New(env); + + exports["createNewSymbolWithNoArgs"] = + Function::New(env, CreateNewSymbolWithNoArgs); + exports["createNewSymbolWithCppStr"] = + Function::New(env, CreateNewSymbolWithCppStrDesc); + exports["createNewSymbolWithCStr"] = + Function::New(env, CreateNewSymbolWithCStrDesc); + exports["createNewSymbolWithNapi"] = + Function::New(env, CreateNewSymbolWithNapiString); + exports["getWellKnownSymbol"] = Function::New(env, GetWellknownSymbol); + exports["getSymbolFromGlobalRegistry"] = + Function::New(env, FetchSymbolFromGlobalRegistry); + exports["getSymbolFromGlobalRegistryWithCKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithCKey); + exports["getSymbolFromGlobalRegistryWithCppKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithCppKey); + exports["getSymbolFromGlobalRegistryWithStringViewKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithStringViewKey); + exports["getSymbolFromGlobalRegistryWithStringLikeKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithStringLikeKey); + exports["getSymbolFromGlobalRegistryWithRvalueStringLikeKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithRvalueStringLikeKey); + exports["getSymbolFromGlobalRegistryWithStringOnlyLikeKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithStringOnlyLikeKey); + exports["getSymbolFromGlobalRegistryWithBothBasesKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithBothBasesKey); + exports["getSymbolFromGlobalRegistryWithViewAndNapiStringKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithViewAndNapiStringKey); + exports["getSymbolFromGlobalRegistryWithStringReferenceKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithStringReferenceKey); + exports["getSymbolFromGlobalRegistryWithImplicitViewKey"] = + Function::New(env, FetchSymbolFromGlobalRegistryWithImplicitViewKey); + exports["testUndefinedSymbolCanBeCreated"] = + Function::New(env, TestUndefinedSymbolsCanBeCreated); + exports["testNullSymbolCanBeCreated"] = + Function::New(env, TestNullSymbolsCanBeCreated); + return exports; +} diff --git a/test/node-addon-api/test/symbol.js b/test/node-addon-api/test/symbol.js new file mode 100644 index 0000000..6ecbb90 --- /dev/null +++ b/test/node-addon-api/test/symbol.js @@ -0,0 +1,89 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + const majorNodeVersion = process.versions.node.split('.')[0]; + + const wellKnownSymbolFunctions = ['asyncIterator', 'hasInstance', 'isConcatSpreadable', 'iterator', 'match', 'replace', 'search', 'split', 'species', 'toPrimitive', 'toStringTag', 'unscopables']; + if (majorNodeVersion >= 12) { + wellKnownSymbolFunctions.push('matchAll'); + } + + function assertCanCreateSymbol (symbol) { + assert(binding.symbol.createNewSymbolWithCppStr(symbol) !== null); + assert(binding.symbol.createNewSymbolWithCStr(symbol) !== null); + assert(binding.symbol.createNewSymbolWithNapi(symbol) !== null); + } + + function assertSymbolAreUnique (symbol) { + const symbolOne = binding.symbol.createNewSymbolWithCppStr(symbol); + const symbolTwo = binding.symbol.createNewSymbolWithCppStr(symbol); + + assert(symbolOne !== symbolTwo); + } + + function assertSymbolIsWellknown (symbol) { + const symbOne = binding.symbol.getWellKnownSymbol(symbol); + const symbTwo = binding.symbol.getWellKnownSymbol(symbol); + assert(symbOne && symbTwo); + assert(symbOne === symbTwo); + } + + function assertSymbolIsNotWellknown (symbol) { + const symbolTest = binding.symbol.getWellKnownSymbol(symbol); + assert(symbolTest === undefined); + } + + function assertCanCreateOrFetchGlobalSymbols (symbol, fetchFunction) { + const symbOne = fetchFunction(symbol); + const symbTwo = fetchFunction(symbol); + assert(symbOne && symbTwo); + assert(symbOne === symbTwo); + assert(symbOne === Symbol.for(symbol)); + } + + assertCanCreateSymbol('testing'); + assertSymbolAreUnique('symbol'); + assertSymbolIsNotWellknown('testing'); + + for (const wellknownProperty of wellKnownSymbolFunctions) { + assertSymbolIsWellknown(wellknownProperty); + } + + assertCanCreateOrFetchGlobalSymbols('data', binding.symbol.getSymbolFromGlobalRegistry); + assertCanCreateOrFetchGlobalSymbols('CppKey', binding.symbol.getSymbolFromGlobalRegistryWithCppKey); + assertCanCreateOrFetchGlobalSymbols('StringViewKey', binding.symbol.getSymbolFromGlobalRegistryWithStringViewKey); + assertCanCreateOrFetchGlobalSymbols( + 'StringLikeKey', + binding.symbol.getSymbolFromGlobalRegistryWithStringLikeKey); + assertCanCreateOrFetchGlobalSymbols( + 'RvalueStringLikeKey', + binding.symbol.getSymbolFromGlobalRegistryWithRvalueStringLikeKey); + assertCanCreateOrFetchGlobalSymbols( + 'StringOnlyLikeKey', + binding.symbol.getSymbolFromGlobalRegistryWithStringOnlyLikeKey); + assertCanCreateOrFetchGlobalSymbols( + 'BothBasesKey', + binding.symbol.getSymbolFromGlobalRegistryWithBothBasesKey); + assertCanCreateOrFetchGlobalSymbols( + 'ViewAndNapiStringKey', + binding.symbol.getSymbolFromGlobalRegistryWithViewAndNapiStringKey); + assertCanCreateOrFetchGlobalSymbols( + 'StringReferenceKey', + binding.symbol.getSymbolFromGlobalRegistryWithStringReferenceKey); + assertCanCreateOrFetchGlobalSymbols( + 'ImplicitViewKey', + binding.symbol.getSymbolFromGlobalRegistryWithImplicitViewKey); + assertCanCreateOrFetchGlobalSymbols('CKey', binding.symbol.getSymbolFromGlobalRegistryWithCKey); + + assert(binding.symbol.createNewSymbolWithNoArgs() === undefined); + + // eslint-disable-next-line no-self-compare + assert(binding.symbol.testNullSymbolCanBeCreated() === binding.symbol.testNullSymbolCanBeCreated()); + // eslint-disable-next-line no-self-compare + assert(binding.symbol.testUndefinedSymbolCanBeCreated() === binding.symbol.testUndefinedSymbolCanBeCreated()); + assert(binding.symbol.testUndefinedSymbolCanBeCreated() !== binding.symbol.testNullSymbolCanBeCreated()); +} diff --git a/test/node-addon-api/test/testUtil.js b/test/node-addon-api/test/testUtil.js new file mode 100644 index 0000000..470ba81 --- /dev/null +++ b/test/node-addon-api/test/testUtil.js @@ -0,0 +1,54 @@ +// Run each test function in sequence, +// with an async delay and GC call between each. + +function tick (x) { + return new Promise((resolve) => { + setImmediate(function ontick () { + if (--x === 0) { + resolve(); + } else { + setImmediate(ontick); + } + }); + }); +} + +async function runGCTests (tests) { + // Break up test list into a list of lists of the form + // [ [ 'test name', function() {}, ... ], ..., ]. + const testList = []; + let currentTest; + for (const item of tests) { + if (typeof item === 'string') { + currentTest = []; + testList.push(currentTest); + } + currentTest.push(item); + } + + for (const test of testList) { + await (async function (test) { + let title; + for (let i = 0; i < test.length; i++) { + if (i === 0) { + title = test[i]; + } else { + try { + test[i](); + } catch (e) { + console.error('Test failed: ' + title); + throw e; + } + if (i < tests.length - 1) { + global.gc(); + await tick(10); + } + } + } + })(test); + } +} + +module.exports = { + runGCTests +}; diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function.cc b/test/node-addon-api/test/threadsafe_function/threadsafe_function.cc new file mode 100644 index 0000000..8902b73 --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function.cc @@ -0,0 +1,230 @@ +#include +#include +#include +#include +#include "napi.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +constexpr size_t ARRAY_LENGTH = 10; +constexpr size_t MAX_QUEUE_SIZE = 2; + +static std::thread threads[2]; +static ThreadSafeFunction s_tsfn; + +struct ThreadSafeFunctionInfo { + enum CallType { + DEFAULT, + BLOCKING, + NON_BLOCKING, + NON_BLOCKING_DEFAULT, + NON_BLOCKING_SINGLE_ARG + } type; + bool abort; + bool startSecondary; + FunctionReference jsFinalizeCallback; + uint32_t maxQueueSize; + bool closeCalledFromJs; + std::mutex protect; + std::condition_variable signal; +} tsfnInfo; + +// Thread data to transmit to JS +static int ints[ARRAY_LENGTH]; + +static void SecondaryThread() { + if (s_tsfn.Release() != napi_ok) { + Error::Fatal("SecondaryThread", "ThreadSafeFunction.Release() failed"); + } +} + +// Source thread producing the data +static void DataSourceThread() { + ThreadSafeFunctionInfo* info = s_tsfn.GetContext(); + + if (info->startSecondary) { + if (s_tsfn.Acquire() != napi_ok) { + Error::Fatal("DataSourceThread", "ThreadSafeFunction.Acquire() failed"); + } + threads[1] = std::thread(SecondaryThread); + } + + bool queueWasFull = false; + bool queueWasClosing = false; + + for (int index = ARRAY_LENGTH - 1; index > -1 && !queueWasClosing; index--) { + napi_status status = napi_generic_failure; + + auto callback = [](Env env, Function jsCallback, int* data) { + jsCallback.Call({Number::New(env, *data)}); + }; + + auto noArgCallback = [](Env env, Function jsCallback) { + jsCallback.Call({Number::New(env, 42)}); + }; + + switch (info->type) { + case ThreadSafeFunctionInfo::DEFAULT: + status = s_tsfn.BlockingCall(); + break; + case ThreadSafeFunctionInfo::BLOCKING: + status = s_tsfn.BlockingCall(&ints[index], callback); + break; + case ThreadSafeFunctionInfo::NON_BLOCKING: + status = s_tsfn.NonBlockingCall(&ints[index], callback); + break; + case ThreadSafeFunctionInfo::NON_BLOCKING_DEFAULT: + status = s_tsfn.NonBlockingCall(); + break; + + case ThreadSafeFunctionInfo::NON_BLOCKING_SINGLE_ARG: + status = s_tsfn.NonBlockingCall(noArgCallback); + break; + } + + if (info->abort && (info->type == ThreadSafeFunctionInfo::BLOCKING || + info->type == ThreadSafeFunctionInfo::DEFAULT)) { + // Let's make this thread really busy to give the main thread a chance to + // abort / close. + std::unique_lock lk(info->protect); + while (!info->closeCalledFromJs) { + info->signal.wait(lk); + } + } + + switch (status) { + case napi_queue_full: + queueWasFull = true; + index++; + // fall through + + case napi_ok: + continue; + + case napi_closing: + queueWasClosing = true; + break; + + default: + Error::Fatal("DataSourceThread", "ThreadSafeFunction.*Call() failed"); + } + } + + if (info->type == ThreadSafeFunctionInfo::NON_BLOCKING && !queueWasFull) { + Error::Fatal("DataSourceThread", "Queue was never full"); + } + + if (info->abort && !queueWasClosing) { + Error::Fatal("DataSourceThread", "Queue was never closing"); + } + + if (!queueWasClosing && s_tsfn.Release() != napi_ok) { + Error::Fatal("DataSourceThread", "ThreadSafeFunction.Release() failed"); + } +} + +static Value StopThread(const CallbackInfo& info) { + tsfnInfo.jsFinalizeCallback = Napi::Persistent(info[0].As()); + bool abort = info[1].As(); + if (abort) { + s_tsfn.Abort(); + } else { + s_tsfn.Release(); + } + { + std::lock_guard _(tsfnInfo.protect); + tsfnInfo.closeCalledFromJs = true; + tsfnInfo.signal.notify_one(); + } + return Value(); +} + +// Join the thread and inform JS that we're done. +static void JoinTheThreads(Env /* env */, + std::thread* theThreads, + ThreadSafeFunctionInfo* info) { + theThreads[0].join(); + if (info->startSecondary) { + theThreads[1].join(); + } + + info->jsFinalizeCallback.Call({}); + info->jsFinalizeCallback.Reset(); +} + +static Value StartThreadInternal(const CallbackInfo& info, + ThreadSafeFunctionInfo::CallType type) { + tsfnInfo.type = type; + tsfnInfo.abort = info[1].As(); + tsfnInfo.startSecondary = info[2].As(); + tsfnInfo.maxQueueSize = info[3].As().Uint32Value(); + tsfnInfo.closeCalledFromJs = false; + + s_tsfn = ThreadSafeFunction::New(info.Env(), + info[0].As(), + "Test", + tsfnInfo.maxQueueSize, + 2, + &tsfnInfo, + JoinTheThreads, + threads); + + threads[0] = std::thread(DataSourceThread); + + return Value(); +} + +static Value Release(const CallbackInfo& /* info */) { + if (s_tsfn.Release() != napi_ok) { + Error::Fatal("Release", "ThreadSafeFunction.Release() failed"); + } + return Value(); +} + +static Value StartThread(const CallbackInfo& info) { + return StartThreadInternal(info, ThreadSafeFunctionInfo::BLOCKING); +} + +static Value StartThreadNonblocking(const CallbackInfo& info) { + return StartThreadInternal(info, ThreadSafeFunctionInfo::NON_BLOCKING); +} + +static Value StartThreadNoNative(const CallbackInfo& info) { + return StartThreadInternal(info, ThreadSafeFunctionInfo::DEFAULT); +} + +static Value StartThreadNonblockingNoNative(const CallbackInfo& info) { + return StartThreadInternal(info, + ThreadSafeFunctionInfo::NON_BLOCKING_DEFAULT); +} + +static Value StartThreadNonBlockingSingleArg(const CallbackInfo& info) { + return StartThreadInternal(info, + ThreadSafeFunctionInfo::NON_BLOCKING_SINGLE_ARG); +} + +Object InitThreadSafeFunction(Env env) { + for (size_t index = 0; index < ARRAY_LENGTH; index++) { + ints[index] = index; + } + + Object exports = Object::New(env); + exports["ARRAY_LENGTH"] = Number::New(env, ARRAY_LENGTH); + exports["MAX_QUEUE_SIZE"] = Number::New(env, MAX_QUEUE_SIZE); + exports["startThread"] = Function::New(env, StartThread); + exports["startThreadNoNative"] = Function::New(env, StartThreadNoNative); + exports["startThreadNonblockingNoNative"] = + Function::New(env, StartThreadNonblockingNoNative); + exports["startThreadNonblocking"] = + Function::New(env, StartThreadNonblocking); + exports["startThreadNonblockSingleArg"] = + Function::New(env, StartThreadNonBlockingSingleArg); + exports["stopThread"] = Function::New(env, StopThread); + exports["release"] = Function::New(env, Release); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function.js b/test/node-addon-api/test/threadsafe_function/threadsafe_function.js new file mode 100644 index 0000000..b29dfad --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function.js @@ -0,0 +1,225 @@ +'use strict'; + +const assert = require('assert'); +const common = require('../common'); + +module.exports = common.runTest(test); + +// Main test body +async function test (binding) { + const expectedArray = (function (arrayLength) { + const result = []; + for (let index = 0; index < arrayLength; index++) { + result.push(arrayLength - 1 - index); + } + return result; + })(binding.threadsafe_function.ARRAY_LENGTH); + + const expectedDefaultArray = Array.from({ length: binding.threadsafe_function.ARRAY_LENGTH }, (_, i) => 42); + + function testWithJSMarshaller ({ + threadStarter, + quitAfter, + abort, + maxQueueSize, + launchSecondary + }) { + return new Promise((resolve) => { + const array = []; + binding.threadsafe_function[threadStarter](function testCallback (value) { + array.push(value); + if (array.length === quitAfter) { + binding.threadsafe_function.stopThread(common.mustCall(() => { + resolve(array); + }), !!abort); + } + }, !!abort, !!launchSecondary, maxQueueSize); + if ((threadStarter === 'startThreadNonblocking' || threadStarter === 'startThreadNonblockSingleArg')) { + // 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. + const start = Date.now(); + while (Date.now() - start < 200); + } + }); + } + + function testWithoutJSMarshallers (nativeFunction) { + return new Promise((resolve) => { + let callCount = 0; + nativeFunction(function testCallback () { + callCount++; + + // The default call-into-JS implementation passes no arguments. + assert.strictEqual(arguments.length, 0); + if (callCount === binding.threadsafe_function.ARRAY_LENGTH) { + setImmediate(() => { + binding.threadsafe_function.stopThread(common.mustCall(() => { + resolve(); + }), false); + }); + } + }, false /* abort */, false /* launchSecondary */, + binding.threadsafe_function.MAX_QUEUE_SIZE); + }); + } + + await testWithoutJSMarshallers(binding.threadsafe_function.startThreadNoNative); + await testWithoutJSMarshallers(binding.threadsafe_function.startThreadNonblockingNoNative); + + // Start the thread in blocking mode, and assert that all values are passed. + // Quit after it's done. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThread', + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: binding.threadsafe_function.ARRAY_LENGTH + }), + expectedArray + ); + + // Start the thread in blocking mode with an infinite queue, and assert that + // all values are passed. Quit after it's done. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThread', + maxQueueSize: 0, + quitAfter: binding.threadsafe_function.ARRAY_LENGTH + }), + expectedArray + ); + + // Start the thread in non-blocking mode, and assert that all values are + // passed. Quit after it's done. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThreadNonblocking', + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: binding.threadsafe_function.ARRAY_LENGTH + }), + expectedArray + ); + + // Start the thread in blocking mode, and assert that all values are passed. + // Quit early, but let the thread finish. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThread', + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: 1 + }), + expectedArray + ); + + // Start the thread in blocking mode with an infinite queue, and assert that + // all values are passed. Quit early, but let the thread finish. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThread', + maxQueueSize: 0, + quitAfter: 1 + }), + expectedArray + ); + + // Start the thread in non-blocking mode, and assert that all values are + // passed. Quit early, but let the thread finish. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThreadNonblocking', + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: 1 + }), + expectedArray + ); + + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThreadNonblockSingleArg', + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: 1 + }), + expectedDefaultArray + ); + + // Start the thread in blocking mode, and assert that all values are passed. + // Quit early, but let the thread finish. Launch a secondary thread to test + // the reference counter incrementing functionality. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThread', + quitAfter: 1, + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + launchSecondary: true + }), + expectedArray + ); + + // Start the thread in non-blocking mode, and assert that all values are + // passed. Quit early, but let the thread finish. Launch a secondary thread + // to test the reference counter incrementing functionality. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThreadNonblocking', + quitAfter: 1, + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + launchSecondary: true + }), + expectedArray + ); + + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThreadNonblockSingleArg', + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: 1, + launchSecondary: true + }), + expectedDefaultArray + ); + + // Start the thread in blocking mode, and assert that it could not finish. + // Quit early by aborting. + assert.strictEqual( + (await testWithJSMarshaller({ + threadStarter: 'startThread', + quitAfter: 1, + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + abort: true + })).indexOf(0), + -1 + ); + + // Start the thread in blocking mode with an infinite queue, and assert that + // it could not finish. Quit early by aborting. + assert.strictEqual( + (await testWithJSMarshaller({ + threadStarter: 'startThread', + quitAfter: 1, + maxQueueSize: 0, + abort: true + })).indexOf(0), + -1 + ); + + // Start the thread in non-blocking mode, and assert that it could not finish. + // Quit early and aborting. + assert.strictEqual( + (await testWithJSMarshaller({ + threadStarter: 'startThreadNonblocking', + quitAfter: 1, + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + abort: true + })).indexOf(0), + -1 + ); + + assert.strictEqual( + (await testWithJSMarshaller({ + threadStarter: 'startThreadNonblockSingleArg', + quitAfter: 1, + maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, + abort: true + })).indexOf(0), + -1 + ); +} diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_ctx.cc b/test/node-addon-api/test/threadsafe_function/threadsafe_function_ctx.cc new file mode 100644 index 0000000..abe92fd --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_ctx.cc @@ -0,0 +1,155 @@ +#include +#include "napi.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +class TSFNWrap : public ObjectWrap { + public: + static Function Init(Napi::Env env); + TSFNWrap(const CallbackInfo& info); + + Napi::Value GetContext(const CallbackInfo& /*info*/) { + Reference* ctx = _tsfn.GetContext(); + return ctx->Value(); + }; + + Napi::Value Release(const CallbackInfo& info) { + Napi::Env env = info.Env(); + _deferred = std::unique_ptr(new Promise::Deferred(env)); + _tsfn.Release(); + return _deferred->Promise(); + }; + + private: + ThreadSafeFunction _tsfn; + std::unique_ptr _deferred; +}; + +Function TSFNWrap::Init(Napi::Env env) { + Function func = + DefineClass(env, + "TSFNWrap", + {InstanceMethod("getContext", &TSFNWrap::GetContext), + InstanceMethod("release", &TSFNWrap::Release)}); + return func; +} + +TSFNWrap::TSFNWrap(const CallbackInfo& info) : ObjectWrap(info) { + Napi::Env env = info.Env(); + + Reference* _ctx = new Reference; + *_ctx = Persistent(info[0]); + + _tsfn = ThreadSafeFunction::New( + info.Env(), + Function::New(env, [](const CallbackInfo& /*info*/) {}), + Object::New(env), + "Test", + 1, + 1, + _ctx, + [this](Napi::Env env, Reference* ctx) { + _deferred->Resolve(env.Undefined()); + ctx->Reset(); + delete ctx; + }); +} +struct SimpleTestContext { + SimpleTestContext(int val) : _val(val) {} + int _val = -1; +}; + +void AssertGetContextFromVariousTSOverloads(const CallbackInfo& info) { + Env env = info.Env(); + Function emptyFunc; + + SimpleTestContext* ctx = new SimpleTestContext(42); + ThreadSafeFunction fn = + ThreadSafeFunction::New(env, emptyFunc, "testResource", 1, 1, ctx); + + assert(fn.GetContext() == ctx); + delete ctx; + fn.Release(); + + fn = ThreadSafeFunction::New(env, emptyFunc, "testRes", 1, 1, [](Env) {}); + fn.Release(); + + ctx = new SimpleTestContext(42); + fn = ThreadSafeFunction::New(env, + emptyFunc, + Object::New(env), + "resStrObj", + 1, + 1, + ctx, + [](Env, SimpleTestContext*) {}); + assert(fn.GetContext() == ctx); + delete ctx; + fn.Release(); + + fn = ThreadSafeFunction::New( + env, emptyFunc, Object::New(env), "resStrObj", 1, 1); + fn.Release(); + + ctx = new SimpleTestContext(42); + fn = ThreadSafeFunction::New( + env, emptyFunc, Object::New(env), "resStrObj", 1, 1, ctx); + assert(fn.GetContext() == ctx); + delete ctx; + fn.Release(); + + using FinalizerDataType = int; + FinalizerDataType* finalizerData = new int(42); + fn = ThreadSafeFunction::New( + env, + emptyFunc, + Object::New(env), + "resObject", + 1, + 1, + [](Env, FinalizerDataType* data) { + assert(*data == 42); + delete data; + }, + finalizerData); + fn.Release(); + + ctx = new SimpleTestContext(42); + FinalizerDataType* finalizerDataB = new int(42); + + fn = ThreadSafeFunction::New( + env, + emptyFunc, + Object::New(env), + "resObject", + 1, + 1, + ctx, + [](Env, FinalizerDataType* _data, SimpleTestContext* _ctx) { + assert(*_data == 42); + assert(_ctx->_val == 42); + delete _data; + delete _ctx; + }, + finalizerDataB); + assert(fn.GetContext() == ctx); + fn.Release(); +} + +} // namespace + +Object InitThreadSafeFunctionCtx(Env env) { + Object exports = Object::New(env); + Function tsfnWrap = TSFNWrap::Init(env); + exports.Set("TSFNWrap", tsfnWrap); + exports.Set("AssertFnReturnCorrectCxt", + Function::New(env, AssertGetContextFromVariousTSOverloads)); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_ctx.js b/test/node-addon-api/test/threadsafe_function/threadsafe_function_ctx.js new file mode 100644 index 0000000..4ba707b --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_ctx.js @@ -0,0 +1,13 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +async function test (binding) { + const ctx = { }; + const tsfn = new binding.threadsafe_function_ctx.TSFNWrap(ctx); + assert(tsfn.getContext() === ctx); + await tsfn.release(); + binding.threadsafe_function_ctx.AssertFnReturnCorrectCxt(); +} diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_exception.cc b/test/node-addon-api/test/threadsafe_function/threadsafe_function_exception.cc new file mode 100644 index 0000000..9ffe703 --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_exception.cc @@ -0,0 +1,50 @@ +#include +#include "napi.h" +#include "test_helper.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +void CallJS(napi_env env, napi_value /* callback */, void* /*data*/) { + Napi::Error error = Napi::Error::New(env, "test-from-native"); + NAPI_THROW_VOID(error); +} + +void TestCall(const CallbackInfo& info) { + Napi::Env env = info.Env(); + + ThreadSafeFunction wrapped = + ThreadSafeFunction::New(env, + info[0].As(), + Object::New(env), + String::New(env, "Test"), + 0, + 1); + wrapped.BlockingCall(static_cast(nullptr)); + wrapped.Release(); +} + +void TestCallWithNativeCallback(const CallbackInfo& info) { + Napi::Env env = info.Env(); + + ThreadSafeFunction wrapped = ThreadSafeFunction::New( + env, Napi::Function(), Object::New(env), String::New(env, "Test"), 0, 1); + wrapped.BlockingCall(static_cast(nullptr), CallJS); + wrapped.Release(); +} + +} // namespace + +Object InitThreadSafeFunctionException(Env env) { + Object exports = Object::New(env); + exports["testCall"] = Function::New(env, TestCall); + exports["testCallWithNativeCallback"] = + Function::New(env, TestCallWithNativeCallback); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_exception.js b/test/node-addon-api/test/threadsafe_function/threadsafe_function_exception.js new file mode 100644 index 0000000..688a53b --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_exception.js @@ -0,0 +1,20 @@ +'use strict'; + +const common = require('../common'); + +module.exports = common.runTest(test); + +const execArgv = ['--force-node-api-uncaught-exceptions-policy=true']; +async function test () { + await common.runTestInChildProcess({ + suite: 'threadsafe_function_exception', + testName: 'testCall', + execArgv + }); + + await common.runTestInChildProcess({ + suite: 'threadsafe_function_exception', + testName: 'testCallWithNativeCallback', + execArgv + }); +} diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_existing_tsfn.cc b/test/node-addon-api/test/threadsafe_function/threadsafe_function_existing_tsfn.cc new file mode 100644 index 0000000..2264937 --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_existing_tsfn.cc @@ -0,0 +1,125 @@ +#include +#include "napi.h" +#include "test_helper.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +struct TestContext { + TestContext(Promise::Deferred&& deferred) + : deferred(std::move(deferred)), callData(nullptr){}; + + napi_threadsafe_function tsfn; + Promise::Deferred deferred; + double* callData; + + ~TestContext() { + if (callData != nullptr) delete callData; + }; +}; + +void FinalizeCB(napi_env env, void* /*finalizeData */, void* context) { + TestContext* testContext = static_cast(context); + if (testContext->callData != nullptr) { + testContext->deferred.Resolve(Number::New(env, *testContext->callData)); + } else { + testContext->deferred.Resolve(Napi::Env(env).Undefined()); + } + delete testContext; +} + +void CallJSWithData(napi_env env, + napi_value /* callback */, + void* context, + void* data) { + TestContext* testContext = static_cast(context); + testContext->callData = static_cast(data); + + napi_status status = + napi_release_threadsafe_function(testContext->tsfn, napi_tsfn_release); + + NAPI_THROW_IF_FAILED_VOID(env, status); +} + +void CallJSNoData(napi_env env, + napi_value /* callback */, + void* context, + void* /*data*/) { + TestContext* testContext = static_cast(context); + testContext->callData = nullptr; + + napi_status status = + napi_release_threadsafe_function(testContext->tsfn, napi_tsfn_release); + + NAPI_THROW_IF_FAILED_VOID(env, status); +} + +static Value TestCall(const CallbackInfo& info) { + Napi::Env env = info.Env(); + bool isBlocking = false; + bool hasData = false; + if (info.Length() > 0) { + Object opts = info[0].As(); + bool hasProperty = MaybeUnwrap(opts.Has("blocking")); + if (hasProperty) { + isBlocking = MaybeUnwrap(MaybeUnwrap(opts.Get("blocking")).ToBoolean()); + } + hasProperty = MaybeUnwrap(opts.Has("data")); + if (hasProperty) { + hasData = MaybeUnwrap(MaybeUnwrap(opts.Get("data")).ToBoolean()); + } + } + + // Allow optional callback passed from JS. Useful for testing. + Function cb = Function::New(env, [](const CallbackInfo& /*info*/) {}); + + TestContext* testContext = new TestContext(Napi::Promise::Deferred(env)); + + napi_status status = + napi_create_threadsafe_function(env, + cb, + Object::New(env), + String::New(env, "Test"), + 0, + 1, + nullptr, /*finalize data*/ + FinalizeCB, + testContext, + hasData ? CallJSWithData : CallJSNoData, + &testContext->tsfn); + + NAPI_THROW_IF_FAILED(env, status, Value()); + + ThreadSafeFunction wrapped = ThreadSafeFunction(testContext->tsfn); + + // Test the four napi_threadsafe_function direct-accessing calls + if (isBlocking) { + if (hasData) { + wrapped.BlockingCall(static_cast(new double(std::rand()))); + } else { + wrapped.BlockingCall(static_cast(nullptr)); + } + } else { + if (hasData) { + wrapped.NonBlockingCall(static_cast(new double(std::rand()))); + } else { + wrapped.NonBlockingCall(static_cast(nullptr)); + } + } + + return testContext->deferred.Promise(); +} + +} // namespace + +Object InitThreadSafeFunctionExistingTsfn(Env env) { + Object exports = Object::New(env); + exports["testCall"] = Function::New(env, TestCall); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_existing_tsfn.js b/test/node-addon-api/test/threadsafe_function/threadsafe_function_existing_tsfn.js new file mode 100644 index 0000000..8de71f7 --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_existing_tsfn.js @@ -0,0 +1,14 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +async function test (binding) { + const testCall = binding.threadsafe_function_existing_tsfn.testCall; + + assert.strictEqual(typeof await testCall({ blocking: true, data: true }), 'number'); + assert.strictEqual(typeof await testCall({ blocking: true, data: false }), 'undefined'); + assert.strictEqual(typeof await testCall({ blocking: false, data: true }), 'number'); + assert.strictEqual(typeof await testCall({ blocking: false, data: false }), 'undefined'); +} diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_ptr.cc b/test/node-addon-api/test/threadsafe_function/threadsafe_function_ptr.cc new file mode 100644 index 0000000..4a1df14 --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_ptr.cc @@ -0,0 +1,27 @@ +#include "napi.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +static Value Test(const CallbackInfo& info) { + Object resource = info[0].As(); + Function cb = info[1].As(); + ThreadSafeFunction tsfn = + ThreadSafeFunction::New(info.Env(), cb, resource, "Test", 1, 1); + tsfn.Release(); + return info.Env().Undefined(); +} + +} // namespace + +Object InitThreadSafeFunctionPtr(Env env) { + Object exports = Object::New(env); + exports["test"] = Function::New(env, Test); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_ptr.js b/test/node-addon-api/test/threadsafe_function/threadsafe_function_ptr.js new file mode 100644 index 0000000..d646682 --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_ptr.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = require('../common').runTest(test); + +function test (binding) { + binding.threadsafe_function_ptr.test({}, () => {}); +} diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_sum.cc b/test/node-addon-api/test/threadsafe_function/threadsafe_function_sum.cc new file mode 100644 index 0000000..68e72fb --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_sum.cc @@ -0,0 +1,240 @@ +#include +#include +#include +#include +#include "napi.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +struct TestData { + TestData(Promise::Deferred&& deferred) : deferred(std::move(deferred)){}; + + // Native Promise returned to JavaScript + Promise::Deferred deferred; + + // List of threads created for test. This list only ever accessed via main + // thread. + std::vector threads = {}; + + ThreadSafeFunction tsfn = ThreadSafeFunction(); + + // These variables are only accessed from the main thread. + bool mainWantsRelease = false; + size_t expected_calls = 0; +}; + +void FinalizerCallback(Napi::Env env, TestData* finalizeData) { + for (size_t i = 0; i < finalizeData->threads.size(); ++i) { + finalizeData->threads[i].join(); + } + finalizeData->deferred.Resolve(Boolean::New(env, true)); + delete finalizeData; +} + +/** + * See threadsafe_function_sum.js for descriptions of the tests in this file + */ + +void entryWithTSFN(ThreadSafeFunction tsfn, int threadId) { + std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 100 + 1)); + tsfn.BlockingCall([=](Napi::Env env, Function callback) { + callback.Call({Number::New(env, static_cast(threadId))}); + }); + tsfn.Release(); +} + +static Value TestWithTSFN(const CallbackInfo& info) { + int threadCount = info[0].As().Int32Value(); + Function cb = info[1].As(); + + // We pass the test data to the Finalizer for cleanup. The finalizer is + // responsible for deleting this data as well. + TestData* testData = new TestData(Promise::Deferred::New(info.Env())); + + ThreadSafeFunction tsfn = ThreadSafeFunction::New( + info.Env(), + cb, + "Test", + 0, + threadCount, + std::function(FinalizerCallback), + testData); + + for (int i = 0; i < threadCount; ++i) { + // A copy of the ThreadSafeFunction will go to the thread entry point + testData->threads.push_back(std::thread(entryWithTSFN, tsfn, i)); + } + + return testData->deferred.Promise(); +} + +// Task instance created for each new std::thread +class DelayedTSFNTask { + public: + // Each instance has its own tsfn + ThreadSafeFunction tsfn; + + // Thread-safety + std::mutex mtx; + std::condition_variable cv; + + // Entry point for std::thread + void entryDelayedTSFN(int threadId) { + std::unique_lock lk(mtx); + cv.wait(lk, [this] { return this->tsfn != nullptr; }); + tsfn.BlockingCall([=](Napi::Env env, Function callback) { + callback.Call({Number::New(env, static_cast(threadId))}); + }); + tsfn.Release(); + }; +}; + +struct TestDataDelayed { + TestDataDelayed(Promise::Deferred&& deferred) + : deferred(std::move(deferred)){}; + ~TestDataDelayed() { taskInsts.clear(); }; + // Native Promise returned to JavaScript + Promise::Deferred deferred; + + // List of threads created for test. This list only ever accessed via main + // thread. + std::vector threads = {}; + + // List of DelayedTSFNThread instances + std::vector> taskInsts = {}; + + ThreadSafeFunction tsfn = ThreadSafeFunction(); +}; + +void FinalizerCallbackDelayed(Napi::Env env, TestDataDelayed* finalizeData) { + for (size_t i = 0; i < finalizeData->threads.size(); ++i) { + finalizeData->threads[i].join(); + } + finalizeData->deferred.Resolve(Boolean::New(env, true)); + delete finalizeData; +} + +static Value TestDelayedTSFN(const CallbackInfo& info) { + int threadCount = info[0].As().Int32Value(); + Function cb = info[1].As(); + + TestDataDelayed* testData = + new TestDataDelayed(Promise::Deferred::New(info.Env())); + + testData->tsfn = + ThreadSafeFunction::New(info.Env(), + cb, + "Test", + 0, + threadCount, + std::function( + FinalizerCallbackDelayed), + testData); + + for (int i = 0; i < threadCount; ++i) { + testData->taskInsts.push_back( + std::unique_ptr(new DelayedTSFNTask())); + testData->threads.push_back(std::thread(&DelayedTSFNTask::entryDelayedTSFN, + testData->taskInsts.back().get(), + i)); + } + std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 100 + 1)); + + for (auto& task : testData->taskInsts) { + std::lock_guard lk(task->mtx); + task->tsfn = testData->tsfn; + task->cv.notify_all(); + } + + return testData->deferred.Promise(); +} + +void AcquireFinalizerCallback(Napi::Env env, + TestData* finalizeData, + TestData* context) { + (void)context; + for (size_t i = 0; i < finalizeData->threads.size(); ++i) { + finalizeData->threads[i].join(); + } + finalizeData->deferred.Resolve(Boolean::New(env, true)); + delete finalizeData; +} + +void entryAcquire(ThreadSafeFunction tsfn, int threadId) { + tsfn.Acquire(); + TestData* testData = tsfn.GetContext(); + std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 100 + 1)); + tsfn.BlockingCall([=](Napi::Env env, Function callback) { + // This lambda runs on the main thread so it's OK to access the variables + // `expected_calls` and `mainWantsRelease`. + testData->expected_calls--; + if (testData->expected_calls == 0 && testData->mainWantsRelease) + testData->tsfn.Release(); + callback.Call({Number::New(env, static_cast(threadId))}); + }); + tsfn.Release(); +} + +static Value CreateThread(const CallbackInfo& info) { + TestData* testData = static_cast(info.Data()); + // Counting expected calls like this only works because on the JS side this + // binding is called from a synchronous loop. This means the main loop has no + // chance to run the tsfn JS callback before we've counted how many threads + // the JS intends to create. + testData->expected_calls++; + ThreadSafeFunction tsfn = testData->tsfn; + int threadId = testData->threads.size(); + // A copy of the ThreadSafeFunction will go to the thread entry point + testData->threads.push_back(std::thread(entryAcquire, tsfn, threadId)); + return Number::New(info.Env(), threadId); +} + +static Value StopThreads(const CallbackInfo& info) { + TestData* testData = static_cast(info.Data()); + testData->mainWantsRelease = true; + return info.Env().Undefined(); +} + +static Value TestAcquire(const CallbackInfo& info) { + Function cb = info[0].As(); + Napi::Env env = info.Env(); + + // We pass the test data to the Finalizer for cleanup. The finalizer is + // responsible for deleting this data as well. + TestData* testData = new TestData(Promise::Deferred::New(info.Env())); + + testData->tsfn = + ThreadSafeFunction::New(env, + cb, + "Test", + 0, + 1, + testData, + std::function( + AcquireFinalizerCallback), + testData); + + Object result = Object::New(env); + result["createThread"] = + Function::New(env, CreateThread, "createThread", testData); + result["stopThreads"] = + Function::New(env, StopThreads, "stopThreads", testData); + result["promise"] = testData->deferred.Promise(); + + return result; +} +} // namespace + +Object InitThreadSafeFunctionSum(Env env) { + Object exports = Object::New(env); + exports["testDelayedTSFN"] = Function::New(env, TestDelayedTSFN); + exports["testWithTSFN"] = Function::New(env, TestWithTSFN); + exports["testAcquire"] = Function::New(env, TestAcquire); + return exports; +} + +#endif diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_sum.js b/test/node-addon-api/test/threadsafe_function/threadsafe_function_sum.js new file mode 100644 index 0000000..6322544 --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_sum.js @@ -0,0 +1,59 @@ +'use strict'; +const assert = require('assert'); + +/** + * + * ThreadSafeFunction Tests: Thread Id Sums + * + * Every native C++ function that utilizes the TSFN will call the registered + * callback with the thread id. Passing Array.prototype.push with a bound array + * will push the thread id to the array. Therefore, starting `N` threads, we + * will expect the sum of all elements in the array to be `(N-1) * (N) / 2` (as + * thread IDs are 0-based) + * + * We check different methods of passing a ThreadSafeFunction around multiple + * threads: + * - `testWithTSFN`: The main thread creates the TSFN. Then, it creates + * threads, passing the TSFN at thread construction. The number of threads is + * static (known at TSFN creation). + * - `testDelayedTSFN`: The main thread creates threads, passing a promise to a + * TSFN at construction. Then, it creates the TSFN, and resolves each + * threads' promise. The number of threads is static. + * - `testAcquire`: The native binding returns a function to start a new. A + * call to this function will return `false` once `N` calls have been made. + * Each thread will acquire its own use of the TSFN, call it, and then + * release. + */ + +const THREAD_COUNT = 5; +const EXPECTED_SUM = (THREAD_COUNT - 1) * (THREAD_COUNT) / 2; + +module.exports = require('../common').runTest(test); + +/** @param {number[]} N */ +const sum = (N) => N.reduce((sum, n) => sum + n, 0); + +function test (binding) { + async function check (bindingFunction) { + const calls = []; + const result = await bindingFunction(THREAD_COUNT, Array.prototype.push.bind(calls)); + assert.ok(result); + assert.equal(sum(calls), EXPECTED_SUM); + } + + async function checkAcquire () { + const calls = []; + const { promise, createThread, stopThreads } = binding.threadsafe_function_sum.testAcquire(Array.prototype.push.bind(calls)); + for (let i = 0; i < THREAD_COUNT; i++) { + createThread(); + } + stopThreads(); + const result = await promise; + assert.ok(result); + assert.equal(sum(calls), EXPECTED_SUM); + } + + return check(binding.threadsafe_function_sum.testDelayedTSFN) + .then(() => check(binding.threadsafe_function_sum.testWithTSFN)) + .then(() => checkAcquire()); +} diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_unref.cc b/test/node-addon-api/test/threadsafe_function/threadsafe_function_unref.cc new file mode 100644 index 0000000..5fcc5dd --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_unref.cc @@ -0,0 +1,55 @@ +#include "napi.h" +#include "test_helper.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +static Value TestUnref(const CallbackInfo& info) { + Napi::Env env = info.Env(); + Object global = env.Global(); + Object resource = info[0].As(); + Function cb = info[1].As(); + Function setTimeout = MaybeUnwrap(global.Get("setTimeout")).As(); + ThreadSafeFunction* tsfn = new ThreadSafeFunction; + + *tsfn = ThreadSafeFunction::New( + info.Env(), cb, resource, "Test", 1, 1, [tsfn](Napi::Env /* env */) { + delete tsfn; + }); + + tsfn->BlockingCall(); + + setTimeout.Call( + global, + {Function::New( + env, [tsfn](const CallbackInfo& info) { tsfn->Unref(info.Env()); }), + Number::New(env, 100)}); + + return info.Env().Undefined(); +} + +static Value TestRef(const CallbackInfo& info) { + Function cb = info[1].As(); + + auto tsfn = ThreadSafeFunction::New(info.Env(), cb, "testRes", 1, 1); + + tsfn.BlockingCall(); + tsfn.Unref(info.Env()); + tsfn.Ref(info.Env()); + + return info.Env().Undefined(); +} + +} // namespace + +Object InitThreadSafeFunctionUnref(Env env) { + Object exports = Object::New(env); + exports["testUnref"] = Function::New(env, TestUnref); + exports["testRef"] = Function::New(env, TestRef); + return exports; +} + +#endif diff --git a/test/node-addon-api/test/threadsafe_function/threadsafe_function_unref.js b/test/node-addon-api/test/threadsafe_function/threadsafe_function_unref.js new file mode 100644 index 0000000..1f0e96b --- /dev/null +++ b/test/node-addon-api/test/threadsafe_function/threadsafe_function_unref.js @@ -0,0 +1,98 @@ +'use strict'; + +const assert = require('assert'); + +const isMainProcess = process.argv[1] !== __filename; + +/** + * In order to test that the event loop exits even with an active TSFN, we need + * to spawn a new process for the test. + * - Main process: spawns new node instance, executing this script + * - Child process: creates TSFN. Native module Unref's via setTimeout after some time but does NOT call Release. + * + * Main process should expect child process to exit. + * + * We also added a new test case for `Ref`. The idea being, if a TSFN is active, the event loop that it belongs to should not exit + * Our setup is similar to the test for the `Unref` case, with the difference being now we are expecting the child process to hang + */ + +if (isMainProcess) { + module.exports = require('../common').runTestWithBindingPath(test); +} else { + const isTestingRef = (process.argv[3] === 'true'); + + if (isTestingRef) { + execTSFNRefTest(process.argv[2]); + } else { + execTSFNUnrefTest(process.argv[2]); + } +} + +function testUnRefCallback (resolve, reject, bindingFile) { + const child = require('../napi_child').spawn(process.argv[0], [ + '--expose-gc', __filename, bindingFile, false + ], { stdio: 'inherit' }); + + let timeout = setTimeout(function () { + child.kill(); + timeout = 0; + reject(new Error('Expected child to die')); + }, 5000); + + child.on('error', (err) => { + clearTimeout(timeout); + timeout = 0; + reject(new Error(err)); + }); + + child.on('close', (code) => { + if (timeout) clearTimeout(timeout); + assert.strictEqual(code, 0, 'Expected return value 0'); + resolve(); + }); +} + +function testRefCallback (resolve, reject, bindingFile) { + const child = require('../napi_child').spawn(process.argv[0], [ + '--expose-gc', __filename, bindingFile, true + ], { stdio: 'inherit' }); + + let timeout = setTimeout(function () { + child.kill(); + timeout = 0; + resolve(); + }, 1000); + + child.on('error', (err) => { + clearTimeout(timeout); + timeout = 0; + reject(new Error(err)); + }); + + child.on('close', (code) => { + if (timeout) clearTimeout(timeout); + + reject(new Error('We expected Child to hang')); + }); +} + +function test (bindingFile) { + // Main process + return new Promise((resolve, reject) => { + testUnRefCallback(resolve, reject, bindingFile); + }).then(() => { + return new Promise((resolve, reject) => { + testRefCallback(resolve, reject, bindingFile); + }); + }); +} + +function execTSFNUnrefTest (bindingFile) { + const binding = require(bindingFile); + binding.threadsafe_function_unref.testUnref({}, () => { }); +} + +function execTSFNRefTest (bindingFile) { + const binding = require(bindingFile); + binding.threadsafe_function_unref.testRef({}, () => { }); +} diff --git a/test/node-addon-api/test/thunking_manual.cc b/test/node-addon-api/test/thunking_manual.cc new file mode 100644 index 0000000..a9a0adf --- /dev/null +++ b/test/node-addon-api/test/thunking_manual.cc @@ -0,0 +1,127 @@ +#include + +// The formulaic comment below should accompany any code that results in an +// internal piece of heap data getting created, because each such piece of heap +// data must be attached to an object by way of a deleter which gets called when +// the object gets garbage-collected. +// +// At the very least, you can add a fprintf(stderr, ...) to the deleter in +// napi-inl.h and then count the number of times the deleter prints by running +// node --expose-gc test/thunking_manual.js and counting the number of prints +// between the two rows of dashes. That number should coincide with the number +// of formulaic comments below. +// +// Note that currently this result can only be achieved with node-chakracore, +// because V8 does not garbage-collect classes. + +static Napi::Value TestMethod(const Napi::CallbackInfo& /*info*/) { + return Napi::Value(); +} + +static Napi::Value TestGetter(const Napi::CallbackInfo& /*info*/) { + return Napi::Value(); +} + +static void TestSetter(const Napi::CallbackInfo& /*info*/) {} + +class TestClass : public Napi::ObjectWrap { + public: + TestClass(const Napi::CallbackInfo& info) : ObjectWrap(info) {} + static Napi::Value TestClassStaticMethod(const Napi::CallbackInfo& info) { + return Napi::Number::New(info.Env(), 42); + } + + static void TestClassStaticVoidMethod(const Napi::CallbackInfo& /*info*/) {} + + Napi::Value TestClassInstanceMethod(const Napi::CallbackInfo& info) { + return Napi::Number::New(info.Env(), 42); + } + + void TestClassInstanceVoidMethod(const Napi::CallbackInfo& /*info*/) {} + + Napi::Value TestClassInstanceGetter(const Napi::CallbackInfo& info) { + return Napi::Number::New(info.Env(), 42); + } + + void TestClassInstanceSetter(const Napi::CallbackInfo& /*info*/, + const Napi::Value& /*new_value*/) {} + + static Napi::Function NewClass(Napi::Env env) { + return DefineClass( + env, + "TestClass", + {// Make sure to check that the deleter gets called. + StaticMethod("staticMethod", TestClassStaticMethod), + // Make sure to check that the deleter gets called. + StaticMethod("staticVoidMethod", TestClassStaticVoidMethod), + // Make sure to check that the deleter gets called. + StaticMethod(Napi::Symbol::New(env, "staticMethod"), + TestClassStaticMethod), + // Make sure to check that the deleter gets called. + StaticMethod(Napi::Symbol::New(env, "staticVoidMethod"), + TestClassStaticVoidMethod), + // Make sure to check that the deleter gets called. + InstanceMethod("instanceMethod", &TestClass::TestClassInstanceMethod), + // Make sure to check that the deleter gets called. + InstanceMethod("instanceVoidMethod", + &TestClass::TestClassInstanceVoidMethod), + // Make sure to check that the deleter gets called. + InstanceMethod(Napi::Symbol::New(env, "instanceMethod"), + &TestClass::TestClassInstanceMethod), + // Make sure to check that the deleter gets called. + InstanceMethod(Napi::Symbol::New(env, "instanceVoidMethod"), + &TestClass::TestClassInstanceVoidMethod), + // Make sure to check that the deleter gets called. + InstanceAccessor("instanceAccessor", + &TestClass::TestClassInstanceGetter, + &TestClass::TestClassInstanceSetter)}); + } +}; + +static Napi::Value CreateTestObject(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + Napi::Object item = Napi::Object::New(env); + + // Make sure to check that the deleter gets called. + item["testMethod"] = Napi::Function::New(env, TestMethod, "testMethod"); + + item.DefineProperties({ + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor(env, item, "accessor_1", TestGetter), + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor( + env, item, std::string("accessor_1_std_string"), TestGetter), + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor( + env, + item, + Napi::String::New(info.Env(), "accessor_1_js_string"), + TestGetter), + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor( + env, item, "accessor_2", TestGetter, TestSetter), + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor(env, + item, + std::string("accessor_2_std_string"), + TestGetter, + TestSetter), + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor( + env, + item, + Napi::String::New(env, "accessor_2_js_string"), + TestGetter, + TestSetter), + Napi::PropertyDescriptor::Value("TestClass", TestClass::NewClass(env)), + }); + + return item; +} + +Napi::Object InitThunkingManual(Napi::Env env) { + Napi::Object exports = Napi::Object::New(env); + exports["createTestObject"] = + Napi::Function::New(env, CreateTestObject, "createTestObject"); + return exports; +} diff --git a/test/node-addon-api/test/thunking_manual.js b/test/node-addon-api/test/thunking_manual.js new file mode 100644 index 0000000..9ea7266 --- /dev/null +++ b/test/node-addon-api/test/thunking_manual.js @@ -0,0 +1,16 @@ +// Flags: --expose-gc +'use strict'; + +module.exports = require('./common').runTest(test); + +function test (binding) { + console.log('Thunking: Performing initial GC'); + global.gc(); + console.log('Thunking: Creating test object'); + let object = binding.thunking_manual.createTestObject(); + // eslint-disable-next-line no-unused-vars + object = null; + console.log('Thunking: About to GC\n--------'); + global.gc(); + console.log('--------\nThunking: GC complete'); +} diff --git a/test/node-addon-api/test/type_taggable.cc b/test/node-addon-api/test/type_taggable.cc new file mode 100644 index 0000000..ac58f92 --- /dev/null +++ b/test/node-addon-api/test/type_taggable.cc @@ -0,0 +1,66 @@ +#include "napi.h" + +#if (NAPI_VERSION > 7) + +using namespace Napi; + +static const napi_type_tag type_tags[5] = { + {0xdaf987b3cc62481a, 0xb745b0497f299531}, + {0xbb7936c374084d9b, 0xa9548d0762eeedb9}, + {0xa5ed9ce2e4c00c38, 0}, + {0, 0}, + {0xa5ed9ce2e4c00c38, 0xdaf987b3cc62481a}, +}; + +template +class TestTypeTaggable { + public: + static Value TypeTaggedInstance(const CallbackInfo& info) { + TypeTaggable instance = Factory(info.Env()); + uint32_t type_index = info[0].As().Int32Value(); + + instance.TypeTag(&type_tags[type_index]); + + return instance; + } + + static Value CheckTypeTag(const CallbackInfo& info) { + uint32_t type_index = info[0].As().Int32Value(); + TypeTaggable instance = info[1].UnsafeAs(); + + return Boolean::New(info.Env(), + instance.CheckTypeTag(&type_tags[type_index])); + } +}; + +TypeTaggable ObjectFactory(Env env) { + return Object::New(env); +} + +TypeTaggable ExternalFactory(Env env) { + // External does not accept a nullptr for its data. + return External::New(env, reinterpret_cast(0x1)); +} + +using TestObject = TestTypeTaggable; +using TestExternal = TestTypeTaggable>; + +Object InitTypeTaggable(Env env) { + Object exports = Object::New(env); + + Object external = Object::New(env); + exports["external"] = external; + external["checkTypeTag"] = Function::New(env, &TestExternal::CheckTypeTag); + external["typeTaggedInstance"] = + Function::New(env, &TestExternal::TypeTaggedInstance); + + Object object = Object::New(env); + exports["object"] = object; + object["checkTypeTag"] = Function::New(env, &TestObject::CheckTypeTag); + object["typeTaggedInstance"] = + Function::New(env, &TestObject::TypeTaggedInstance); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/type_taggable.js b/test/node-addon-api/test/type_taggable.js new file mode 100644 index 0000000..7bc843c --- /dev/null +++ b/test/node-addon-api/test/type_taggable.js @@ -0,0 +1,59 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +function testTypeTaggable ({ typeTaggedInstance, checkTypeTag }) { + const obj1 = typeTaggedInstance(0); + const obj2 = typeTaggedInstance(1); + + // Verify that type tags are correctly accepted. + assert.strictEqual(checkTypeTag(0, obj1), true); + assert.strictEqual(checkTypeTag(1, obj2), true); + + // Verify that wrongly tagged objects are rejected. + assert.strictEqual(checkTypeTag(0, obj2), false); + assert.strictEqual(checkTypeTag(1, obj1), false); + + // Verify that untagged objects are rejected. + assert.strictEqual(checkTypeTag(0, {}), false); + assert.strictEqual(checkTypeTag(1, {}), false); + + // Node v14 and v16 have an issue checking type tags if the `upper` in + // `napi_type_tag` is 0, so these tests can only be performed on Node version + // >=18. See: + // - https://github.com/nodejs/node/issues/43786 + // - https://github.com/nodejs/node/pull/43788 + const nodeVersion = parseInt(process.versions.node.split('.')[0]); + if (nodeVersion < 18) { + return; + } + + const obj3 = typeTaggedInstance(2); + const obj4 = typeTaggedInstance(3); + + // Verify that untagged objects are rejected. + assert.strictEqual(checkTypeTag(0, {}), false); + assert.strictEqual(checkTypeTag(1, {}), false); + + // Verify that type tags are correctly accepted. + assert.strictEqual(checkTypeTag(0, obj1), true); + assert.strictEqual(checkTypeTag(1, obj2), true); + assert.strictEqual(checkTypeTag(2, obj3), true); + assert.strictEqual(checkTypeTag(3, obj4), true); + + // Verify that wrongly tagged objects are rejected. + assert.strictEqual(checkTypeTag(0, obj2), false); + assert.strictEqual(checkTypeTag(1, obj1), false); + assert.strictEqual(checkTypeTag(0, obj3), false); + assert.strictEqual(checkTypeTag(1, obj4), false); + assert.strictEqual(checkTypeTag(2, obj4), false); + assert.strictEqual(checkTypeTag(3, obj3), false); + assert.strictEqual(checkTypeTag(4, obj3), false); +} + +function test (binding) { + testTypeTaggable(binding.type_taggable.external); + testTypeTaggable(binding.type_taggable.object); +} diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function.cc b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function.cc new file mode 100644 index 0000000..ce345b8 --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function.cc @@ -0,0 +1,215 @@ +#include +#include +#include +#include +#include "napi.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +constexpr size_t ARRAY_LENGTH = 10; +constexpr size_t MAX_QUEUE_SIZE = 2; + +static std::thread threads[2]; + +static struct ThreadSafeFunctionInfo { + enum CallType { DEFAULT, BLOCKING, NON_BLOCKING } type; + bool abort; + bool startSecondary; + FunctionReference jsFinalizeCallback; + uint32_t maxQueueSize; + bool closeCalledFromJs; + std::mutex protect; + std::condition_variable signal; +} tsfnInfo; + +static void TSFNCallJS(Env env, + Function jsCallback, + ThreadSafeFunctionInfo* /* context */, + int* data) { + // A null environment signifies the threadsafe function has been finalized. + if (!(env == nullptr || jsCallback == nullptr)) { + // If called with no data + if (data == nullptr) { + jsCallback.Call({}); + } else { + jsCallback.Call({Number::New(env, *data)}); + } + } +} + +using TSFN = TypedThreadSafeFunction; +static TSFN s_tsfn; + +// Thread data to transmit to JS +static int ints[ARRAY_LENGTH]; + +static void SecondaryThread() { + if (s_tsfn.Release() != napi_ok) { + Error::Fatal("TypedSecondaryThread", "ThreadSafeFunction.Release() failed"); + } +} + +// Source thread producing the data +static void DataSourceThread() { + ThreadSafeFunctionInfo* info = s_tsfn.GetContext(); + + if (info->startSecondary) { + if (s_tsfn.Acquire() != napi_ok) { + Error::Fatal("TypedDataSourceThread", + "ThreadSafeFunction.Acquire() failed"); + } + + threads[1] = std::thread(SecondaryThread); + } + + bool queueWasFull = false; + bool queueWasClosing = false; + for (int index = ARRAY_LENGTH - 1; index > -1 && !queueWasClosing; index--) { + napi_status status = napi_generic_failure; + + switch (info->type) { + case ThreadSafeFunctionInfo::DEFAULT: + status = s_tsfn.BlockingCall(); + break; + case ThreadSafeFunctionInfo::BLOCKING: + status = s_tsfn.BlockingCall(&ints[index]); + break; + case ThreadSafeFunctionInfo::NON_BLOCKING: + status = s_tsfn.NonBlockingCall(&ints[index]); + break; + } + + if (info->abort && info->type != ThreadSafeFunctionInfo::NON_BLOCKING) { + // Let's make this thread really busy to give the main thread a chance to + // abort / close. + std::unique_lock lk(info->protect); + while (!info->closeCalledFromJs) { + info->signal.wait(lk); + } + } + + switch (status) { + case napi_queue_full: + queueWasFull = true; + index++; + // fall through + + case napi_ok: + continue; + + case napi_closing: + queueWasClosing = true; + break; + + default: + Error::Fatal("TypedDataSourceThread", + "ThreadSafeFunction.*Call() failed"); + } + } + + if (info->type == ThreadSafeFunctionInfo::NON_BLOCKING && !queueWasFull) { + Error::Fatal("TypedDataSourceThread", "Queue was never full"); + } + + if (info->abort && !queueWasClosing) { + Error::Fatal("TypedDataSourceThread", "Queue was never closing"); + } + + if (!queueWasClosing && s_tsfn.Release() != napi_ok) { + Error::Fatal("TypedDataSourceThread", + "ThreadSafeFunction.Release() failed"); + } +} + +static Value StopThread(const CallbackInfo& info) { + tsfnInfo.jsFinalizeCallback = Napi::Persistent(info[0].As()); + bool abort = info[1].As(); + if (abort) { + s_tsfn.Abort(); + } else { + s_tsfn.Release(); + } + { + std::lock_guard _(tsfnInfo.protect); + tsfnInfo.closeCalledFromJs = true; + tsfnInfo.signal.notify_one(); + } + return Value(); +} + +// Join the thread and inform JS that we're done. +static void JoinTheThreads(Env /* env */, + std::thread* theThreads, + ThreadSafeFunctionInfo* info) { + theThreads[0].join(); + if (info->startSecondary) { + theThreads[1].join(); + } + + info->jsFinalizeCallback.Call({}); + info->jsFinalizeCallback.Reset(); +} + +static Value StartThreadInternal(const CallbackInfo& info, + ThreadSafeFunctionInfo::CallType type) { + tsfnInfo.type = type; + tsfnInfo.abort = info[1].As(); + tsfnInfo.startSecondary = info[2].As(); + tsfnInfo.maxQueueSize = info[3].As().Uint32Value(); + tsfnInfo.closeCalledFromJs = false; + + s_tsfn = TSFN::New(info.Env(), + info[0].As(), + Object::New(info.Env()), + "Test", + tsfnInfo.maxQueueSize, + 2, + &tsfnInfo, + JoinTheThreads, + threads); + + threads[0] = std::thread(DataSourceThread); + + return Value(); +} + +static Value Release(const CallbackInfo& /* info */) { + if (s_tsfn.Release() != napi_ok) { + Error::Fatal("Release", "TypedThreadSafeFunction.Release() failed"); + } + return Value(); +} + +static Value StartThread(const CallbackInfo& info) { + return StartThreadInternal(info, ThreadSafeFunctionInfo::BLOCKING); +} + +static Value StartThreadNonblocking(const CallbackInfo& info) { + return StartThreadInternal(info, ThreadSafeFunctionInfo::NON_BLOCKING); +} + +static Value StartThreadNoNative(const CallbackInfo& info) { + return StartThreadInternal(info, ThreadSafeFunctionInfo::DEFAULT); +} + +Object InitTypedThreadSafeFunction(Env env) { + for (size_t index = 0; index < ARRAY_LENGTH; index++) { + ints[index] = index; + } + + Object exports = Object::New(env); + exports["ARRAY_LENGTH"] = Number::New(env, ARRAY_LENGTH); + exports["MAX_QUEUE_SIZE"] = Number::New(env, MAX_QUEUE_SIZE); + exports["startThread"] = Function::New(env, StartThread); + exports["startThreadNoNative"] = Function::New(env, StartThreadNoNative); + exports["startThreadNonblocking"] = + Function::New(env, StartThreadNonblocking); + exports["stopThread"] = Function::New(env, StopThread); + exports["release"] = Function::New(env, Release); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function.js b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function.js new file mode 100644 index 0000000..6ef2876 --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function.js @@ -0,0 +1,188 @@ +'use strict'; + +const assert = require('assert'); +const common = require('../common'); + +module.exports = common.runTest(test); + +async function test (binding) { + const expectedArray = (function (arrayLength) { + const result = []; + for (let index = 0; index < arrayLength; index++) { + result.push(arrayLength - 1 - index); + } + return result; + })(binding.typed_threadsafe_function.ARRAY_LENGTH); + + function testWithJSMarshaller ({ + threadStarter, + quitAfter, + abort, + maxQueueSize, + launchSecondary + }) { + return new Promise((resolve) => { + const array = []; + binding.typed_threadsafe_function[threadStarter](function testCallback (value) { + array.push(value); + if (array.length === quitAfter) { + binding.typed_threadsafe_function.stopThread(common.mustCall(() => { + resolve(array); + }), !!abort); + } + }, !!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. + const start = Date.now(); + while (Date.now() - start < 200); + } + }); + } + + await new Promise(function testWithoutJSMarshaller (resolve) { + let callCount = 0; + binding.typed_threadsafe_function.startThreadNoNative(function testCallback () { + callCount++; + + // The default call-into-JS implementation passes no arguments. + assert.strictEqual(arguments.length, 0); + if (callCount === binding.typed_threadsafe_function.ARRAY_LENGTH) { + setImmediate(() => { + binding.typed_threadsafe_function.stopThread(common.mustCall(() => { + resolve(); + }), false); + }); + } + }, false /* abort */, false /* launchSecondary */, + binding.typed_threadsafe_function.MAX_QUEUE_SIZE); + }); + + // Start the thread in blocking mode, and assert that all values are passed. + // Quit after it's done. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThread', + maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: binding.typed_threadsafe_function.ARRAY_LENGTH + }), + expectedArray + ); + + // Start the thread in blocking mode with an infinite queue, and assert that + // all values are passed. Quit after it's done. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThread', + maxQueueSize: 0, + quitAfter: binding.typed_threadsafe_function.ARRAY_LENGTH + }), + expectedArray + ); + + // Start the thread in non-blocking mode, and assert that all values are + // passed. Quit after it's done. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThreadNonblocking', + maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: binding.typed_threadsafe_function.ARRAY_LENGTH + }), + expectedArray + ); + + // Start the thread in blocking mode, and assert that all values are passed. + // Quit early, but let the thread finish. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThread', + maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: 1 + }), + expectedArray + ); + + // Start the thread in blocking mode with an infinite queue, and assert that + // all values are passed. Quit early, but let the thread finish. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThread', + maxQueueSize: 0, + quitAfter: 1 + }), + expectedArray + ); + + // Start the thread in non-blocking mode, and assert that all values are + // passed. Quit early, but let the thread finish. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThreadNonblocking', + maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, + quitAfter: 1 + }), + expectedArray + ); + + // Start the thread in blocking mode, and assert that all values are passed. + // Quit early, but let the thread finish. Launch a secondary thread to test + // the reference counter incrementing functionality. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThread', + quitAfter: 1, + maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, + launchSecondary: true + }), + expectedArray + ); + + // Start the thread in non-blocking mode, and assert that all values are + // passed. Quit early, but let the thread finish. Launch a secondary thread + // to test the reference counter incrementing functionality. + assert.deepStrictEqual( + await testWithJSMarshaller({ + threadStarter: 'startThreadNonblocking', + quitAfter: 1, + maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, + launchSecondary: true + }), + expectedArray + ); + + // Start the thread in blocking mode, and assert that it could not finish. + // Quit early by aborting. + assert.strictEqual( + (await testWithJSMarshaller({ + threadStarter: 'startThread', + quitAfter: 1, + maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, + abort: true + })).indexOf(0), + -1 + ); + + // Start the thread in blocking mode with an infinite queue, and assert that + // it could not finish. Quit early by aborting. + assert.strictEqual( + (await testWithJSMarshaller({ + threadStarter: 'startThread', + quitAfter: 1, + maxQueueSize: 0, + abort: true + })).indexOf(0), + -1 + ); + + // Start the thread in non-blocking mode, and assert that it could not finish. + // Quit early and aborting. + assert.strictEqual( + (await testWithJSMarshaller({ + threadStarter: 'startThreadNonblocking', + quitAfter: 1, + maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, + abort: true + })).indexOf(0), + -1 + ); +} diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ctx.cc b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ctx.cc new file mode 100644 index 0000000..7cf2209 --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ctx.cc @@ -0,0 +1,120 @@ +#include +#include "napi.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +using ContextType = Reference; +using TSFN = TypedThreadSafeFunction; + +namespace { + +class TSFNWrap : public ObjectWrap { + public: + static Function Init(Napi::Env env); + TSFNWrap(const CallbackInfo& info); + + Napi::Value GetContext(const CallbackInfo& /*info*/) { + ContextType* ctx = _tsfn.GetContext(); + return ctx->Value(); + }; + + Napi::Value Release(const CallbackInfo& info) { + Napi::Env env = info.Env(); + _deferred = std::unique_ptr(new Promise::Deferred(env)); + _tsfn.Release(); + return _deferred->Promise(); + }; + + private: + TSFN _tsfn; + std::unique_ptr _deferred; +}; + +Function TSFNWrap::Init(Napi::Env env) { + Function func = + DefineClass(env, + "TSFNWrap", + {InstanceMethod("getContext", &TSFNWrap::GetContext), + InstanceMethod("release", &TSFNWrap::Release)}); + + return func; +} + +TSFNWrap::TSFNWrap(const CallbackInfo& info) : ObjectWrap(info) { + ContextType* _ctx = new ContextType; + *_ctx = Persistent(info[0]); + + _tsfn = TSFN::New(info.Env(), + this->Value(), + "Test", + 1, + 1, + _ctx, + [this](Napi::Env env, void*, ContextType* ctx) { + _deferred->Resolve(env.Undefined()); + ctx->Reset(); + delete ctx; + }); +} + +} // namespace + +struct SimpleTestContext { + SimpleTestContext(int val) : _val(val) {} + int _val = -1; +}; + +// A simple test to check that the context has been set successfully +void AssertGetContextFromTSFNNoFinalizerIsCorrect(const CallbackInfo& info) { + // Test the overload where we provide a resource name but no finalizer + using TSFN = TypedThreadSafeFunction; + SimpleTestContext* ctx = new SimpleTestContext(42); + TSFN tsfn = TSFN::New(info.Env(), "testRes", 1, 1, ctx); + + assert(tsfn.GetContext() == ctx); + delete ctx; + tsfn.Release(); + + // Test the other overload where we provide a async resource object, res name + // but no finalizer + ctx = new SimpleTestContext(52); + tsfn = TSFN::New( + info.Env(), Object::New(info.Env()), "testResourceObject", 1, 1, ctx); + + assert(tsfn.GetContext() == ctx); + delete ctx; + tsfn.Release(); + + ctx = new SimpleTestContext(52); + tsfn = TSFN::New(info.Env(), + "resStrings", + 1, + 1, + ctx, + [](Napi::Env, void*, SimpleTestContext*) {}); + + assert(tsfn.GetContext() == ctx); + delete ctx; + tsfn.Release(); + + ctx = new SimpleTestContext(52); + Function emptyFunc; + tsfn = TSFN::New(info.Env(), emptyFunc, "resString", 1, 1, ctx); + assert(tsfn.GetContext() == ctx); + delete ctx; + tsfn.Release(); +} + +Object InitTypedThreadSafeFunctionCtx(Env env) { + Object exports = Object::New(env); + Function tsfnWrap = TSFNWrap::Init(env); + + exports.Set("TSFNWrap", tsfnWrap); + exports.Set("AssertTSFNReturnCorrectCxt", + Function::New(env, AssertGetContextFromTSFNNoFinalizerIsCorrect)); + return exports; +} + +#endif diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ctx.js b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ctx.js new file mode 100644 index 0000000..ddbddcc --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ctx.js @@ -0,0 +1,14 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +async function test (binding) { + const ctx = { }; + const tsfn = new binding.typed_threadsafe_function_ctx.TSFNWrap(ctx); + assert(tsfn.getContext() === ctx); + await tsfn.release(); + + binding.typed_threadsafe_function_ctx.AssertTSFNReturnCorrectCxt(); +} diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_exception.cc b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_exception.cc new file mode 100644 index 0000000..c55ca23 --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_exception.cc @@ -0,0 +1,39 @@ +#include +#include "napi.h" +#include "test_helper.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +void CallJS(Napi::Env env, + Napi::Function /* callback */, + std::nullptr_t* /* context */, + void* /*data*/) { + Napi::Error error = Napi::Error::New(env, "test-from-native"); + NAPI_THROW_VOID(error); +} + +using TSFN = TypedThreadSafeFunction; + +void TestCall(const CallbackInfo& info) { + Napi::Env env = info.Env(); + + TSFN wrapped = TSFN::New( + env, Napi::Function(), Object::New(env), String::New(env, "Test"), 0, 1); + wrapped.BlockingCall(static_cast(nullptr)); + wrapped.Release(); +} + +} // namespace + +Object InitTypedThreadSafeFunctionException(Env env) { + Object exports = Object::New(env); + exports["testCall"] = Function::New(env, TestCall); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_exception.js b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_exception.js new file mode 100644 index 0000000..60ff673 --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_exception.js @@ -0,0 +1,13 @@ +'use strict'; + +const common = require('../common'); + +module.exports = common.runTest(test); + +async function test () { + await common.runTestInChildProcess({ + suite: 'typed_threadsafe_function_exception', + testName: 'testCall', + execArgv: ['--force-node-api-uncaught-exceptions-policy=true'] + }); +} diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.cc b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.cc new file mode 100644 index 0000000..daa273f --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.cc @@ -0,0 +1,127 @@ +#include +#include "napi.h" +#include "test_helper.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +struct TestContext { + TestContext(Promise::Deferred&& deferred) + : deferred(std::move(deferred)), callData(nullptr){}; + + napi_threadsafe_function tsfn; + Promise::Deferred deferred; + double* callData; + + ~TestContext() { + if (callData != nullptr) delete callData; + }; +}; + +using TSFN = TypedThreadSafeFunction; + +void FinalizeCB(napi_env env, void* /*finalizeData */, void* context) { + TestContext* testContext = static_cast(context); + if (testContext->callData != nullptr) { + testContext->deferred.Resolve(Number::New(env, *testContext->callData)); + } else { + testContext->deferred.Resolve(Napi::Env(env).Undefined()); + } + delete testContext; +} + +void CallJSWithData(napi_env env, + napi_value /* callback */, + void* context, + void* data) { + TestContext* testContext = static_cast(context); + testContext->callData = static_cast(data); + + napi_status status = + napi_release_threadsafe_function(testContext->tsfn, napi_tsfn_release); + + NAPI_THROW_IF_FAILED_VOID(env, status); +} + +void CallJSNoData(napi_env env, + napi_value /* callback */, + void* context, + void* /*data*/) { + TestContext* testContext = static_cast(context); + testContext->callData = nullptr; + + napi_status status = + napi_release_threadsafe_function(testContext->tsfn, napi_tsfn_release); + + NAPI_THROW_IF_FAILED_VOID(env, status); +} + +static Value TestCall(const CallbackInfo& info) { + Napi::Env env = info.Env(); + bool isBlocking = false; + bool hasData = false; + if (info.Length() > 0) { + Object opts = info[0].As(); + bool hasProperty = MaybeUnwrap(opts.Has("blocking")); + if (hasProperty) { + isBlocking = MaybeUnwrap(MaybeUnwrap(opts.Get("blocking")).ToBoolean()); + } + hasProperty = MaybeUnwrap(opts.Has("data")); + if (hasProperty) { + hasData = MaybeUnwrap(MaybeUnwrap(opts.Get("data")).ToBoolean()); + } + } + + // Allow optional callback passed from JS. Useful for testing. + Function cb = Function::New(env, [](const CallbackInfo& /*info*/) {}); + + TestContext* testContext = new TestContext(Napi::Promise::Deferred(env)); + + napi_status status = + napi_create_threadsafe_function(env, + cb, + Object::New(env), + String::New(env, "Test"), + 0, + 1, + nullptr, /*finalize data*/ + FinalizeCB, + testContext, + hasData ? CallJSWithData : CallJSNoData, + &testContext->tsfn); + + NAPI_THROW_IF_FAILED(env, status, Value()); + + TSFN wrapped = TSFN(testContext->tsfn); + + // Test the four napi_threadsafe_function direct-accessing calls + if (isBlocking) { + if (hasData) { + wrapped.BlockingCall(new double(std::rand())); + } else { + wrapped.BlockingCall(nullptr); + } + } else { + if (hasData) { + wrapped.NonBlockingCall(new double(std::rand())); + } else { + wrapped.NonBlockingCall(nullptr); + } + } + + return testContext->deferred.Promise(); +} + +} // namespace + +Object InitTypedThreadSafeFunctionExistingTsfn(Env env) { + Object exports = Object::New(env); + exports["testCall"] = Function::New(env, TestCall); + + return exports; +} + +#endif diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.js b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.js new file mode 100644 index 0000000..17185a8 --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.js @@ -0,0 +1,14 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('../common').runTest(test); + +async function test (binding) { + const testCall = binding.typed_threadsafe_function_existing_tsfn.testCall; + + assert.strictEqual(typeof await testCall({ blocking: true, data: true }), 'number'); + assert.strictEqual(typeof await testCall({ blocking: true, data: false }), 'undefined'); + assert.strictEqual(typeof await testCall({ blocking: false, data: true }), 'number'); + assert.strictEqual(typeof await testCall({ blocking: false, data: false }), 'undefined'); +} diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ptr.cc b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ptr.cc new file mode 100644 index 0000000..a4da743 --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ptr.cc @@ -0,0 +1,32 @@ +#include "napi.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +using TSFN = TypedThreadSafeFunction<>; + +static Value Test(const CallbackInfo& info) { + Object resource = info[0].As(); + Function cb = info[1].As(); + TSFN tsfn = TSFN::New(info.Env(), cb, resource, "Test", 1, 1); + tsfn.Release(); + return info.Env().Undefined(); +} + +static Value ExtractEnvNullValue(const CallbackInfo& info) { + return info.Env().Null(); +} + +} // namespace + +Object InitTypedThreadSafeFunctionPtr(Env env) { + Object exports = Object::New(env); + exports["test"] = Function::New(env, Test); + exports["null"] = Function::New(env, ExtractEnvNullValue); + return exports; +} + +#endif diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ptr.js b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ptr.js new file mode 100644 index 0000000..e919217 --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_ptr.js @@ -0,0 +1,8 @@ +'use strict'; +const assert = require('assert'); +module.exports = require('../common').runTest(test); + +function test (binding) { + assert(binding.typed_threadsafe_function_ptr.test({}, () => {}) === undefined); + assert(binding.typed_threadsafe_function_ptr.null() === null); +} diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_sum.cc b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_sum.cc new file mode 100644 index 0000000..b36ab28 --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_sum.cc @@ -0,0 +1,237 @@ +#include +#include +#include +#include +#include "napi.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +struct TestData { + TestData(Promise::Deferred&& deferred) : deferred(std::move(deferred)){}; + + // Native Promise returned to JavaScript + Promise::Deferred deferred; + + // List of threads created for test. This list only ever accessed via main + // thread. + std::vector threads = {}; + + // These variables are only accessed from the main thread. + bool mainWantsRelease = false; + size_t expected_calls = 0; + + static void CallJs(Napi::Env env, + Function callback, + TestData* testData, + double* data) { + // This lambda runs on the main thread so it's OK to access the variables + // `expected_calls` and `mainWantsRelease`. + testData->expected_calls--; + if (testData->expected_calls == 0 && testData->mainWantsRelease) + testData->tsfn.Release(); + callback.Call({Number::New(env, *data)}); + delete data; + } + + TypedThreadSafeFunction tsfn; +}; + +using TSFN = TypedThreadSafeFunction; + +void FinalizerCallback(Napi::Env env, void*, TestData* finalizeData) { + for (size_t i = 0; i < finalizeData->threads.size(); ++i) { + finalizeData->threads[i].join(); + } + finalizeData->deferred.Resolve(Boolean::New(env, true)); + delete finalizeData; +} + +/** + * See threadsafe_function_sum.js for descriptions of the tests in this file + */ + +void entryWithTSFN(TSFN tsfn, int threadId) { + std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 100 + 1)); + tsfn.BlockingCall(new double(threadId)); + tsfn.Release(); +} + +static Value TestWithTSFN(const CallbackInfo& info) { + int threadCount = info[0].As().Int32Value(); + Function cb = info[1].As(); + + // We pass the test data to the Finalizer for cleanup. The finalizer is + // responsible for deleting this data as well. + TestData* testData = new TestData(Promise::Deferred::New(info.Env())); + + TSFN tsfn = + TSFN::New(info.Env(), + cb, + "Test", + 0, + threadCount, + testData, + std::function(FinalizerCallback), + testData); + + for (int i = 0; i < threadCount; ++i) { + // A copy of the ThreadSafeFunction will go to the thread entry point + testData->threads.push_back(std::thread(entryWithTSFN, tsfn, i)); + } + + return testData->deferred.Promise(); +} + +// Task instance created for each new std::thread +class DelayedTSFNTask { + public: + // Each instance has its own tsfn + TSFN tsfn; + + // Thread-safety + std::mutex mtx; + std::condition_variable cv; + + // Entry point for std::thread + void entryDelayedTSFN(int threadId) { + std::unique_lock lk(mtx); + cv.wait(lk, [this] { return this->tsfn != nullptr; }); + tsfn.BlockingCall(new double(threadId)); + tsfn.Release(); + }; +}; + +struct TestDataDelayed : TestData { + TestDataDelayed(Promise::Deferred&& deferred) + : TestData(std::move(deferred)){}; + ~TestDataDelayed() { taskInsts.clear(); }; + + // List of DelayedTSFNThread instances + std::vector> taskInsts = {}; +}; + +void FinalizerCallbackDelayed(Napi::Env env, + TestDataDelayed* finalizeData, + TestData*) { + for (size_t i = 0; i < finalizeData->threads.size(); ++i) { + finalizeData->threads[i].join(); + } + finalizeData->deferred.Resolve(Boolean::New(env, true)); + delete finalizeData; +} + +static Value TestDelayedTSFN(const CallbackInfo& info) { + int threadCount = info[0].As().Int32Value(); + Function cb = info[1].As(); + + TestDataDelayed* testData = + new TestDataDelayed(Promise::Deferred::New(info.Env())); + + testData->tsfn = TSFN::New(info.Env(), + cb, + "Test", + 0, + threadCount, + testData, + std::function( + FinalizerCallbackDelayed), + testData); + + for (int i = 0; i < threadCount; ++i) { + testData->taskInsts.push_back( + std::unique_ptr(new DelayedTSFNTask())); + testData->threads.push_back(std::thread(&DelayedTSFNTask::entryDelayedTSFN, + testData->taskInsts.back().get(), + i)); + } + std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 100 + 1)); + + for (auto& task : testData->taskInsts) { + std::lock_guard lk(task->mtx); + task->tsfn = testData->tsfn; + task->cv.notify_all(); + } + + return testData->deferred.Promise(); +} + +void AcquireFinalizerCallback(Napi::Env env, + TestData* finalizeData, + TestData* context) { + (void)context; + for (size_t i = 0; i < finalizeData->threads.size(); ++i) { + finalizeData->threads[i].join(); + } + finalizeData->deferred.Resolve(Boolean::New(env, true)); + delete finalizeData; +} + +void entryAcquire(TSFN tsfn, int threadId) { + tsfn.Acquire(); + std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 100 + 1)); + tsfn.BlockingCall(new double(threadId)); + tsfn.Release(); +} + +static Value CreateThread(const CallbackInfo& info) { + TestData* testData = static_cast(info.Data()); + // Counting expected calls like this only works because on the JS side this + // binding is called from a synchronous loop. This means the main loop has no + // chance to run the tsfn JS callback before we've counted how many threads + // the JS intends to create. + testData->expected_calls++; + TSFN tsfn = testData->tsfn; + int threadId = testData->threads.size(); + // A copy of the ThreadSafeFunction will go to the thread entry point + testData->threads.push_back(std::thread(entryAcquire, tsfn, threadId)); + return Number::New(info.Env(), threadId); +} + +static Value StopThreads(const CallbackInfo& info) { + TestData* testData = static_cast(info.Data()); + testData->mainWantsRelease = true; + return info.Env().Undefined(); +} + +static Value TestAcquire(const CallbackInfo& info) { + Function cb = info[0].As(); + Napi::Env env = info.Env(); + + // We pass the test data to the Finalizer for cleanup. The finalizer is + // responsible for deleting this data as well. + TestData* testData = new TestData(Promise::Deferred::New(info.Env())); + + testData->tsfn = TSFN::New(env, + cb, + "Test", + 0, + 1, + testData, + std::function( + AcquireFinalizerCallback), + testData); + + Object result = Object::New(env); + result["createThread"] = + Function::New(env, CreateThread, "createThread", testData); + result["stopThreads"] = + Function::New(env, StopThreads, "stopThreads", testData); + result["promise"] = testData->deferred.Promise(); + + return result; +} +} // namespace + +Object InitTypedThreadSafeFunctionSum(Env env) { + Object exports = Object::New(env); + exports["testDelayedTSFN"] = Function::New(env, TestDelayedTSFN); + exports["testWithTSFN"] = Function::New(env, TestWithTSFN); + exports["testAcquire"] = Function::New(env, TestAcquire); + return exports; +} + +#endif diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_sum.js b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_sum.js new file mode 100644 index 0000000..0a59bba --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_sum.js @@ -0,0 +1,59 @@ +'use strict'; +const assert = require('assert'); + +/** + * + * ThreadSafeFunction Tests: Thread Id Sums + * + * Every native C++ function that utilizes the TSFN will call the registered + * callback with the thread id. Passing Array.prototype.push with a bound array + * will push the thread id to the array. Therefore, starting `N` threads, we + * will expect the sum of all elements in the array to be `(N-1) * (N) / 2` (as + * thread IDs are 0-based) + * + * We check different methods of passing a ThreadSafeFunction around multiple + * threads: + * - `testWithTSFN`: The main thread creates the TSFN. Then, it creates + * threads, passing the TSFN at thread construction. The number of threads is + * static (known at TSFN creation). + * - `testDelayedTSFN`: The main thread creates threads, passing a promise to a + * TSFN at construction. Then, it creates the TSFN, and resolves each + * threads' promise. The number of threads is static. + * - `testAcquire`: The native binding returns a function to start a new. A + * call to this function will return `false` once `N` calls have been made. + * Each thread will acquire its own use of the TSFN, call it, and then + * release. + */ + +const THREAD_COUNT = 5; +const EXPECTED_SUM = (THREAD_COUNT - 1) * (THREAD_COUNT) / 2; + +module.exports = require('../common').runTest(test); + +/** @param {number[]} N */ +const sum = (N) => N.reduce((sum, n) => sum + n, 0); + +function test (binding) { + async function check (bindingFunction) { + const calls = []; + const result = await bindingFunction(THREAD_COUNT, Array.prototype.push.bind(calls)); + assert.ok(result); + assert.equal(sum(calls), EXPECTED_SUM); + } + + async function checkAcquire () { + const calls = []; + const { promise, createThread, stopThreads } = binding.typed_threadsafe_function_sum.testAcquire(Array.prototype.push.bind(calls)); + for (let i = 0; i < THREAD_COUNT; i++) { + createThread(); + } + stopThreads(); + const result = await promise; + assert.ok(result); + assert.equal(sum(calls), EXPECTED_SUM); + } + + return check(binding.typed_threadsafe_function_sum.testDelayedTSFN) + .then(() => check(binding.typed_threadsafe_function_sum.testWithTSFN)) + .then(() => checkAcquire()); +} diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_unref.cc b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_unref.cc new file mode 100644 index 0000000..b6588e2 --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_unref.cc @@ -0,0 +1,67 @@ +#include "napi.h" +#include "test_helper.h" + +#if (NAPI_VERSION > 3) + +using namespace Napi; + +namespace { + +using TSFN = TypedThreadSafeFunction<>; +using ContextType = std::nullptr_t; +using FinalizerDataType = void; +static Value TestUnref(const CallbackInfo& info) { + Napi::Env env = info.Env(); + Object global = env.Global(); + Object resource = info[0].As(); + Function cb = info[1].As(); + Function setTimeout = MaybeUnwrap(global.Get("setTimeout")).As(); + TSFN* tsfn = new TSFN; + + *tsfn = TSFN::New( + info.Env(), + cb, + resource, + "Test", + 1, + 1, + nullptr, + [tsfn](Napi::Env /* env */, FinalizerDataType*, ContextType*) { + delete tsfn; + }, + static_cast(nullptr)); + + tsfn->BlockingCall(); + tsfn->Ref(info.Env()); + + setTimeout.Call( + global, + {Function::New( + env, [tsfn](const CallbackInfo& info) { tsfn->Unref(info.Env()); }), + Number::New(env, 100)}); + + return info.Env().Undefined(); +} + +static Value TestRef(const CallbackInfo& info) { + Function cb = info[1].As(); + + auto tsfn = TSFN::New(info.Env(), cb, "testRes", 1, 1, nullptr); + + tsfn.BlockingCall(); + tsfn.Unref(info.Env()); + tsfn.Ref(info.Env()); + + return info.Env().Undefined(); +} + +} // namespace + +Object InitTypedThreadSafeFunctionUnref(Env env) { + Object exports = Object::New(env); + exports["testUnref"] = Function::New(env, TestUnref); + exports["testRef"] = Function::New(env, TestRef); + return exports; +} + +#endif diff --git a/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_unref.js b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_unref.js new file mode 100644 index 0000000..88bf7d3 --- /dev/null +++ b/test/node-addon-api/test/typed_threadsafe_function/typed_threadsafe_function_unref.js @@ -0,0 +1,98 @@ +'use strict'; + +const assert = require('assert'); + +const isMainProcess = process.argv[1] !== __filename; + +/** + * In order to test that the event loop exits even with an active TSFN, we need + * to spawn a new process for the test. + * - Main process: spawns new node instance, executing this script + * - Child process: creates TSFN. Native module Unref's via setTimeout after some time but does NOT call Release. + * + * Main process should expect child process to exit. + * + * We also added a new test case for `Ref`. The idea being, if a TSFN is active, the event loop that it belongs to should not exit + * Our setup is similar to the test for the `Unref` case, with the difference being now we are expecting the child process to hang + */ + +if (isMainProcess) { + module.exports = require('../common').runTestWithBindingPath(test); +} else { + const isTestingRef = (process.argv[3] === 'true'); + + if (isTestingRef) { + execTSFNRefTest(process.argv[2]); + } else { + execTSFNUnrefTest(process.argv[2]); + } +} + +function testUnRefCallback (resolve, reject, bindingFile) { + const child = require('../napi_child').spawn(process.argv[0], [ + '--expose-gc', __filename, bindingFile, false + ], { stdio: 'inherit' }); + + let timeout = setTimeout(function () { + child.kill(); + timeout = 0; + reject(new Error('Expected child to die')); + }, 5000); + + child.on('error', (err) => { + clearTimeout(timeout); + timeout = 0; + reject(new Error(err)); + }); + + child.on('close', (code) => { + if (timeout) clearTimeout(timeout); + assert.strictEqual(code, 0, 'Expected return value 0'); + resolve(); + }); +} + +function testRefCallback (resolve, reject, bindingFile) { + const child = require('../napi_child').spawn(process.argv[0], [ + '--expose-gc', __filename, bindingFile, true + ], { stdio: 'inherit' }); + + let timeout = setTimeout(function () { + child.kill(); + timeout = 0; + resolve(); + }, 1000); + + child.on('error', (err) => { + clearTimeout(timeout); + timeout = 0; + reject(new Error(err)); + }); + + child.on('close', (code) => { + if (timeout) clearTimeout(timeout); + + reject(new Error('We expected Child to hang')); + }); +} + +function test (bindingFile) { + // Main process + return new Promise((resolve, reject) => { + testUnRefCallback(resolve, reject, bindingFile); + }).then(() => { + return new Promise((resolve, reject) => { + testRefCallback(resolve, reject, bindingFile); + }); + }); +} + +function execTSFNUnrefTest (bindingFile) { + const binding = require(bindingFile); + binding.typed_threadsafe_function_unref.testUnref({}, () => { }); +} + +function execTSFNRefTest (bindingFile) { + const binding = require(bindingFile); + binding.typed_threadsafe_function_unref.testRef({}, () => { }); +} diff --git a/test/node-addon-api/test/typedarray-bigint.js b/test/node-addon-api/test/typedarray-bigint.js new file mode 100644 index 0000000..1c31745 --- /dev/null +++ b/test/node-addon-api/test/typedarray-bigint.js @@ -0,0 +1,58 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +function test (binding) { + [ + ['bigint64', BigInt64Array], + ['biguint64', BigUint64Array] + ].forEach(([type, Constructor]) => { + try { + const length = 4; + const t = binding.typedarray.createTypedArray(type, length); + assert.ok(t instanceof Constructor); + assert.strictEqual(binding.typedarray.getTypedArrayType(t), type); + assert.strictEqual(binding.typedarray.getTypedArrayLength(t), length); + + t[3] = 11n; + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 11n); + binding.typedarray.setTypedArrayElement(t, 3, 22n); + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 22n); + assert.strictEqual(t[3], 22n); + + const b = binding.typedarray.getTypedArrayBuffer(t); + assert.ok(b instanceof ArrayBuffer); + } catch (e) { + console.log(type, Constructor); + throw e; + } + + try { + const length = 4; + const offset = 8; + const b = new ArrayBuffer(offset + 64 * 4); + + const t = binding.typedarray.createTypedArray(type, length, b, offset); + assert.ok(t instanceof Constructor); + assert.strictEqual(binding.typedarray.getTypedArrayType(t), type); + assert.strictEqual(binding.typedarray.getTypedArrayLength(t), length); + + t[3] = 11n; + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 11n); + binding.typedarray.setTypedArrayElement(t, 3, 22n); + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 22n); + assert.strictEqual(t[3], 22n); + + assert.strictEqual(binding.typedarray.getTypedArrayBuffer(t), b); + } catch (e) { + console.log(type, Constructor); + throw e; + } + }); + + assert.throws(() => { + binding.typedarray.createInvalidTypedArray(); + }, /Invalid (pointer passed as )?argument/); +} diff --git a/test/node-addon-api/test/typedarray.cc b/test/node-addon-api/test/typedarray.cc new file mode 100644 index 0000000..795f281 --- /dev/null +++ b/test/node-addon-api/test/typedarray.cc @@ -0,0 +1,438 @@ +#include +#include "napi.h" +using namespace Napi; + +#if defined(NAPI_HAS_CONSTEXPR) +#define NAPI_TYPEDARRAY_NEW(className, env, length, type) \ + className::New(env, length) +#define NAPI_TYPEDARRAY_NEW_BUFFER( \ + className, env, length, buffer, bufferOffset, type) \ + className::New(env, length, buffer, bufferOffset) +#else +#define NAPI_TYPEDARRAY_NEW(className, env, length, type) \ + className::New(env, length, type) +#define NAPI_TYPEDARRAY_NEW_BUFFER( \ + className, env, length, buffer, bufferOffset, type) \ + className::New(env, length, buffer, bufferOffset, type) +#endif + +namespace { + +Value CreateTypedArray(const CallbackInfo& info) { + std::string arrayType = info[0].As(); + size_t length = info[1].As().Uint32Value(); + Value buffer = info[2]; + size_t bufferOffset = + info[3].IsUndefined() ? 0 : info[3].As().Uint32Value(); + + if (arrayType == "int8") { + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Int8Array, info.Env(), length, napi_int8_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Int8Array, + info.Env(), + length, + buffer.As(), + bufferOffset, + napi_int8_array); + } else if (arrayType == "uint8") { + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Uint8Array, info.Env(), length, napi_uint8_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Uint8Array, + info.Env(), + length, + buffer.As(), + bufferOffset, + napi_uint8_array); + } else if (arrayType == "uint8_clamped") { + return buffer.IsUndefined() + ? Uint8Array::New(info.Env(), length, napi_uint8_clamped_array) + : Uint8Array::New(info.Env(), + length, + buffer.As(), + bufferOffset, + napi_uint8_clamped_array); + } else if (arrayType == "int16") { + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Int16Array, info.Env(), length, napi_int16_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Int16Array, + info.Env(), + length, + buffer.As(), + bufferOffset, + napi_int16_array); + } else if (arrayType == "uint16") { + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Uint16Array, info.Env(), length, napi_uint16_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Uint16Array, + info.Env(), + length, + buffer.As(), + bufferOffset, + napi_uint16_array); + } else if (arrayType == "int32") { + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Int32Array, info.Env(), length, napi_int32_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Int32Array, + info.Env(), + length, + buffer.As(), + bufferOffset, + napi_int32_array); + } else if (arrayType == "uint32") { + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Uint32Array, info.Env(), length, napi_uint32_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Uint32Array, + info.Env(), + length, + buffer.As(), + bufferOffset, + napi_uint32_array); + } else if (arrayType == "float32") { + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Float32Array, info.Env(), length, napi_float32_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Float32Array, + info.Env(), + length, + buffer.As(), + bufferOffset, + napi_float32_array); + } else if (arrayType == "float64") { + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Float64Array, info.Env(), length, napi_float64_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Float64Array, + info.Env(), + length, + buffer.As(), + bufferOffset, + napi_float64_array); +#if (NAPI_VERSION > 5) + } else if (arrayType == "bigint64") { + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + BigInt64Array, info.Env(), length, napi_bigint64_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(BigInt64Array, + info.Env(), + length, + buffer.As(), + bufferOffset, + napi_bigint64_array); + } else if (arrayType == "biguint64") { + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + BigUint64Array, info.Env(), length, napi_biguint64_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(BigUint64Array, + info.Env(), + length, + buffer.As(), + bufferOffset, + napi_biguint64_array); +#endif + } else { + Error::New(info.Env(), "Invalid typed-array type.") + .ThrowAsJavaScriptException(); + return Value(); + } +} + +Value CreateInvalidTypedArray(const CallbackInfo& info) { + return NAPI_TYPEDARRAY_NEW_BUFFER( + Int8Array, info.Env(), 1, ArrayBuffer(), 0, napi_int8_array); +} + +Value GetTypedArrayType(const CallbackInfo& info) { + TypedArray array = info[0].As(); + switch (array.TypedArrayType()) { + case napi_int8_array: + return String::New(info.Env(), "int8"); + case napi_uint8_array: + return String::New(info.Env(), "uint8"); + case napi_uint8_clamped_array: + return String::New(info.Env(), "uint8_clamped"); + case napi_int16_array: + return String::New(info.Env(), "int16"); + case napi_uint16_array: + return String::New(info.Env(), "uint16"); + case napi_int32_array: + return String::New(info.Env(), "int32"); + case napi_uint32_array: + return String::New(info.Env(), "uint32"); + case napi_float32_array: + return String::New(info.Env(), "float32"); + case napi_float64_array: + return String::New(info.Env(), "float64"); +#if (NAPI_VERSION > 5) + case napi_bigint64_array: + return String::New(info.Env(), "bigint64"); + case napi_biguint64_array: + return String::New(info.Env(), "biguint64"); +#endif + default: + return String::New(info.Env(), "invalid"); + } +} + +template +bool TypedArrayDataIsEquivalent(TypedArrayOf arr, + TypedArrayOf inputArr) { + if (arr.ElementLength() != inputArr.ElementLength()) { + return false; + } + std::vector bufferContent(arr.Data(), arr.Data() + arr.ElementLength()); + std::vector inputContent(inputArr.Data(), + inputArr.Data() + inputArr.ElementLength()); + if (bufferContent != inputContent) { + return false; + } + return true; +} + +Value CheckBufferContent(const CallbackInfo& info) { + TypedArray array = info[0].As(); + + switch (array.TypedArrayType()) { + case napi_int8_array: + return Boolean::New( + info.Env(), + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); + + break; + case napi_uint8_array: + return Boolean::New( + info.Env(), + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); + + case napi_uint8_clamped_array: + return Boolean::New( + info.Env(), + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); + + case napi_int16_array: + return Boolean::New( + info.Env(), + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); + + case napi_uint16_array: + return Boolean::New( + info.Env(), + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); + + case napi_int32_array: + return Boolean::New( + info.Env(), + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); + + case napi_uint32_array: + return Boolean::New( + info.Env(), + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); + + case napi_float32_array: + return Boolean::New( + info.Env(), + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); + + case napi_float64_array: + return Boolean::New( + info.Env(), + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); + +#if (NAPI_VERSION > 5) + case napi_bigint64_array: + return Boolean::New( + info.Env(), + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); + + case napi_biguint64_array: + return Boolean::New( + info.Env(), + TypedArrayDataIsEquivalent(info[0].As(), + info[1].As())); + +#endif + default: + return Boolean::New(info.Env(), false); + } +} + +Value GetTypedArrayLength(const CallbackInfo& info) { + TypedArray array = info[0].As(); + return Number::New(info.Env(), static_cast(array.ElementLength())); +} + +Value GetTypedArraySize(const CallbackInfo& info) { + TypedArray array = info[0].As(); + return Number::New(info.Env(), static_cast(array.ElementSize())); +} + +Value GetTypedArrayByteOffset(const CallbackInfo& info) { + TypedArray array = info[0].As(); + return Number::New(info.Env(), static_cast(array.ByteOffset())); +} + +Value GetTypedArrayByteLength(const CallbackInfo& info) { + TypedArray array = info[0].As(); + return Number::New(info.Env(), static_cast(array.ByteLength())); +} + +Value GetTypedArrayBuffer(const CallbackInfo& info) { + TypedArray array = info[0].As(); + return array.ArrayBuffer(); +} + +Value GetTypedArrayBufferValue(const CallbackInfo& info) { + TypedArray array = info[0].As(); + return array.Buffer(); +} + +Value GetTypedArrayElement(const CallbackInfo& info) { + TypedArray array = info[0].As(); + size_t index = info[1].As().Uint32Value(); + switch (array.TypedArrayType()) { + case napi_int8_array: + return Number::New(info.Env(), array.As()[index]); + case napi_uint8_array: + return Number::New(info.Env(), array.As()[index]); + case napi_uint8_clamped_array: + return Number::New(info.Env(), array.As()[index]); + case napi_int16_array: + return Number::New(info.Env(), array.As()[index]); + case napi_uint16_array: + return Number::New(info.Env(), array.As()[index]); + case napi_int32_array: + return Number::New(info.Env(), array.As()[index]); + case napi_uint32_array: + return Number::New(info.Env(), array.As()[index]); + case napi_float32_array: + return Number::New(info.Env(), array.As()[index]); + case napi_float64_array: + return Number::New(info.Env(), array.As()[index]); +#if (NAPI_VERSION > 5) + case napi_bigint64_array: + return BigInt::New(info.Env(), array.As()[index]); + case napi_biguint64_array: + return BigInt::New(info.Env(), array.As()[index]); +#endif + default: + Error::New(info.Env(), "Invalid typed-array type.") + .ThrowAsJavaScriptException(); + return Value(); + } +} + +void SetTypedArrayElement(const CallbackInfo& info) { + TypedArray array = info[0].As(); + size_t index = info[1].As().Uint32Value(); + Value value = info[2]; + switch (array.TypedArrayType()) { + case napi_int8_array: + array.As()[index] = + static_cast(value.As().Int32Value()); + break; + case napi_uint8_array: + array.As()[index] = + static_cast(value.As().Uint32Value()); + break; + case napi_uint8_clamped_array: + array.As()[index] = + static_cast(value.As().Uint32Value()); + break; + case napi_int16_array: + array.As()[index] = + static_cast(value.As().Int32Value()); + break; + case napi_uint16_array: + array.As()[index] = + static_cast(value.As().Uint32Value()); + break; + case napi_int32_array: + array.As()[index] = value.As().Int32Value(); + break; + case napi_uint32_array: + array.As()[index] = value.As().Uint32Value(); + break; + case napi_float32_array: + array.As()[index] = value.As().FloatValue(); + break; + case napi_float64_array: + array.As()[index] = value.As().DoubleValue(); + break; +#if (NAPI_VERSION > 5) + case napi_bigint64_array: { + bool lossless; + array.As()[index] = + value.As().Int64Value(&lossless); + break; + } + case napi_biguint64_array: { + bool lossless; + array.As()[index] = + value.As().Uint64Value(&lossless); + break; + } +#endif + default: + Error::New(info.Env(), "Invalid typed-array type.") + .ThrowAsJavaScriptException(); + } +} + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +Value CreateInt8TypedArrayFromSharedArrayBuffer(const CallbackInfo& info) { + auto buffer = info[0].As(); + size_t length = buffer.ByteLength(); + + return NAPI_TYPEDARRAY_NEW_BUFFER(Int8Array, + info.Env(), + length, + buffer.As(), + 0, + napi_int8_array); +} +#endif + +} // end anonymous namespace + +Object InitTypedArray(Env env) { + Object exports = Object::New(env); + + exports["createTypedArray"] = Function::New(env, CreateTypedArray); +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + exports["createInt8TypedArrayFromSharedArrayBuffer"] = + Function::New(env, CreateInt8TypedArrayFromSharedArrayBuffer); +#endif + exports["createInvalidTypedArray"] = + Function::New(env, CreateInvalidTypedArray); + exports["getTypedArrayType"] = Function::New(env, GetTypedArrayType); + exports["getTypedArrayLength"] = Function::New(env, GetTypedArrayLength); + exports["getTypedArraySize"] = Function::New(env, GetTypedArraySize); + exports["getTypedArrayByteOffset"] = + Function::New(env, GetTypedArrayByteOffset); + exports["getTypedArrayByteLength"] = + Function::New(env, GetTypedArrayByteLength); + exports["getTypedArrayBuffer"] = Function::New(env, GetTypedArrayBuffer); + exports["getTypedArrayBufferValue"] = + Function::New(env, GetTypedArrayBufferValue); + exports["getTypedArrayElement"] = Function::New(env, GetTypedArrayElement); + exports["setTypedArrayElement"] = Function::New(env, SetTypedArrayElement); + exports["checkBufferContent"] = Function::New(env, CheckBufferContent); + + return exports; +} diff --git a/test/node-addon-api/test/typedarray.js b/test/node-addon-api/test/typedarray.js new file mode 100644 index 0000000..b6ae4a7 --- /dev/null +++ b/test/node-addon-api/test/typedarray.js @@ -0,0 +1,139 @@ +'use strict'; + +const assert = require('assert'); + +let runSharedArrayBufferTests = true; + +module.exports = require('./common').runTest(test); + +function test (binding) { + const testData = [ + ['int8', Int8Array, 1, new Int8Array([0, 124, 24, 44])], + ['uint8', Uint8Array, 1, new Uint8Array([0, 255, 2, 14])], + ['uint8_clamped', Uint8ClampedArray, 1, new Uint8ClampedArray([0, 256, 0, 255])], + ['int16', Int16Array, 2, new Int16Array([-32768, 32767, 1234, 42])], + ['uint16', Uint16Array, 2, new Uint16Array([0, 65535, 4, 12])], + ['int32', Int32Array, 4, new Int32Array([Math.pow(2, 31), Math.pow(-2, 31), 255, 4])], + ['uint32', Uint32Array, 4, new Uint32Array([0, Math.pow(2, 32), 24, 125])], + ['float32', Float32Array, 4, new Float32Array([0, 21, 34, 45])], + ['float64', Float64Array, 8, new Float64Array([0, 4124, 45, 90])] + ]; + + const bigIntTests = [ + ['bigint64', BigInt64Array, 8, new BigInt64Array([9007199254740991n, 9007199254740991n, 24n, 125n])], + ['biguint64', BigUint64Array, 8, new BigUint64Array([9007199254740991n, 9007199254740991n, 2345n, 345n])] + ]; + + bigIntTests.forEach(data => { + const length = 4; + const t = binding.typedarray.createTypedArray(data[0], length); + assert.ok(t instanceof data[1]); + assert.strictEqual(binding.typedarray.getTypedArrayType(t), data[0]); + assert.strictEqual(binding.typedarray.getTypedArrayLength(t), length); + assert.strictEqual(binding.typedarray.getTypedArraySize(t), data[2]); + assert.strictEqual(binding.typedarray.getTypedArrayByteOffset(t), 0); + assert.strictEqual(binding.typedarray.getTypedArrayByteLength(t), data[2] * length); + + t[3] = 11n; + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 11n); + binding.typedarray.setTypedArrayElement(t, 3, 22n); + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 22n); + assert.strictEqual(t[3], 22n); + + const nonEmptyTypedArray = binding.typedarray.createTypedArray(data[0], length, data[3].buffer); + binding.typedarray.checkBufferContent(nonEmptyTypedArray, data[3]); + }); + + testData.forEach(data => { + try { + const length = 4; + const t = binding.typedarray.createTypedArray(data[0], length); + assert.ok(t instanceof data[1]); + assert.strictEqual(binding.typedarray.getTypedArrayType(t), data[0]); + assert.strictEqual(binding.typedarray.getTypedArrayLength(t), length); + assert.strictEqual(binding.typedarray.getTypedArraySize(t), data[2]); + assert.strictEqual(binding.typedarray.getTypedArrayByteOffset(t), 0); + assert.strictEqual(binding.typedarray.getTypedArrayByteLength(t), data[2] * length); + + t[3] = 11; + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 11); + binding.typedarray.setTypedArrayElement(t, 3, 22); + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 22); + assert.strictEqual(t[3], 22); + + const b = binding.typedarray.getTypedArrayBuffer(t); + assert.ok(b instanceof ArrayBuffer); + const bAsValue = binding.typedarray.getTypedArrayBufferValue(t); + assert.ok(bAsValue instanceof ArrayBuffer); + assert.strictEqual(b, bAsValue); + } catch (e) { + console.log(data); + throw e; + } + }); + + testData.forEach(data => { + try { + const length = 4; + const offset = 8; + const b = new ArrayBuffer(offset + 64 * 4); + + const t = binding.typedarray.createTypedArray(data[0], length, b, offset); + assert.ok(t instanceof data[1]); + assert.strictEqual(binding.typedarray.getTypedArrayType(t), data[0]); + assert.strictEqual(binding.typedarray.getTypedArrayLength(t), length); + assert.strictEqual(binding.typedarray.getTypedArraySize(t), data[2]); + assert.strictEqual(binding.typedarray.getTypedArrayByteOffset(t), offset); + assert.strictEqual(binding.typedarray.getTypedArrayByteLength(t), data[2] * length); + + t[3] = 11; + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 11); + binding.typedarray.setTypedArrayElement(t, 3, 22); + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, 3), 22); + assert.strictEqual(t[3], 22); + + assert.strictEqual(binding.typedarray.getTypedArrayBuffer(t), b); + + const nonEmptyTypedArray = binding.typedarray.createTypedArray(data[0], length, data[3].buffer); + assert.strictEqual(binding.typedarray.checkBufferContent(nonEmptyTypedArray, data[3]), true); + } catch (e) { + console.log(data); + throw e; + } + }); + + assert.throws(() => { + binding.typedarray.createInvalidTypedArray(); + }, /Invalid (pointer passed as )?argument/); + + if (binding.hasSharedArrayBuffer && runSharedArrayBufferTests) { + const length = 4; + const sab = new SharedArrayBuffer(length); + /** @type {Int8Array} */ + let t; + + try { + t = binding.typedarray.createInt8TypedArrayFromSharedArrayBuffer(sab); + } catch (ex) { + if (ex.message === 'Invalid argument') { + console.warn(`The current version of Node.js (${process.version}) does not support creating TypedArrays on SharedArrayBuffers; skipping tests.`); + runSharedArrayBufferTests = false; + return; + } + + throw ex; + } + + assert.ok(t instanceof Int8Array); + assert.strictEqual(binding.typedarray.getTypedArrayType(t), 'int8'); + assert.strictEqual(binding.typedarray.getTypedArrayLength(t), length); + for (let i = 0; i < length; i++) { + const value = 2 ** (i + 1); + t[i] = value; + assert.strictEqual(binding.typedarray.getTypedArrayElement(t, i), value); + } + const bAsValue = binding.typedarray.getTypedArrayBufferValue(t); + assert.ok(bAsValue instanceof SharedArrayBuffer); + assert.strictEqual(bAsValue, sab); + } +} diff --git a/test/node-addon-api/test/value_type_cast.cc b/test/node-addon-api/test/value_type_cast.cc new file mode 100644 index 0000000..dfc03b3 --- /dev/null +++ b/test/node-addon-api/test/value_type_cast.cc @@ -0,0 +1,70 @@ +#include "common/test_helper.h" +#include "napi.h" + +using namespace Napi; + +#define TYPE_CAST_TYPES(V) \ + V(Boolean) \ + V(Number) \ + V(BigInt) \ + V(Date) \ + V(String) \ + V(Symbol) \ + V(Object) \ + V(Array) \ + V(ArrayBuffer) \ + V(TypedArray) \ + V(DataView) \ + V(Function) \ + V(Promise) + +// The following types are tested individually. +// External +// TypedArrayOf +// Buffer + +namespace { +#define V(Type) \ + void TypeCast##Type(const CallbackInfo& info) { USE(info[0].As()); } +TYPE_CAST_TYPES(V) + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER +V(SharedArrayBuffer) +#endif + +#undef V + +void TypeCastBuffer(const CallbackInfo& info) { + USE(info[0].As>()); +} + +void TypeCastExternal(const CallbackInfo& info) { + USE(info[0].As>()); +} + +void TypeCastTypeArrayOfUint8(const CallbackInfo& info) { + USE(info[0].As>()); +} +} // namespace + +Object InitValueTypeCast(Env env, Object exports) { + exports["external"] = External::New(env, nullptr); + +#define V(Type) exports["typeCast" #Type] = Function::New(env, TypeCast##Type); + TYPE_CAST_TYPES(V) + +#ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER + V(SharedArrayBuffer) +#endif + +#undef V + + exports["typeCastBuffer"] = Function::New(env, TypeCastBuffer); + exports["typeCastExternal"] = Function::New(env, TypeCastExternal); + exports["typeCastTypeArrayOfUint8"] = + Function::New(env, TypeCastTypeArrayOfUint8); + + return exports; +} + +NODE_API_MODULE(addon, InitValueTypeCast) diff --git a/test/node-addon-api/test/value_type_cast.js b/test/node-addon-api/test/value_type_cast.js new file mode 100644 index 0000000..274dd27 --- /dev/null +++ b/test/node-addon-api/test/value_type_cast.js @@ -0,0 +1,113 @@ +'use strict'; + +const assert = require('assert'); +const napiChild = require('./napi_child'); + +module.exports = require('./common').runTestWithBuildType(test); + +function test (buildType) { + const binding = require(`./build/${buildType}/binding_type_check.node`); + const testTable = { + typeCastBoolean: { + positiveValues: [true, false], + negativeValues: [{}, [], 1, 1n, 'true', null, undefined] + }, + typeCastNumber: { + positiveValues: [1, NaN], + negativeValues: [{}, [], true, 1n, '1', null, undefined] + }, + typeCastBigInt: { + positiveValues: [1n], + negativeValues: [{}, [], true, 1, '1', null, undefined] + }, + typeCastDate: { + positiveValues: [new Date()], + negativeValues: [{}, [], true, 1, 1n, '1', null, undefined] + }, + typeCastString: { + positiveValues: ['', '1'], + negativeValues: [{}, [], true, 1, 1n, null, undefined] + }, + typeCastSymbol: { + positiveValues: [Symbol('1')], + negativeValues: [{}, [], true, 1, 1n, '1', null, undefined] + }, + typeCastObject: { + positiveValues: [{}, new Date(), []], + negativeValues: [true, 1, 1n, '1', null, undefined] + }, + typeCastArray: { + positiveValues: [[1]], + negativeValues: [{}, true, 1, 1n, '1', null, undefined] + }, + typeCastArrayBuffer: { + positiveValues: [new ArrayBuffer(0)], + negativeValues: [new Uint8Array(1), new SharedArrayBuffer(0), {}, [], null, undefined] + }, + typeCastTypedArray: { + positiveValues: [new Uint8Array(0)], + negativeValues: [new ArrayBuffer(1), {}, [], null, undefined] + }, + typeCastDataView: { + positiveValues: [new DataView(new ArrayBuffer(0))], + negativeValues: [new ArrayBuffer(1), null, undefined] + }, + typeCastFunction: { + positiveValues: [() => {}], + negativeValues: [{}, null, undefined] + }, + typeCastPromise: { + positiveValues: [Promise.resolve()], + // napi_is_promise distinguishes Promise and thenable. + negativeValues: [{ then: () => {} }, null, undefined] + }, + typeCastBuffer: { + positiveValues: [Buffer.from('')], + // napi_is_buffer doesn't distinguish between Buffer and TypedArrays. + negativeValues: [new ArrayBuffer(1), null, undefined] + }, + typeCastExternal: { + positiveValues: [binding.external], + negativeValues: [{}, null, undefined] + }, + typeCastTypeArrayOfUint8: { + // TypedArrayOf::CheckCast doesn't distinguish between Uint8ClampedArray and Uint8Array. + positiveValues: [new Uint8Array(0), new Uint8ClampedArray(0)], + negativeValues: [new Int8Array(1), null, undefined] + } + }; + + if ('typeCastSharedArrayBuffer' in binding) { + testTable.typeCastSharedArrayBuffer = { + positiveValues: [new SharedArrayBuffer(0)], + negativeValues: [new Uint8Array(1), new ArrayBuffer(0), {}, [], null, undefined] + }; + } + + if (process.argv[2] === 'child') { + child(binding, testTable, process.argv[3], process.argv[4], parseInt(process.argv[5])); + return; + } + + for (const [methodName, { positiveValues, negativeValues }] of Object.entries(testTable)) { + for (const idx of positiveValues.keys()) { + const { status } = napiChild.spawnSync(process.execPath, [__filename, 'child', methodName, 'positiveValues', idx]); + assert.strictEqual(status, 0, `${methodName} positive value ${idx} test failed`); + } + for (const idx of negativeValues.keys()) { + const { status, signal, stderr } = napiChild.spawnSync(process.execPath, [__filename, 'child', methodName, 'negativeValues', idx], { + encoding: 'utf8' + }); + if (process.platform === 'win32') { + assert.strictEqual(status, 128 + 6 /* SIGABRT */, `${methodName} negative value ${idx} test failed`); + } else { + assert.strictEqual(signal, 'SIGABRT', `${methodName} negative value ${idx} test failed`); + } + assert.ok(stderr.match(/FATAL ERROR: .*::CheckCast.*/)); + } + } +} + +async function child (binding, testTable, methodName, type, idx) { + binding[methodName](testTable[methodName][type][idx]); +} diff --git a/test/node-addon-api/test/version_management.cc b/test/node-addon-api/test/version_management.cc new file mode 100644 index 0000000..6496f57 --- /dev/null +++ b/test/node-addon-api/test/version_management.cc @@ -0,0 +1,28 @@ +#include "napi.h" + +using namespace Napi; + +Value getNapiVersion(const CallbackInfo& info) { + Napi::Env env = info.Env(); + uint32_t napi_version = VersionManagement::GetNapiVersion(env); + return Number::New(env, napi_version); +} + +Value getNodeVersion(const CallbackInfo& info) { + Napi::Env env = info.Env(); + const napi_node_version* node_version = + VersionManagement::GetNodeVersion(env); + Object version = Object::New(env); + version.Set("major", Number::New(env, node_version->major)); + version.Set("minor", Number::New(env, node_version->minor)); + version.Set("patch", Number::New(env, node_version->patch)); + version.Set("release", String::New(env, node_version->release)); + return version; +} + +Object InitVersionManagement(Env env) { + Object exports = Object::New(env); + exports["getNapiVersion"] = Function::New(env, getNapiVersion); + exports["getNodeVersion"] = Function::New(env, getNodeVersion); + return exports; +} diff --git a/test/node-addon-api/test/version_management.js b/test/node-addon-api/test/version_management.js new file mode 100644 index 0000000..06d4f9c --- /dev/null +++ b/test/node-addon-api/test/version_management.js @@ -0,0 +1,29 @@ +'use strict'; + +const assert = require('assert'); + +module.exports = require('./common').runTest(test); + +function parseVersion () { + const expected = {}; + expected.napi = parseInt(process.versions.napi); + expected.release = process.release.name; + const nodeVersion = process.versions.node.split('.'); + expected.major = parseInt(nodeVersion[0]); + expected.minor = parseInt(nodeVersion[1]); + expected.patch = parseInt(nodeVersion[2]); + return expected; +} + +function test (binding) { + const expected = parseVersion(); + + const napiVersion = binding.version_management.getNapiVersion(); + assert.strictEqual(napiVersion, expected.napi); + + const nodeVersion = binding.version_management.getNodeVersion(); + assert.strictEqual(nodeVersion.major, expected.major); + assert.strictEqual(nodeVersion.minor, expected.minor); + assert.strictEqual(nodeVersion.patch, expected.patch); + assert.strictEqual(nodeVersion.release, expected.release); +} diff --git a/test/node-addon-api/tests.cmake b/test/node-addon-api/tests.cmake new file mode 100644 index 0000000..7486333 --- /dev/null +++ b/test/node-addon-api/tests.cmake @@ -0,0 +1,90 @@ +# Generated by tools/sync_node_addon_api.py from node-addon-api 8.9.2. +# Do not edit. +set(QJSNAPI_NAA_VERSION 8.9.2) +set(QJSNAPI_NAA_BUILD_SOURCES "addon.cc" "addon_data.cc" "array_buffer.cc" "async_context.cc" "async_progress_queue_worker.cc" "async_progress_worker.cc" "async_worker.cc" "async_worker_persistent.cc" "basic_types/array.cc" "basic_types/boolean.cc" "basic_types/number.cc" "basic_types/value.cc" "bigint.cc" "callbackInfo.cc" "date.cc" "binding.cc" "buffer_no_external.cc" "buffer.cc" "callbackscope.cc" "dataview/dataview.cc" "dataview/dataview_read_write.cc" "env_cleanup.cc" "env_misc.cc" "error.cc" "error_handling_for_primitives.cc" "external.cc" "finalizer_order.cc" "function.cc" "function_reference.cc" "handlescope.cc" "maybe/check.cc" "movable_callbacks.cc" "memory_management.cc" "name.cc" "globalObject/global_object_delete_property.cc" "globalObject/global_object_has_own_property.cc" "globalObject/global_object_set_property.cc" "globalObject/global_object_get_property.cc" "globalObject/global_object.cc" "object/delete_property.cc" "object/finalizer.cc" "object/get_property.cc" "object/has_own_property.cc" "object/has_property.cc" "object/object.cc" "object/object_freeze_seal.cc" "object/set_property.cc" "object/subscript_operator.cc" "promise.cc" "run_script.cc" "shared_array_buffer.cc" "symbol.cc" "threadsafe_function/threadsafe_function_ctx.cc" "threadsafe_function/threadsafe_function_exception.cc" "threadsafe_function/threadsafe_function_existing_tsfn.cc" "threadsafe_function/threadsafe_function_ptr.cc" "threadsafe_function/threadsafe_function_sum.cc" "threadsafe_function/threadsafe_function_unref.cc" "threadsafe_function/threadsafe_function.cc" "type_taggable.cc" "typed_threadsafe_function/typed_threadsafe_function_ctx.cc" "typed_threadsafe_function/typed_threadsafe_function_exception.cc" "typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.cc" "typed_threadsafe_function/typed_threadsafe_function_ptr.cc" "typed_threadsafe_function/typed_threadsafe_function_sum.cc" "typed_threadsafe_function/typed_threadsafe_function_unref.cc" "typed_threadsafe_function/typed_threadsafe_function.cc" "typedarray.cc" "objectwrap.cc" "objectwrap_constructor_exception.cc" "objectwrap_function.cc" "objectwrap_removewrap.cc" "objectwrap_multiple_inheritance.cc" "object_reference.cc" "reference.cc" "version_management.cc" "thunking_manual.cc" "object/object_deprecated.cc") +set(QJSNAPI_NAA_SWALLOWEXCEPT_SOURCES "binding-swallowexcept.cc" "error.cc") +set(QJSNAPI_NAA_EXCEPT_ALL_SOURCES "except_all.cc") +set(QJSNAPI_NAA_TYPE_CHECK_SOURCES "value_type_cast.cc") + +# qjsnapi_naa_test(): one CTest per test module. +qjsnapi_naa_test(addon) +qjsnapi_naa_test(addon_data) +qjsnapi_naa_test(array_buffer) +qjsnapi_naa_test(async_context) +qjsnapi_naa_test(async_progress_queue_worker) +qjsnapi_naa_test(async_progress_worker) +qjsnapi_naa_test(async_worker) +qjsnapi_naa_test(async_worker_nocallback) +qjsnapi_naa_test(async_worker_persistent) +qjsnapi_naa_test(basic_types/array) +qjsnapi_naa_test(basic_types/boolean) +qjsnapi_naa_test(basic_types/number) +qjsnapi_naa_test(basic_types/value) +qjsnapi_naa_test(bigint) +qjsnapi_naa_test(buffer) +qjsnapi_naa_test(callbackInfo) +qjsnapi_naa_test(callbackscope) +qjsnapi_naa_test(dataview/dataview) +qjsnapi_naa_test(dataview/dataview_read_write) +qjsnapi_naa_test(date) +qjsnapi_naa_test(env_cleanup) +qjsnapi_naa_test(env_misc) +qjsnapi_naa_test(error) +qjsnapi_naa_test(error_handling_for_primitives) +# skipped: error_terminating_environment (needs worker_threads) +qjsnapi_naa_test(except_all) +# skipped: exports (checks the npm package's index.js (semver, package.json), not Node-API) +qjsnapi_naa_test(external) +qjsnapi_naa_test(finalizer_order) +qjsnapi_naa_test(function) +qjsnapi_naa_test(function_reference) +qjsnapi_naa_test(globalObject/global_object_delete_property) +qjsnapi_naa_test(globalObject/global_object_get_property) +qjsnapi_naa_test(globalObject/global_object_has_own_property) +qjsnapi_naa_test(globalObject/global_object_set_property) +qjsnapi_naa_test(handlescope) +qjsnapi_naa_test(maybe) +qjsnapi_naa_test(memory_management) +qjsnapi_naa_test(movable_callbacks) +qjsnapi_naa_test(name) +qjsnapi_naa_test(object/delete_property) +qjsnapi_naa_test(object/finalizer) +qjsnapi_naa_test(object/get_property) +qjsnapi_naa_test(object/has_own_property) +qjsnapi_naa_test(object/has_property) +qjsnapi_naa_test(object/object) +qjsnapi_naa_test(object/object_deprecated) +qjsnapi_naa_test(object/object_freeze_seal) +qjsnapi_naa_test(object/set_property) +qjsnapi_naa_test(object/subscript_operator) +qjsnapi_naa_test(object_reference) +qjsnapi_naa_test(objectwrap) +qjsnapi_naa_test(objectwrap_constructor_exception) +qjsnapi_naa_test(objectwrap_function) +qjsnapi_naa_test(objectwrap_multiple_inheritance) +qjsnapi_naa_test(objectwrap_removewrap) +# skipped: objectwrap_worker_thread (needs worker_threads) +qjsnapi_naa_test(promise) +qjsnapi_naa_test(reference) +qjsnapi_naa_test(run_script) +qjsnapi_naa_test(shared_array_buffer) +qjsnapi_naa_test(symbol) +qjsnapi_naa_test(threadsafe_function/threadsafe_function) +qjsnapi_naa_test(threadsafe_function/threadsafe_function_ctx) +qjsnapi_naa_test(threadsafe_function/threadsafe_function_exception) +qjsnapi_naa_test(threadsafe_function/threadsafe_function_existing_tsfn) +qjsnapi_naa_test(threadsafe_function/threadsafe_function_ptr) +qjsnapi_naa_test(threadsafe_function/threadsafe_function_sum) +qjsnapi_naa_test(threadsafe_function/threadsafe_function_unref) +qjsnapi_naa_test(type_taggable) +qjsnapi_naa_test(typed_threadsafe_function/typed_threadsafe_function) +qjsnapi_naa_test(typed_threadsafe_function/typed_threadsafe_function_ctx) +qjsnapi_naa_test(typed_threadsafe_function/typed_threadsafe_function_exception) +qjsnapi_naa_test(typed_threadsafe_function/typed_threadsafe_function_existing_tsfn) +qjsnapi_naa_test(typed_threadsafe_function/typed_threadsafe_function_ptr) +qjsnapi_naa_test(typed_threadsafe_function/typed_threadsafe_function_sum) +qjsnapi_naa_test(typed_threadsafe_function/typed_threadsafe_function_unref) +qjsnapi_naa_test(typedarray-bigint) +qjsnapi_naa_test(typedarray) +qjsnapi_naa_test(value_type_cast) +qjsnapi_naa_test(version_management) diff --git a/test/node/common/assert.js b/test/node/common/assert.js index 0ef189c..cd19d5f 100644 --- a/test/node/common/assert.js +++ b/test/node/common/assert.js @@ -1,6 +1,8 @@ 'use strict'; -// Subset of Node.js `assert` (strict mode semantics) used by the vendored -// js-native-api tests. Registered as the 'assert' builtin by ./index.js. +// Subset of Node.js `assert` used by the vendored Node.js and node-addon-api +// tests: strict comparisons, plus the legacy loose equal / notEqual +// (deepEqual stays strict). Registered as the 'assert' builtin by ./index.js +// and by the node-addon-api preload. class AssertionError extends Error { constructor(message) { @@ -189,6 +191,28 @@ function match(string, regexp, message) { } } +// Legacy (loose) assert.equal / notEqual: ==, with NaN equal to NaN. +function equal(actual, expected, message) { + // eslint-disable-next-line eqeqeq + if (!(actual == expected || (actual !== actual && expected !== expected))) { + fail(message || `${inspect(actual)} == ${inspect(expected)}`); + } +} + +function notEqual(actual, expected, message) { + // eslint-disable-next-line eqeqeq + if (actual == expected || (actual !== actual && expected !== expected)) { + fail(message || `${inspect(actual)} != ${inspect(expected)}`); + } +} + +function ifError(value) { + if (value !== null && value !== undefined) { + if (value instanceof Error) throw value; + fail(`ifError got unwanted exception: ${inspect(value)}`); + } +} + function assert(value, message) { ok(value, message); } Object.assign(assert, { AssertionError, @@ -196,8 +220,8 @@ Object.assign(assert, { fail, strictEqual, notStrictEqual, - equal: strictEqual, - notEqual: notStrictEqual, + equal, + notEqual, deepStrictEqual, notDeepStrictEqual, deepEqual: deepStrictEqual, @@ -206,6 +230,7 @@ Object.assign(assert, { doesNotThrow, rejects, match, + ifError, }); assert.strict = assert; diff --git a/test/unit/test_embed.c b/test/unit/test_embed.c index aa86d3a..f538724 100644 --- a/test/unit/test_embed.c +++ b/test/unit/test_embed.c @@ -76,8 +76,15 @@ static void check_lifetime(napi_env env, napi_value exports) { EXPECT(napi_create_reference(env, ext, 0, &weak) == napi_ok); EXPECT(napi_close_handle_scope(env, scope) == napi_ok); - /* The external is dead: the weak reference sees it at once ... */ - napi_value v = (napi_value)(void *)0x1; + /* Like a V8 weak handle, the target survives until the kept objects are + * cleared (end of the macrotask, gc()) ... */ + napi_value v = NULL; + EXPECT(napi_open_handle_scope(env, &scope) == napi_ok); + EXPECT(napi_get_reference_value(env, weak, &v) == napi_ok && v != NULL); + EXPECT(napi_close_handle_scope(env, scope) == napi_ok); + qjsnapi_host_clear_kept_objects(g_host); + /* ... then it is dead: the weak reference sees it at once ... */ + v = (napi_value)(void *)0x1; EXPECT(napi_get_reference_value(env, weak, &v) == napi_ok && v == NULL); EXPECT(napi_delete_reference(env, weak) == napi_ok); /* ... but its finalizer only runs from the event loop, after a GC. */ diff --git a/tools/sync_node_addon_api.py b/tools/sync_node_addon_api.py new file mode 100644 index 0000000..e725225 --- /dev/null +++ b/tools/sync_node_addon_api.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python3 +"""Vendors the node-addon-api test suite into test/node-addon-api. + +Usage: tools/sync_node_addon_api.py + +Copies the headers (napi.h, napi-inl.h, napi-inl.deprecated.h), the license +and the test directory of a node-addon-api release, applies PATCHES (each +with its reason) and writes test/node-addon-api/tests.cmake: the sources of +the eight bindings of test/binding.gyp and one CTest per test module (the +modules that upstream test/index.js would run). test/node-addon-api/harness +holds the quickjs-napi files laid over the copy at build time (common +helpers, runner); it is not touched here. +""" +import ast +import os +import shutil +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +DEST = os.path.join(ROOT, "test", "node-addon-api") + +HEADERS = ["napi.h", "napi-inl.h", "napi-inl.deprecated.h", "LICENSE.md"] + +# Test directories not copied at all. +EXCLUDED = { + # Both build an addon with `npm install` (node-gyp, network). + "addon_build": "builds an addon with npm install", + "require_basic_finalizers": "builds an addon with npm install " + "(and runs only with NAPI_EXPERIMENTAL)", +} + +# Test modules that are copied but not run, with the reason. +SKIPPED = { + "exports": "checks the npm package's index.js (semver, package.json), " + "not Node-API", + "objectwrap_worker_thread": "needs worker_threads", + "error_terminating_environment": "needs worker_threads", +} + +# (relative path under test/, old, new, reason). A patch must apply exactly +# once; the sync fails otherwise, so a changed upstream file is noticed. +_NO_ASYNC_HOOKS = ( + " if (nodeVersion >= 8) {\n", + " if (false) { // quickjs-napi: no async_hooks\n", + "no async_hooks: the tests take their pre-Node.js-8 path, which runs the " + "same native code without checking hook events") +PATCHES = [ + ("async_context.js",) + _NO_ASYNC_HOOKS, + ("async_progress_queue_worker.js",) + _NO_ASYNC_HOOKS, + ("async_progress_worker.js",) + _NO_ASYNC_HOOKS, + ("async_worker.js",) + _NO_ASYNC_HOOKS, + ("callbackscope.js",) + _NO_ASYNC_HOOKS, + ("async_worker.js", + " binding.asyncworker.doWork(true, null, function (e) {\n", + " // quickjs-napi: {} instead of null, as in the async_hooks path\n" + " binding.asyncworker.doWork(true, {}, function (e) {\n", + "the pre-async_hooks path passes a null resource, which the " + "NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS binding rejects with a fatal " + "error (Object::CheckCast); Node.js never runs that path"), + ("function_reference.js", + "const asyncHook = require('async_hooks');\n", + "", + "no async_hooks"), + ("function_reference.js", + " await canCallAsyncFunctionWithDifferentOverloads(binding);\n", + " // quickjs-napi: canCallAsyncFunctionWithDifferentOverloads checks " + "async_hooks events.\n", + "no async_hooks: that case only checks the hook events"), + ("array_buffer.js", + " const mem = new WebAssembly.Memory({ initial: 1 });\n" + " binding.arraybuffer.checkDetachUpdatesData(mem.buffer, () => " + "mem.grow(1));\n", + " // quickjs-napi: no WebAssembly; ArrayBuffer.prototype.transfer\n" + " // detaches the buffer from JavaScript as well.\n" + " const ab = new ArrayBuffer(65536);\n" + " binding.arraybuffer.checkDetachUpdatesData(ab, () => " + "ab.transfer());\n", + "no WebAssembly in QuickJS"), +] + +# V8 error messages matched by regular expression: QuickJS throws the same +# error type with its own wording. +_V8_MESSAGES = [ + "/Cannot assign to read only property 'x' of object '#/", + "/Cannot add property w, object is not extensible/", + "/Cannot delete property 'x' of #/", +] + + +def _message_patches(): + out = [] + for msg in _V8_MESSAGES: + out.append(("object/object_freeze_seal.js", "}, %s);" % msg, + "}, TypeError); // quickjs-napi: V8 message %s" % msg, + "V8-specific error message")) + return out + + +def copy_tree(src, dst): + for dirpath, dirnames, filenames in os.walk(src): + rel = os.path.relpath(dirpath, src) + dirnames[:] = [d for d in dirnames + if not (rel == "." and (d in EXCLUDED or d == "build"))] + os.makedirs(os.path.join(dst, rel), exist_ok=True) + for f in filenames: + shutil.copy2(os.path.join(dirpath, f), os.path.join(dst, rel, f)) + + +def apply_patches(test_dir, patches): + for rel, old, new, reason in patches: + path = os.path.join(test_dir, rel) + try: + with open(path, encoding="utf-8") as f: + text = f.read() + except OSError as e: + raise SystemExit("cannot read %s: %s" % (path, e)) + count = text.count(old) + if count == 0: + raise SystemExit("patch for %s (%s) does not apply" % (rel, reason)) + if rel == "object/object_freeze_seal.js": + text = text.replace(old, new) # the same check appears twice + elif count != 1: + raise SystemExit("patch for %s (%s) is ambiguous" % (rel, reason)) + else: + text = text.replace(old, new) + with open(path, "w", encoding="utf-8") as f: + f.write(text) # OSError: reported by main() + + +def test_modules(test_dir): + """The modules upstream test/index.js runs (loadTestModules).""" + skip_top = {"binding.cc", "binding.gyp", "build", "common", + "child_processes", "napi_child.js", "testUtil.js", + "thunking_manual.cc", "thunking_manual.js", "index.js"} + out = [] + + def walk(directory, pre): + for f in sorted(os.listdir(directory)): + if (directory == test_dir and f in skip_top) or f.startswith("."): + continue + full = os.path.join(directory, f) + if os.path.isdir(full): + if os.path.exists(os.path.join(full, "index.js")): + out.append(pre + f) + else: + walk(full, pre + f + "/") + elif f.endswith(".js"): + out.append(pre + f[:-3]) + + walk(test_dir, "") + return out + + +def cmake_list(items): + return " ".join('"%s"' % i for i in items) + + +def main(): + try: + sync() + except (OSError, shutil.Error) as e: + # A failed copy or write: the tree may be partial, run the sync again. + raise SystemExit("sync failed: %s" % e) + + +def sync(): + if len(sys.argv) != 2: + raise SystemExit(__doc__) + src = sys.argv[1] + if not os.path.isfile(os.path.join(src, "napi.h")): + raise SystemExit("not a node-addon-api checkout: %s" % src) + try: + with open(os.path.join(src, "package.json"), encoding="utf-8") as f: + version = next(l.split('"')[3] for l in f + if l.strip().startswith('"version"')) + with open(os.path.join(src, "test", "binding.gyp"), + encoding="utf-8") as f: + gyp = ast.literal_eval(f.read()) + except (OSError, StopIteration, ValueError, SyntaxError) as e: + raise SystemExit("cannot read the node-addon-api checkout: %s" % e) + + # Fresh copy of the vendored files; the harness stays. + os.makedirs(DEST, exist_ok=True) + for entry in os.listdir(DEST): + if entry == "harness": + continue + path = os.path.join(DEST, entry) + if os.path.isdir(path): + shutil.rmtree(path) + else: + os.remove(path) + for h in HEADERS: + shutil.copy2(os.path.join(src, h), os.path.join(DEST, h)) + test_dir = os.path.join(DEST, "test") + copy_tree(os.path.join(src, "test"), test_dir) + patches = PATCHES + _message_patches() + apply_patches(test_dir, patches) + + variables = gyp["target_defaults"]["variables"] + build_sources = list(variables["build_sources"]) + # disable_deprecated is not set: upstream adds object_deprecated.cc. + build_sources.append("object/object_deprecated.cc") + modules = test_modules(test_dir) + + lines = [ + "# Generated by tools/sync_node_addon_api.py from node-addon-api %s." + % version, + "# Do not edit.", + "set(QJSNAPI_NAA_VERSION %s)" % version, + "set(QJSNAPI_NAA_BUILD_SOURCES %s)" % cmake_list(build_sources), + "set(QJSNAPI_NAA_SWALLOWEXCEPT_SOURCES %s)" + % cmake_list(variables["build_sources_swallowexcept"]), + "set(QJSNAPI_NAA_EXCEPT_ALL_SOURCES %s)" + % cmake_list(variables["build_sources_except_all"]), + "set(QJSNAPI_NAA_TYPE_CHECK_SOURCES %s)" + % cmake_list(variables["build_sources_type_check"]), + "", + "# qjsnapi_naa_test(): one CTest per test module.", + ] + for m in modules: + if m in SKIPPED: + lines.append("# skipped: %s (%s)" % (m, SKIPPED[m])) + else: + lines.append("qjsnapi_naa_test(%s)" % m) + with open(os.path.join(DEST, "tests.cmake"), "w", encoding="utf-8") as f: + f.write("\n".join(lines) + "\n") + # Not "VERSION": DEST is on the include path, and on case-insensitive + # file systems (macOS, Windows) it would shadow the C++ header. + with open(os.path.join(DEST, "NODE_ADDON_API_VERSION"), "w", + encoding="utf-8") as f: + f.write(version + "\n") + print("node-addon-api %s: %d test modules, %d skipped, %d patches" + % (version, len(modules) - len(SKIPPED), len(SKIPPED), len(patches))) + + +if __name__ == "__main__": + main()